blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9c6b0a118028490373bda0feda9e1244111f3408 | hemangbehl/Data-Structures-Algorithms_practice | /session4/detectLoopLinkedList.py | 1,641 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None #point to null
class LinkedList:
def __init__(self):
self.head = None #by default head is none
def printList(self):
curr = self.head
print ("#start#")
while curr!=None: #while loop until it reaches the end
print (curr.data)
curr = curr.next #go to next node
def insertHead(self, ele):
new = Node(ele)
new.next = self.head
self.head = new
def insertEnd(self, ele):
new = Node(ele)
new.next = None
curr = self.head
#check id list is empty
if self.head == None:
self.head = new
print("Inserted at head as list was empty")
return
else:
while (curr!=None):
prev = curr
curr = curr.next
#at end of loop, curr is none and prev has some value
prev.next = new
new.next = curr
print ("Inserted at the end")
return
#new function
def detectLoop(head):
if not head or not head.next: return False
slow = head.next
fast = head.next.next
while fast and fast.next:
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
#code
ll = LinkedList()
ll.head = Node(1)
second = Node(2)
third = Node(3)
#linking lists
ll.head.next = second
second.next = second
# ll.insertHead(11)
# ll.printList()
# ll.insertEnd(100)
# ll.printList()
print( detectLoop(ll.head))
| true |
7fe72a736e4a241e5ff0237f2085894d74b5de72 | hemangbehl/Data-Structures-Algorithms_practice | /leetcode_session2/linkedlist_segregate_even_odd.py | 2,127 | 4.34375 | 4 | class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
curr = self.head
print("#start#")
while curr:
print(curr.data)
curr = curr.next
def segregate_even_odd(self):
curr = self.head
if not curr:
return
odd = 0
even = 0
if curr.data%2 == 0: #even
even = curr
else: #odd
odd = curr
while curr.next != None:
if curr.next.data %2 ==0: #next is even
if odd==0: #no odd before, curr is even and next is also even
even = curr.next #set even to new even
curr = curr.next #go next
else: #current node is an odd no. and next is even
#need to swap
temp = curr.next.next
curr.next.next = odd #next even will point to odd
if even == 0: #no even before, then next node will be set as head
self.head = curr.next
else: #even existed before
#even will point to new even
even.next = curr.next
even = curr.next #set new even
curr.next = temp
#we do not advance curr
else: #next node is an odd no.
#advance forward
curr = curr.next
return
# Driver program
llist1 = LinkedList()
llist1.push(6)
llist1.push(5)
llist1.push(4)
llist1.push(3)
llist1.push(2)
llist1.push(1)
llist1.printList()
llist1.segregate_even_odd()
llist1.printList() | true |
7af93d9feb7c895a9a6131e554db2f0d5bc6b875 | GenaroVS/DSA | /algorithms/array/rotate.py | 1,057 | 4.21875 | 4 | """
Write a function that rotates a list by k elements. For example, [1, 2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2]. Try solving this without creating a copy of the list. How many swap or move operations do you need?
"""
from typing import Sequence
def rotate(nums, k):
N = len(nums)
k = N - (abs(k) % N) if k < 0 else k % N
for _ in range(k):
first_element = nums[0]
for i in range(N - 1):
nums[i] = nums[i + 1]
nums[N - 1] = first_element
return nums
def rotate2(nums, k):
N = len(nums)
k = N - (abs(k) % N) if k < 0 else k % N
reverse(nums, 0, k - 1)
reverse(nums, k, N - 1)
reverse(nums, 0, N - 1)
return nums
def reverse(nums, i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
print(rotate2([1,2,3,4,5,6], 2))
print(rotate2([1,2,3,4,5,6], 4))
print(rotate2([1,2,3,4,5,6], 6)) # should equal k = 1
print(rotate2([1,2,3,4,5,6], 8)) # should equal k = 2
print(rotate2([1,2,3,4,5,6], -2)) # should equal k = 4
| false |
a267c4126b58d272a62aa1c866e0bf36f766bdda | tannervalentine/pythonAssignments | /If Problems Lab/integerSorter.py | 1,061 | 4.15625 | 4 | #whoever reads this i know this is overcomplicated that's how it worked in my BRAIN
int1 = int(input("Enter an integer."))
int2 = int(input("Please enter another."))
int3 = int(input("Please enter one more integer."))
if int1<=int2 and int1<=int3:
sort1 = int1
elif int2<=int1 and int2<=int3:
sort1 = int2
elif int3<=int1 and int3<=int2:
sort1 = int3
if sort1 == int1:
if int2<=int3:
sort2 = int2
else:
sort2 = int3
elif sort1 == int2:
if int1<=int3:
sort2 = int1
else:
sort2 = int3
elif sort1 == int3:
if int1<=int2:
sort2 = int1
else:
sort2 = int2
if sort1 == int1 and sort2 == int2:
sort3 = int3
elif sort1 == int2 and sort2 == int3:
sort3 = int1
elif sort1 == int3 and sort2 == int1:
sort3 = int2
elif sort1 == int1 and sort2 == int3:
sort3 = int2
elif sort1 == int2 and sort2 == int1:
sort3 = int3
elif sort1 == int3 and sort2 == int2:
sort3 = int1
print("Your integers in ascending order are "+str(sort1)+", "+str(sort2)+", "+str(sort3)+".")
| false |
49435661a99e9de54b28d6b2b96b9c15ccb73c98 | RodolpheBeloncle/100-days-Python | /battle_Hand(rock-paper_scissors).py | 1,423 | 4.125 | 4 |
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# first solution
while True:
# list of possibilities
choices = [rock,paper,scissors]
# Player choice
start_battle = int(input('''
What do you choose ? :
Type O for Rock
Type 1 for Paper
Type 2 for Scissors
'''))
if start_battle > len(choices)-1 :
print("You have to choose a number between 0 and 2 nothing else !!")
start_battle
# numbers choosen of each player
playerNumber = start_battle
computerNumber = random.randint(0,2)
# player hand
player_Choice = choices[int(start_battle)]
print( player_Choice)
# computer hand
computer_Choice = choices[computerNumber]
print(computer_Choice)
# conditions to win
if playerNumber == 0 and computerNumber == 2:
print("You win !!")
start_battle
elif playerNumber == 2 and computerNumber == 1:
print("You win !!")
start_battle
elif playerNumber == 1 and computerNumber == 0:
print("You win !!")
start_battle
elif playerNumber == computerNumber:
print("It's a draw!!")
start_battle
else:
print("You loose!!")
break
| false |
f5a4cd30089c52d8c27b974e512d10c5e4852736 | vakhnin/base-python | /lesson02/task02.py | 993 | 4.375 | 4 | """
Для списка реализовать обмен значений соседних элементов,
т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input().
"""
def main():
arr = []
while True:
item = input('Введите элемент списка (наберите "exit" для выхода): ')
if item == 'exit':
break
arr.append(item)
print('Исходный список:')
print(arr)
for i in range(int(len(arr) / 2)):
arr[2 * i], arr[2 * i + 1] = arr[2 * i + 1], arr[2 * i]
print('Обработанный список:')
print(arr)
if __name__ == '__main__':
main()
| false |
b93615ac25a54bba0657a0a455441b833e4dd46b | vakhnin/base-python | /lesson01/task02.py | 728 | 4.125 | 4 | """
Пользователь вводит время в секундах.
Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
Используйте форматирование строк.
"""
def main():
while True:
secs = int(input('Введите количество секунд'
' (целое положительное число): '))
if secs >= 0:
break
mins = secs // 60
secs = secs % 60
hour = mins // 60
mins = mins % 60
print('Введены чч:мм:сс')
print(f'{hour}:{mins}:{secs}')
if __name__ == '__main__':
main()
| false |
0a895501af1455de4092e9db71816108d71c5db6 | jamesbrown5292/nltk | /searching-counting-text.py | 911 | 4.21875 | 4 | import time
#import content form nltk book
from nltk.book import *
#Concordance view shows us a word plus some context
word = input("Enter a word and we will find it in Moby Dick ")
text1.concordance(word)
#Using the .simlar method shows words that appear in a similar context as the word
word = input("\n Enter a word and I will show words that occur in a similar context in Moby Dick ")
text1.similar(word)
input("\n Let's see how the context differs in Jane Austen. Press any key")
text2.similar(word)
#common_contexts shows us the conetxt shared by two or more words
word1 = input("\n Enter two words and we can look at the context shared by these two words in Moby Dick. Enter word 1: ")
word2 = input("\nEnter word 2: ")
text1.common_contexts([word1, word2])
#Generate texts in a syle with .generate()
print("Now, let's generate a text in the style of the inaugural address corpus")
text4.generate() | true |
2d81b2e919323a4a4f30c368b7540976fbec4777 | Arno98/Python-3-Basics | /Chapter 9 (Try - Except - Else)/try_except_2_3.py | 925 | 4.21875 | 4 | while True:
try:
a = int(input("Enter a number: "))
b = int(input("Enter a number: "))
except ValueError:
print("You do not enter a number.Please try again.")
else:
print(a * b)
exit_text = input("Do you want exit?(enter 'y' or 'n') ")
if exit_text == 'n':
continue
elif exit_text == 'y':
break
else:
print("You must enter 'y' or 'n'")
print("\n")
def file_function(filename):
try:
with open(filename) as filetext:
read_file = filetext.read()
except FileNotFoundError:
print("The file " + "'" + filename + "'" + " is not found!")
else:
print(read_file.rstrip())
words = read_file.split()
numbers_of_words = len(words)
print("'" + filename + "'" + " consist of " + str(numbers_of_words) + " words.")
print("\n")
files = ["guest.txt", "guest_book.txt", "Learn Python.txt", "Wonderland.txt"]
for filename in files:
file_function(filename)
| true |
ea86b935509a0782153099dc71a4a92ec9061117 | Arno98/Python-3-Basics | /Chapter 9 (Try - Except - Else)/try_except_3.py | 998 | 4.125 | 4 | try:
print(10 / 0)
except ZeroDivisionError:
print("You can not divide by zero!")
print("\n")
question = input("Enter a number: ")
try:
number = int(question)
except ValueError:
print("You can enter only a number!")
else:
print(number)
print("\n")
file_book = "The Farm.txt"
try:
with open(file_book) as book:
book.read()
except FileNotFoundError:
print("Sorry, but the file " + "'" + file_book + "'" + " does not exist.")
print("\n")
file_work = "Student Work.txt"
try:
with open(file_work) as student_work:
work_read = student_work.read()
except FileNotFoundError:
print("Sorry, but the file " + "'" + file_work + "'" + " does nor exist.")
else:
words = work_read.split()
number_of_words = len(words)
number_of_getman = words.count('гетьман')
print("The file " + "'" + file_work + "'" + " has about " + str(number_of_words) + " words.")
print("Word " + "'гетьман'" + " was writen about " + str(number_of_getman))
| true |
1cd38a41a56220ca7b51a0f6b5d8dde61d53c721 | aryan-upa/Python-Lab | /Set_string_1.py | 254 | 4.125 | 4 | # The characters which are in string 1 but not in string 2.
st1 = set(input('Enter 1st String: '))
st2 = set(input('Enter 2nd String: '))
s = st1 - st1.intersection(st2)
print('The no. of characters are : ',len(s),'\nAnd he characters are : ',*s)
| true |
b0fde66d48738570498b47c976a881ba5a3b062d | aryan-upa/Python-Lab | /Set_String2.py | 321 | 4.5 | 4 | # WAP to find out words which are either in string 1 or in string 2 but not in both.
st1 = set(input('Enter string 1 : '))
st2 = set(input('Enter string 2 : '))
s = st1.symmetric_difference(st2)
print('The characters which are either in string 1 or in string 2 are :',len(s))
print(f'The characters are : {s}')
| true |
4e21110ddca178d2ba17cc24600528ab91c2d04f | dtklumpp/python-merge-sort | /merge_sort/merge_sort.py | 971 | 4.28125 | 4 | """ starter code for merge_sort """
def merge_sort(arr):
""" recursive function to reduce the array to sub-arrays of length one or zero """
# if the array is length one or zero, return the array
# figure out the middle point
# create an array of the left half
# create an array of right half
# call merge on a recursively called left half and right half
# remove this return when done entering merge_sort code.
return arr
def merge(left, right):
""" function to merge two arrays into one in order """
result = []
# while both arrays have elements in them, zip them together
# if left array first element is less than right array first element, append to result
# else append the right array first element to result
# if left is the only array with elements, append them all in
# if right is the only array with elmeents, append them all in
# return final result
return result
| true |
f2b7ae31c1d95f098022106506ffd187ad7b3c1f | indayush/Python_Essentials | /Exercise Files/Chap03/printDetailed.py | 1,769 | 4.5 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
print('Hello, World.')
x = '''
This is a multi-line string
'''
print(x)
a = 5
b,c = 10,20
s = f'values are - a = {a} b = {b} c= {c}'
print(s)
'''
values are - a = 5 b = 10 c= 20
'''
# {} are positional args or placeholders
x = 'Hello, World. {} {} {}'.format(1,2,3,4)
print(x)
# 4 is ignored as no position defined
'''
Hello, World. 1 2 3
'''
# {n} - n here specifies which value from format will go at which position
x = 'Hello, World. {1} {2} {0}'.format(1,2,3,4)
print(x)
# 4 is ignored as no position defined
'''
Hello, World. 2 3 1
'''
# {n} - n here specifies which value from format will go at which position
# If same position is given at two places, then we will get respective value at that position
# If give 20 as position and it is invalid position which doesn't exists, then we will get - Replacement index 20 out of range for positional args tuple
x = 'Hello, World. {0} {2} {0}'.format(1,2,3,4)
print(x)
# 4 is ignored as no position defined
'''
Hello, World. 1 3 1
'''
# {:<n} - will give error. The position is necessary
x = 'Hello, World. +"{0:<5}"+ -"{1:>5}"- *"{2:<6}"*'.format(1,2,3,4)
print(x)
# 4 is ignored as no position defined
'''
Hello, World. +"1 "+ -" 2"- *"3 "*
+"1 "+ = Five chars with left align
-" 2"- = Five chars with right align
*"3 "* = Six chars with left align
'''
x = 'Hello, World. +"{0:<5}"+ -"{1:>5}"- *"{2:<06}"*'.format(1,2,321)
print(x)
# 4 is ignored as no position defined
'''
Hello, World. +"1 "+ -" 2"- *"321000"*
+"1 "+ = Five chars with left align
-" 2"- = Five chars with right align
*"321000"* = Six chars with left align and filled with zeroes where value not present
'''
| true |
79fc8201980867c467e277449e72b0429b7bb40c | akhilbommu/May_LeetCode_Challenge | /Day6-MajorityElement.py | 989 | 4.1875 | 4 | """
Problem Link : "https://leetcode.com/problems/majority-element/"
Approach 1 : Create a dictionary object and iterate through it and check if value of particular element is
greater than "math.floor(len(nums) / 2" if so return that element.
Approach 2 : Sort the given array.For an element to be a majority element its occurances should be greater than
half the length of given array.
So when we sort the array the majority element will be at the index "len(nums)//2".
"""
import math
from collections import Counter
class MajorityElement:
def majorityElement1(self, nums):
d = Counter(nums)
for each in d:
if d[each] > math.floor(len(nums) / 2):
return each
def majorityElement2(self, nums):
nums = sorted(nums)
return nums[len(nums) // 2]
obj = MajorityElement()
nums = [1, 2, 3, 4, 1, 2, 2, 2, 2, 2]
print(obj.majorityElement1(nums))
print(obj.majorityElement2(nums))
| true |
1f9bac887e720291a34cc8e61faf475b2669dfd2 | AleksandrTsimbulov/common | /Algorithms2/traversingtree.py | 1,209 | 4.15625 | 4 | # Traversing tree
# Illustrates an algorithm of traversing through binary tree
import sys
# getting binary tree
data = sys.stdin
binary_tee = []
n = int(data.readline().strip())
for i in range(n):
binary_tee.append([int(x) for x in data.readline().strip().split()])
# in-order traversing
def in_order_travers(root):
# in order traversing of the binary tree
if binary_tee[root][1] != -1:
in_order_travers(binary_tee[root][1])
print(binary_tee[root][0], end=' ')
if binary_tee[root][2] != -1:
in_order_travers(binary_tee[root][2])
def pre_order_travers(root):
# pre-order traversing of the binary tree
print(binary_tee[root][0], end=' ')
if binary_tee[root][1] != -1:
pre_order_travers(binary_tee[root][1])
if binary_tee[root][2] != -1:
pre_order_travers(binary_tee[root][2])
def post_order_travers(root):
# post-order traversing of the binary tree
if binary_tee[root][1] != -1:
post_order_travers(binary_tee[root][1])
if binary_tee[root][2] != -1:
post_order_travers(binary_tee[root][2])
print(binary_tee[root][0], end=' ')
in_order_travers(0)
print()
pre_order_travers(0)
print()
post_order_travers(0) | false |
65191a5443926aeff8c56c14dac0e57ec2f84f9d | lebrancconvas/Hello-Python | /dict.py | 254 | 4.15625 | 4 | try:
num = input("input your number : ");
if float(num)<0:
raise ValueError("Negative!");
else:
print("Ok! The Number is " + num);
except:
print("WTF! Why error ?");
finally:
print("Thank you for your participate.");
| true |
a9b8d206d4989f8faad9dda032c13bd5867ba97e | willstauffernorris/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,173 | 4.53125 | 5 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# Your code here
#print(f'LIST: {nums}')
#print(f'SIZE OF WINDOW: {k}')
#incrementing variable
i = 0
max_list = []
# simplest case:
#print(len(nums))
while k+i <= len(nums):
# grab the first k numbers from nums
window_list = nums[i:k+i]
#print(window_list)
# call the max of the list and return the one max value
max_value = max(window_list)
#print(f'MAX: {max_value}')
# append that max value to a new list
max_list.append(max_value)
#print(f'MAXLIST: {max_list}')
# move the window over one item until the right edge of the window hits the max length of nums
## This is a while loop
#increment i
i += 1
return max_list
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
ee7764b3f44c4ac910142a7673024db95f0ff221 | atulanandnitt/questionsBank | /basicDataStructure/array_list/extra/transform_the_array.py | 402 | 4.21875 | 4 | #https://practice.geeksforgeeks.org/problems/transform-the-array/0
def transform_the_array(list1):
for i in range(len(list1)):
for j in range(len(list1) -1):
if list1[j] == list1[j+1]:
list1[j] = 2 * list1[j]
list1[j+1] =0
print(list1)
return list1
list1=[2,4,5,0,0,5,4,8,6,0,6,8]
print(transform_the_array(list1))
| false |
937faf056e7decac5d0ec51a2aaf4b73aa92cab6 | atulanandnitt/questionsBank | /basicDataStructure/list/callByRef_callByValue.py | 1,671 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
neither call by value nor call by reference
"""
#List is mutable
def change_list_contents(the_list):
print("got",the_list)
the_list.append('Four')
print("chagned to",the_list)
outer_list=['one','two','three']
print('before, outer_list',outer_list)
change_list_contents(outer_list)
print('after, outer_list',outer_list)
print(" ****************LIST IS MUTABLE")
def change_tupple_contents(the_tupple):
print("got",the_tupple)
temp_tupple=('four',)
the_tupple =the_tupple+ temp_tupple
print("chagned to",the_tupple)
outer_tupple=('one','two','three')
print('before, outer_tupple',outer_tupple)
change_tupple_contents(outer_tupple)
print('after, outer_tupple',outer_tupple)
print("**************************TUPPLE IS IMMUTABLE")
def change_list_reference(the_list):
print('got',the_list)
the_list=['and','we','cant','lie']
print('set to',the_list)
outer_list =['we','like','proper','english']
print('before,outer_list :',outer_list)
change_list_reference(outer_list)
print('after ,outer_list =',outer_list)
def change_str_reference(the_str):
print('got',the_str)
the_str="I am the modifed str"
print('set to',the_str)
outer_str ="original string"
print('before,outer_str :',outer_str)
change_str_reference(outer_str)
print('after ,outer_str =',outer_str)
def change_int_reference(the_int):
print('got',the_int)
the_int=99999
print('set to',the_int)
outer_int =1
print('before,outer_int :',outer_int)
change_int_reference(outer_int)
print('after ,outer_int =',outer_int) | false |
b1f55e9cdb8b23631ed4a68cee8f5b12f8ac7eaf | minhluanlqd/AlgorithmProblem | /problem18.py | 1,271 | 4.3125 | 4 | """"""
"""
This problem was asked by Google. #298
A girl is walking along an apple orchard with a bag in each hand. She likes to pick apples from each tree as she goes
along, but is meticulous about not putting different kinds of apples in the same bag.
Given an input describing the types of apples she will pass on her path, in order, determine the length of the longest
portion of her path that consists of just two types of apple trees.
For example, given the input [2, 1, 2, 3, 3, 1, 3, 5], the longest portion will involve types 1 and 3, with a length of
four.
"""
def pick_fruits(trees):
a, b = trees[0], trees[1]
last_picked = b
last_picked_count = (a == b)
max_length_path = curr = 1
for tree in trees[1:]:
if tree not in (a, b):
a, b = last_picked, tree
last_picked = tree
curr = last_picked_count + 1
else:
curr += 1
if last_picked == tree:
last_picked_count += 1
else:
last_picked = tree
last_picked_count = 1
max_length_path = max(curr, max_length_path)
return max_length_path
trees = [2, 1, 2, 3, 3, 1, 3, 5]
print(pick_fruits(trees))
| true |
b38efc6d83de02e7a9f110f4dfe73e1d7da4eb5d | garimatuli/Udacity-Coding-and-Projects | /Python-Programs/random_Turtle_Wander.py | 434 | 4.15625 | 4 | import turtle
import random
colors = ["red", "orange", "yellow", "green", "blue", "purple", "lime", "cyan"]
t = turtle.Turtle()
t.width(12)
t.speed(0)
for step in range(100):
# randint() generates a random number from the given range (inclusive)
angle = random.randint(-90, 90)
# choice() returns a random item from the list
color = random.choice(colors)
t.color(color)
t.right(angle)
t.forward(10)
| true |
0f24c8da71aceaef30614ab4abb0473e2cad92bb | garimatuli/Udacity-Coding-and-Projects | /Python-Strings-Lists-Style-Structure/compareStrings.py | 810 | 4.34375 | 4 | # Write a function called starts_with that takes two strings as arguments,
# and returns True if the first string starts with the second string,
# and False otherwise.
def starts_with(long_str, short_str):
for i in range(len(short_str)):
if long_str[i] != short_str[i]:
return False
return True
# use string slicing
def starts_with_slicing(long_str, short_str):
n = len(short_str)
return long_str[0:n] == short_str
# A call like this should return True:
print(starts_with("apple", "app"))
print(starts_with_slicing("apple", "app"))
# And one like this should return False:
print(starts_with("manatee", "mango"))
print(starts_with_slicing("manatee", "mango"))
# using built-in method startswith
print("apple".startswith("app"))
print("manatee".startswith("mango"))
| true |
d8127aa4f2adbdea3cb0d373fecf1cf5e44a78fb | rhon-au/mytest | /Hide_Credentials.py | 795 | 4.25 | 4 | import getpass
import base64
# ask for username - will be displayed when typed
uname = input("Enter your username : ")
# ask for password - will not be displayed when typed
p = getpass.getpass(prompt="Enter your password: ")
# contruct credential with *.* as separator between username and password
creds = uname + "*.*" + p
# Encrypt given set of credentials
def encryptcredential (pwd) :
rvalue = base64.b64encode (pwd.encode())
return rvalue
# Decrypt a give set of credentials
def decryptcredential (pwd) :
rvalue = base64.b64decode(pwd)
rvalue=rvalue.decode ()
return rvalue
encryptedcreds = encryptcredential (creds)
print ("Simpe creds: " + creds)
print ("Encrypted creds: " + str(encryptedcreds))
print ("Decrypted creds: " + decryptcredential(encryptedcreds))
| true |
0b2d5b8361bf4ab98eee51a3e91651f9a1740384 | ElenaDu/python-challenge | /PyBank/main.py | 2,692 | 4.15625 | 4 | import csv
import os
sum_revenue=0
sum_month=0
file_name=input("Please, input the file name including extension: ")
#file_name="budget_data_2.csv"
#file_name="budget_data_1.csv"
revenue=[]
month=[]
change_revenue=[]
with open(file_name, "r", newline='') as csv_file:
csvreader=csv.reader(csv_file, delimiter=',')
next(csvreader, None)
for row in csvreader:
#Create two lists - with revenue and month data
revenue.append(int(row[1]))
month.append(row[0])
# Find the total number of months included in the dataset
total_months=len(month)
#Find the total amount of revenue gained over the entire period
total_revenue=sum(revenue)
#Create new list with change in revenue between months
for i in range(1,total_months):
change_revenue.append(revenue[i]-revenue[i-1])
#Find the average change in revenue between months over the entire period
avg_revenue_change=sum(change_revenue)/len(change_revenue)
#Find the greatest increase in revenue (date and amount) over the entire period
max_revenue_change=max(change_revenue)
#Check there was an increase
if max_revenue_change > 0:
maxpos=change_revenue.index(max_revenue_change)
month_max_revenue_change=month[maxpos+1]
else:
max_revenue_change = 0
month_max_revenue_change = 'N/A'
#Find the greatest decrease in revenue (date and amount) over the entire period
min_revenue_change=min(change_revenue)
#Check there was a decrease
if min_revenue_change < 0:
minpos=change_revenue.index(min_revenue_change)
month_min_revenue_change=month[minpos+1]
else:
min_revenue_change = 0
month_min_revenue_change = 'N/A'
#Print all the results to the terminal
print("Financial Analysis")
print("----------------------------")
print(f"Total Months: {total_months}")
print(f"Total Revenue: {total_revenue}")
print(f"Average Revenue Change: {avg_revenue_change}")
print(f"Greatest Increase in Revenue: {month_max_revenue_change} (${max_revenue_change})")
print(f"Greatest Decrease in Revenue: {month_min_revenue_change} (${min_revenue_change})")
#Export a text file ("results.txt") with the results.
with open("results.txt","w") as datafile:
datafile.write("Financial Analysis\n")
datafile.write("----------------------------\n")
datafile.write(f"Total Months: {total_months}\n")
datafile.write(f"Total Revenue: {total_revenue}\n")
datafile.write(f"Average Revenue Change: {avg_revenue_change}\n")
datafile.write(f"Greatest Increase in Revenue: {month_max_revenue_change} (${max_revenue_change})\n")
datafile.write(f"Greatest Decrease in Revenue: {month_min_revenue_change} (${min_revenue_change})\n")
print("Result is stored in results.txt")
| true |
b48a2654f648f8acd15f1f8d987439939ededcf1 | gshanbhag525/CP_Practice | /General Coding Problems/Python/print_adavanced.py | 1,337 | 4.625 | 5 | # Python 2
from __future__ import print_function
if __name__ == '__main__':
n = int(raw_input())
for x in xrange(1, n+1):
print(x, sep=' ', end='')
'''
In Python 2, the default print is a simple IO method that doesn't give many options to play around with.
The following two examples will summarize it.
Example 1:
var, var1, var2 = 1,2,3
print var
print var1, var2
Prints two lines and, in the second line, and are separated by a single space.
Example 2:
for i in xrange(10):
print i,
Prints each element separated by space on a single line. Removing the comma at the end will print each element on a new line.
Let's import the advanced print_function from the __future__ module.
Its method signature is below:
print(*values, sep=' ', end='\n', file=sys.stdout)
print(value1, value2, value3, sep=' ', end='\n', file=sys.stdout)
Here, values is an array and *values means array is unpacked, you can add values separated by a comma too. The arguments sep, end, and file are optional, but they can prove helpful in formatting output without taking help from a string module.
The argument definitions are below:
sep defines the delimiter between the values.
end defines what to print after the values.
file defines the output stream.
in Python 2 print_function is much faster than the default print
''' | true |
3117e35203e9fbe92afdfe36f3098d1e9888dba1 | hashrm/Learning-Python-3 | /Python Is Easy Assignments - Hash/05 Basic Loops/main.py | 671 | 4.15625 | 4 | # Homework Assignment #5: Basic Loops - Fizz Buzz
# Defining a range is the easiest way to print all numbers in that range.
for number in range(1, 101):
# By common LCM, for numbers divisible by both 3 & 5 they should also be divisible by 3*5 = 15
if number%(3*5) == 0:
print("FizzBuzz")
continue
# For only divisible by 3
elif number%3 == 0:
print("Fizz")
continue
# For only divisible by 5
elif number%5 == 0:
print("Buzz")
continue
print(number)
# Prime number is to be done for extra credit and it's slightly confusing, Is it possible to do it in a single if statement.
| true |
f24cd990d4c31ba28edb2dc45e25a8d00afc3e04 | EPERLab/matching | /src/matching/player.py | 2,026 | 4.125 | 4 | """ The base Player class for use in various games. """
class Player:
""" A class to represent a player within the matching game.
Parameters
----------
name : object
An identifier. This should be unique and descriptive.
Attributes
----------
prefs : list of Player
The player's preferences. Defaults to ``None`` and is updated using the
``set_prefs`` method.
pref_names : list
A list of the names in ``prefs``. Updates with ``prefs`` via
``set_prefs`` method.
matching : Player or None
The current match of the player. ``None`` if not currently matched.
"""
def __init__(self, name):
self.name = name
self.prefs = None
self.pref_names = None
self.matching = None
def __repr__(self):
return str(self.name)
def set_prefs(self, players):
""" Set the player's preferences to be a list of players. """
self.prefs = players
self.pref_names = [player.name for player in players]
def get_favourite(self):
""" Get the player's favourite player. """
return self.prefs[0]
def match(self, other):
""" Assign the player to be matched to some other player. """
self.matching = other
def unmatch(self):
""" Set the player to be unmatched. """
self.matching = None
def forget(self, other):
""" Forget another player by removing them from the player's preference
list. """
prefs = self.prefs[:]
prefs.remove(other)
self.prefs = prefs
def get_successors(self):
""" Get all the successors to the current match of the player. """
idx = self.prefs.index(self.matching)
return self.prefs[idx + 1 :]
def prefers(self, player, other):
""" Determines whether the player prefers a player over some other
player. """
prefs = self.pref_names
return prefs.index(player.name) < prefs.index(other.name)
| true |
99d33103044743577b7a692fd497cf00d732daca | Madhura-Manwadkar/Python_Basic | /LoopsDemo3.py | 993 | 4.1875 | 4 | #IF ELSE CONDITION
greeting ="Good morning"
if greeting == "Morning":
print("Condition matches")
print("second line")
else:
print("Condition did not match")
print("if else code is completed") #this line is independent of(not a part of) if else block.
#condition will not match as "Good morning" is not equal to "Morning"
a=4
if a>2:
print("Condition matches")
print("second line")
else:
print("Condition did not match")
print("if else code is completed")
#FOR LOOP
obj=[2,3,5,7,9] #list
for i in obj:
print(i)
#print i * 2
for i in obj:
print(i*2) #will print multiple of 2
#print sum of first natural numbers i.e. 1+2+3+4+5=15
summ=0
for j in range(1, 6): #will iterate from 1 to 6-1
summ = summ + j
print(summ)
#Example of for loop
print("*****************************************")
for k in range(1,10,2):
print(k)
print("******************SKIPPING FIRST INDEX***********************")
for m in range(10):
print(m) | true |
8fa5c3d69ac033b3116a2416b67d7767ea4272a8 | dineshkumarv151098/python--Assingment | /assignment 2.py | 1,050 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
print("hi welcome to letsupgrade")
# In[9]:
"""(@) (@)
^
===
"""
# In[11]:
print("he's the person i'm searching for!")
# In[13]:
print('he\'s the person i\'m searching for!')
# In[28]:
name = "dinesh"
dob = "15.10.1998"
place = "hosur"
print("my name is ", name,"and my DOB is ",dob,"i'm living in ",place)
# In[73]:
a = int(input("enter the value for a= "))
b = int(input("enter the value for b= "))
if a==b:
print ("number cannot be same")
if a<=0:
print("please the the valid number ")
if b<=0:
print("please the the valid number ")
if a>0:
if b>0:
if a!=b:
print(a**b)
print(a*b)
print(a/b)
print(a%b)
print(a+b)
print(a-b)
print(a//b)
print(a|b)
print(a&b)
print(a^b)
print(a<<b)
print(a>>b)
# In[ ]:
# In[ ]:
# In[ ]:
| false |
e76d93fee26eb2709eb95eb8270c66b2ef452702 | LenaChretien/Python_functions | /reverseString.py | 233 | 4.46875 | 4 | def reverseString(raw_string):
'''
Function will take a string and returns a new string, that is reversed word by word
Args: String
Rets: string in reversed order
'''
jo = " ".join(raw_string.split()[::-1])
return print(jo) | true |
cc49b81933d0e7fd5de1b123d860d7ca88f7b0fc | LenaChretien/Python_functions | /BinarySearchIter.py | 1,263 | 4.15625 | 4 | # The bisection method in mathematics is a root-finding method that repeatedly bisects an interval and then selects a subinterval in which a root must lie for further processing.
#Given a continuous function f and an interval [𝑎,𝑏], which satisfies that the values of 𝑓(𝑎) and 𝑓(𝑏) are opposite, say 𝑓(𝑎)∗𝑓(𝑏)<0 (there is at least one zero crossing within the interval).
# Calculate 𝑐, the midpoint of the interval, 𝑐=0.5∗(𝑎+𝑏).
# Calculate the function value at the midpoint, 𝑓(𝑐)
# If convergence is satisfactory (that is, 𝑓(𝑐) is sufficiently small), return 𝑐 and stop iterating.
def binarySearchIter(fun, start, end, eps=1e-10):
'''
fun: funtion to fund the root
start, end: the starting and ending of the interval
eps: the machine-precision, should be a very small number like 1e-10
return the root of fun between the interval [start, end]
'''
if fun(start) * fun(end) >= 0:
raise ValueError('The sign of fun(start) and fun(end) should be opposite!')
c = (start + end)/2.0
while abs(fun(c)) > eps:
if fun(start)*fun(c) > 0:
start = c
else:
end = c
c = (start + end)/2.0
return c | true |
baae8c86b5d683f974bbd14c91e8d5c850c81790 | PYBPYB/Python | /15_协程/01_迭代器.py | 1,209 | 4.125 | 4 | from collections import Iterable
from collections import Iterator
import time
class Classmate(object):
def __init__(self):
self.names = list()
def add(self, name):
self.names.append(name)
def __iter__(self):
"""如果想要一个对象被称为 可迭代对象,即可以使用for循环,
那么必须要实现 __iter__ 方法"""
return ClassItertor(self)
class ClassItertor(object):
def __init__(self, obj):
self.obj = obj
self.current_num = -1
def __iter__(self):
pass
def __next__(self):
if self.current_num < len(self.obj.names)-1:
self.current_num += 1
return self.obj.names[self.current_num]
else:
raise StopIteration
classmate = Classmate()
classmate.add("老王")
classmate.add("张三")
classmate.add("李四")
print("判断 classmate 是否是可以迭代的对象:",
isinstance(classmate, Iterable))
classmate_iterator = iter(classmate)
print("判断 classmate_iterator 是否是迭代器:",
isinstance(classmate_iterator, Iterator))
# print(next(classmate_iterator))
for name in classmate:
print(name)
time.sleep(1) | false |
78ce84aa9773536ba0625869ace1336ca3fe2991 | mathcodes/HigherLower-1 | /main.py | 2,320 | 4.25 | 4 | import random
from game_data import data
from art import logo, vs
from replit import clear
# 3.Format the account data into printable format
#code pulled up to put inside a separate, new function:
def format_data(account):
"""Format the account data into printable format"""
account_name = account["name"]#And this will go into that dictionary and pull out the value under the key 'name' and save it to this variable.
account_descr = account["description"]
account_country = account["country"]
return f"{account_name}, a {account_descr}, from {account_country}"
## 7.Use if statement to check it user is correct
def check_answer(guess, a_followers, b_followers):
if a_followers > b_followers:
return guess == "a"
else:
return guess == "b"
# 1.Display art
print(logo)
score = 0
game_should_continue = True
# 11.Making the accounts at position B become the next account at position A
account_b = random.choice(data)
# 10.Make game repeatable.
while game_should_continue:
# 2.Generate a random account from the game data
account_a = account_b
account_b = random.choice(data)
# 2b. Check if counts are equal, in which case we will get a new b
#changing if to a while loop so computer keeps checking if they are equal as they change each round
if account_a == account_b:
account_b = random.choice(data)
print(f"Compare A: {format_data(account_a)}.")
print(vs)
print(f"Compare B: {format_data(account_b)}.")
# 4.Ask the user for a guess
guess = input("Which do you think has more Instagram followers, 'A' or 'B'?\n").lower() #akes everything lower case to accept A and a
# 5.Check if User is correct
## 6.Get follower count of each account
a_followers = account_a["follower_count"]
b_followers = account_b["follower_count"]
is_correct = check_answer(guess, a_followers, b_followers)
print(f"A has {a_followers}.")
print(f"B has {b_followers}.")
# 12.Clear previous output and displays fresh screen
clear()
print(logo)
# 8.Give user feedback on their guess
# 9.Score keeping
if is_correct:
score += 1
print(f"Good job! Your score is {score}")
else:
game_should_continue = False
print(f"Nope. Your final score is {score}")
| true |
ad8097006ef683330426af0e6b4b8a635bd86c1b | Jamesical/Python | /Python Batch/Side Work/While_Prac.py | 508 | 4.34375 | 4 | #Travis Saulat While Loop Practice SUMMATION FACTORIAL 1/26/2021
summ = 0 #placeholder for the sum
facts = 1#place holder for the product
i = 1 #variables for the loops
j = 1
num = int(input("Enter an integer(SUMM): ")) #input for summatipns
while i <= num: #loop for dynamic summantion/factorials
summ = summ+i
i = i+1
print(summ)
num2 = int(input("\n\nEnter an integer(FACT): "))
while j <= num2:
facts = facts*j #note the '*'
j = j+1
print(facts)
| true |
3205b1381a185dbc12b9c9e6ecd86ad297ab5511 | kanth989/allusion | /example3.py | 866 | 4.1875 | 4 | class Fruits(object):
fruits = {}
def __init__(self, f_name, s_name, a_name):
self.f_name = f_name
self.s_name = s_name
self.a_name = a_name
self.add_to_fruits()
def add_to_fruits(self):
if self.f_name.endswith("kaya"):
return "Not added because its is vegetable"
else:
if not self.fruits.get(self.a_name):
self.fruits[self.a_name] = {}
if not self.fruits.get(self.a_name).get(self.s_name):
self.fruits[self.a_name][self.s_name] =[]
self.fruits[self.a_name][self.s_name].append(self.f_name)
else:
self.fruits[self.a_name][self.s_name].append(self.f_name)
apple = Fruits("apple","winter","hyd")
mango = Fruits("mango","summer","hyd")
grapes = Fruits("grapes","winter","hyd")
print apple.fruits | false |
33ad2ac6575f7ef8a0d939b2afb0e04a17897ab8 | ParasBotadra/ThoughtWorks_Assignments | /process_input.py | 1,147 | 4.375 | 4 | #import re
def process_input(user_input):
"""
Checks the type of user input
1. Numeric assignment clause:
i. input should have only three words
ii. it should not end with '?'
iii. second word should be 'is'
iv. third word should be either of 'I,V,X,L,C,D,M'
"""
#count = len(re.findall(r'\w+', user_input))
words = user_input.split()
length = len(words)
if length == 3 and words[length-2].lower() == 'is':
if len(words[length-1]) == 1 and words[length-1] in ('I','V','X','L','C','D','M'):
return ("Numeric Assignment")
else:
return ("Sorry, but there is no such symbol used in the galaxy as \""+ words[length-1] +"\".\nPlease use any symbol from the below list:\nI\nV\nX\nL\nC\nD\nM")
elif length > 3 and words[length-1].lower() == 'credits' and words[length-2].isdigit() == True and words[length-3].lower() == 'is' :
return ("Unit Assignment")
elif length > 3 and words[length-length].lower() == 'how' and words[length-(length-1)].lower() in ('many','much') and "?" == user_input[len(user_input)-1] and "is" in user_input.lower():
return ("Question")
else:
return ("I have no idea what you are talking about")
| true |
595bc7fb3b1e8304986867ee5b2d7b0205dac7c5 | tabris2015/intro_python_blumbit | /basico/calculadora.py | 1,332 | 4.28125 | 4 | # calculadora simple
# esta calculadora recibe una operacion de 2 numeros desde teclado
# la entrada debe estar en este formato: <n1> <op> <n2>
# se soportan las siguientes operaciones:
# multiplicacion: *
# division: /
# suma: +
# resta: -
# los numeros tienen que ser numeros enteros positivos
# ejemplo:
# entrada: '9 - 1'
# salida: '8'
op_validas = ['*', '/', '-', '+']
# recibir la entrada
texto = input('ingrese la operacion: ')
resultado = 0
# validar la entrada
if len(texto.split()) != 3:
print('ingrese una operacion valida en este formato: <n1> <op> <n2>')
else:
palabras = texto.split()
n1_str = palabras[0]
operador = palabras[1]
n2_str = palabras[2]
# validar los componentes
if n1_str.isdigit() and n2_str.isdigit() and operador in op_validas:
n1 = int(n1_str)
n2 = int(n2_str)
# realizar la operacion
if operador == '*':
resultado = n1 * n2
elif operador == '/':
resultado = n1 / n2
elif operador == '+':
resultado = n1 + n2
elif operador == '-':
resultado = n1 - n2
# mostrar resultados
print(f'resultado: {resultado}')
else:
print('ingrese solamente numeros enteros y operadores validos')
| false |
f971342470c5b3bdc4cdda2b111bd150a24e9280 | sdipippo/Intermediate_Python | /Hamlet_word_counter_v1.py | 1,972 | 4.15625 | 4 | from collections import Counter
# Task 1: count the frequency of words in "Hamlet"
counts = Counter()
with open('C:\Users\sdipippo\Desktop\dialogue.txt') as f:
for line in f:
for word in line.split():
counts[word] += 1
print counts.most_common(3)
# Task 2: Organize the unique words by first letter
words = {} #letter -- > set of words beginning with that letter
with open('C:\Users\sdipippo\Desktop\dialogue.txt') as f:
for line in f:
for word in line.split():
initial = word[0]
words.setdefault(initial, set()).add(word)
print words['v']
#alternate way to do task 2
from collections import defaultdict
words = defaultdict(set)
with open('C:\Users\sdipippo\Desktop\dialogue.txt') as f:
for line in f:
for word in line.split():
initial = word[0]
words[initial].add(word)
print words['v']
#Task 3: Organize the words
# chain prev --> list of following words
# Every time you see a word, that's the key, and the value is the list of words
# following the word
#Example: If the key is "the", then the values are all words immediately following
# the word "the" in the document"
# the: castle, house, tower
import random
chain = defaultdict(list)
# Defaultdict always uses a default value if there is no existing key yet,
# as opposed to regular dictionary which would throw a key error
# In this case, it's saying that "Whenever you look up a key that
# doesn't exist, put an empty list into the value field"
last = None, None
with open('C:\Users\sdipippo\Desktop\dialogue.txt') as f:
for line in f:
for word in line.split():
chain[last].append(word)
last = (last[1], word)
capitalized = [word for word in chain if word[0] and word[0][0].isupper()]
last = random.choice(capitalized)
for word in last:
print word,
while word[-1] not in '.?!':
word = random.choice(chain[last])
print word,
last = (last[1], word)
| true |
c874c6a08a43f68bfd662a26d5b3e11badeb0e88 | jakeparmstrong/pythonEdu | /listtup.py | 240 | 4.28125 | 4 | list = [1,2,5,3,4]
print(list) #output is [1, 2, 5, 3, 4]
list[2]=3
list[3]=4
list[4]=5
print(list) #output is [1, 2, 3, 4, 5]
#list[5] = 6 //This produces an error, but...
list = [0,0,0,0,0,0] #you can resize a list like this
print(list)
| true |
886ee14452ede5607ed120c7a50f50a9aff3fff2 | vnikov/Fall-2017 | /CS111/Lab2/lab2task2.py | 801 | 4.125 | 4 | def mysum(x, y):
""" takes two numbers and returns their sum """
total = x + y
return total
def sum_double(a, b):
""" return the sum of the integers, unless the two values are the same, in which case the function should return double their sum """
if a == b:
return 2 * (a + b)
else:
return a + b
def test():
""" function for testing """
test1 = sum_double(1, 2)
print('first test returns', test1)
test2 = sum_double(3, 2)
print('second test returns', test2)
test3 = sum_double(2, 2)
print('third test returns', test3)
test4 = sum_double(0, 0)
print('forth test returns', test4)
test5 = sum_double(-4, -2)
print('fifth test returns', test5)
test6 = sum_double(-3, -3)
print('sixth test returns', test6)
| true |
3c904b1a6037108f664ea55528fbcdf9768b6ab1 | alexlo80/Python_basic_07_09_2020 | /lesson1/task1.py | 1,122 | 4.40625 | 4 | """1.Поработайте с переменными, создайте несколько, выведите на экран,
запросите у пользователя несколько чисел и строк и сохраните в
переменные, выведите на экран."""
# Поработайте с переменными, создайте несколько, выведите на экран
perem_str = "Text variable"
perem_int = 12345
perem_float = 3.1415
perem_bool = True
print(f"str: {perem_str}, int: {perem_int}, float: {perem_float},bool:{perem_bool}")
print()
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран
user_reply_num = input("please insert number: ")
if user_reply_num.isdigit():
user_reply_str = input("please insert text: ")
else:
print("please insert just numbers!!")
print(int(user_reply_num) * user_reply_str)
print()
# вывод в столбик
number = int(user_reply_num)
while number:
print(user_reply_str)
number -= 1
| false |
d1ec001b2e47b8bf14efdd2ebaca0acacc154482 | allybrannon/week1_wednesday | /prompt_for_number.py | 313 | 4.40625 | 4 | # run a program that prompts a user for a number
# and then multiplies that by itself
#this is the first step prompting the user for a number
user_input = int(input("Please enter a number: "))
# second step, multiplying the input
result = user_input * user_input
#Final step, return the result
print (result)
| true |
9e9f8baffb7ba06ededbfed247c6741dd8cf4295 | SamiaAitAyadGoncalves/codewars-1 | /Python/7kyu/Arithmetic sequence - sum of n elements.py | 794 | 4.125 | 4 | # https://www.codewars.com/kata/55cb0597e12e896ab6000099
#
# In your class, you have started lessons about "arithmetic progression".
# Because you are also a programmer, you have decided to write a function.
#
# This function, arithmetic_sequence_sum(a, r, n), should return the sum of
# the first (n) elements of a sequence in which each element is the sum of the
# given integer (a), and a number of occurences of the given integer (r), based
# on the element's position within the sequence.
#
# For example:
#
# arithmetic_sequence_sum(2, 3, 5) should return 40:
#
# 1 2 3 4 5
# a + (a+r) + (a+r+r) + (a+r+r+r) + (a+r+r+r+r)
# 2 + (2+3) + (2+3+3) + (2+3+3+3) + (2+3+3+3+3) = 40
def arithmetic_sequence_sum(a, r, n):
return sum([a+r*i for i in range(n)])
| true |
a1c7067acc620a628aa8a29b3805116ce471d0c3 | SamiaAitAyadGoncalves/codewars-1 | /Python/7kyu/Fix string case.py | 1,170 | 4.21875 | 4 | # https://www.codewars.com/kata/5b180e9fedaa564a7000009a
#
# In this Kata, you will be given a string that may have mixed uppercase and
# lowercase letters and your task is to convert that string to either lowercase only or
# uppercase only based on:
#
# * make as few changes as possible.
# * if the string contains equal number of uppercase and lowercase letters,
# convert the string to lowercase.
#
# For example:
# Haskell
# solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to
# lowercase.
# solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to
# uppercase.
# solve("coDE") = "code". Upper == lowercase. Change all to lowercase.
#
#
# More examples in test cases. Good luck!
#
# Please also try:
#
# [Simple time
# difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
#
# [Simple remove
# duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
def solve(s):
up = 0
low = 0
for letter in s:
if letter.islower():
low += 1
if letter.isupper():
up += 1
if up > low:
return s.upper()
else:
return s.lower()
| true |
1aee58b910fd18d8f69fe59880ce801a4c898870 | AndreBuchanan92/COSC_1336_Python | /Andre_Buchanan_Lab3a.py | 1,706 | 4.1875 | 4 | #Part A
print('Hello, cousin. I cannot understand your measurments! I created this program to help you in the US.')
km = int(input('\nPlease input your kilometers: '))
miles = km / 1.6
if km < 0 :
print ("Error: please re-enter a positive number.")
else :
print ('You have gone ', miles ,' miles')
#Part B
print ('\nOkay, now lets do temperature')
celsius = int(input('What is the temperature in celsius? '))
fahrenheit = (celsius * 9/5) + 32
if celsius > 1000 :
print ("Error: please re-enter less than 1000 degrees")
else:
print ('The temperature is ', fahrenheit, 'degrees.')
#Part C
print ('\nOkay, now lets do liters')
liters = int(input('How many liters do you have? '))
gallons = liters / 3.9
if liters < 0 :
print ("Error: please re-enter a positive number.")
else:
print ('You have ', gallons, 'gallons')
#Part D
print ('\nOkay, now lets do kilograms')
kilogram = int(input('How many kilograms do you have? '))
lbs = kilogram / .45
if kilogram < 0 :
print ("Error: please re-enter a postive number.")
else:
print ('You have ', lbs, 'pounds')
#Part E
print ('\nOkay, now lets do centimeters')
cm = int(input('How many centimeters do you have? '))
inches = cm / 2.54
if cm < 0 :
print("Error: please input a positive number.")
else:
print ('You have ', inches, 'inches')
| true |
b9cecd4e907947951a4203f8f04c5ee2d3a4790c | Drunk-Mozart/card | /DL_02_variable.py | 241 | 4.1875 | 4 | # buy apple
amount = int(input("please input the amount:"))
price = float(input("please input the price:"))
money = amount * price
print("the price of apple is %f, the amount of apple is %f, the money of apple is %f"%(price, amount, money))
| true |
bcda03f1604abc3058994ba89b01a42bd48adbfd | danhill600/mymatthespython | /ch9classes/9_1restaurant.py | 1,469 | 4.375 | 4 | #9-1. Restaurant: Make a class called Restaurant . The __init__() method for
#Restaurant should store two attributes: a restaurant_name and a cuisine_type .
#Make a method called describe_restaurant() that prints these two pieces of
#information, and a method called open_restaurant() that prints a message indi-
#cating that the restaurant is open.
#Make an instance called restaurant from your class. Print the two attri-
#butes individually, and then call both methods.
class Restaurant():
"""An attempt to model a restaurant"""
def __init__(self, name, cuisine):
"""initialize name and cuisine attributes"""
self.name = name
self.cuisine = cuisine
def describe_restaurant(self):
"""tell the user about the restaurant"""
print(self.name.title() + " serves " + self.cuisine + " food.")
def open_restaurant(self):
"""open the restaurant for the day"""
print(self.name.title() + " is now open")
my_restaurant = Restaurant("zorba's", "greek")
print(my_restaurant.name.title() + " serves " + my_restaurant.cuisine.title()
+ " food.")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
second_restaurant = Restaurant("spaghetti shop", "italian")
third_restaurant = Restaurant("maize", "mexican")
fourth_restaurant = Restaurant("Desta", "Ethiopian")
second_restaurant.describe_restaurant()
third_restaurant.describe_restaurant()
fourth_restaurant.describe_restaurant()
| true |
685113342f0f8feb35823ccac5d78fbd620e43b8 | danhill600/mymatthespython | /ch9classes/9_5login_attempts.py | 2,235 | 4.34375 | 4 | #9-3. Users: Make a class called User . Create two attributes called first_name
#and last_name , and then create several other attributes that are typically stored
#in a user profile. Make a method called describe_user() that prints a summary
#of the user’s information. Make another method called greet_user() that prints
#a personalized greeting to the user.
#Create several instances representing different users, and call both methods
#9-5. Login Attempts: Add an attribute called login_attempts to your User
#class from Exercise 9-3 (page 166). Write a method called increment_
#login_attempts() that increments the value of login_attempts by 1. Write
#another method called reset_login_attempts() that resets the value of login_
#attempts to 0.
#Make an instance of the User class and call increment_login_attempts()
#several times. Print the value of login_attempts to make sure it was incremented
#properly, and then call reset_login_attempts() . Print login_attempts again to
#make sure it was reset to 0.
class User():
"""An attempt to model users."""
def __init__(self,first_name, last_name, email, membership, employer):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.membership = membership
self.employer = employer
self.login_attempts = 0
def describe_user(self):
print(self.first_name.title() + " " + self.last_name.title() +
" is employed by " + self.employer.title() + ".")
def greet_user(self):
print("Always nice to see you again, " + self.first_name.title() +
" " + self.last_name.title())
def increment_login_attempts(self):
self.login_attempts = self.login_attempts + 1
def reset_login_attempts(self):
self.login_attempts = 0
user1 = User('Ah', 'Clem', 'ahclem@bozos.fun', 'nb-individual', 'funland')
user2 = User('Count', 'Dracula', 'fangs@monsters.biz', 'sponsor', 'castle')
user1.greet_user()
user1.describe_user()
user2.greet_user()
user2.describe_user()
user1.increment_login_attempts()
user1.increment_login_attempts()
user1.increment_login_attempts()
print(str(user1.login_attempts))
user1.reset_login_attempts()
print(str(user1.login_attempts))
| true |
ad447401b6a52271638c98c96d93600f9c6d8283 | lscamacho/Python | /exercicios/ex005.py | 229 | 4.1875 | 4 | #Faça um programa que leia um número inteiro e mostre na tela seu sucessor e antecessor
num = int(input('Digite um numero: '))
ant = num - 1
pos = num + 1
print(f'O antecessor de <{num}> é <{ant}> e o sucessor é <{pos}> ') | false |
f1bd757fb6ec7b2a7309973bd84d7afac3a62eab | beetee17/week4_divide_and_conquer | /week4_divide_and_conquer/2_majority_element/majority_element.py | 1,815 | 4.28125 | 4 | # Uses python3
import sys
def get_majority_element(a):
"""Majority rule is a decision rule that selects the alternative which has a majority,
that is, more than half the votes. Given a sequence of elements 𝑎1, 𝑎2, . . . , 𝑎𝑛,
you would like to check whether it contains an element that appears more than 𝑛/2 times.
The goal in this code problem is to check whether an input sequence contains a majority element.
Input Format
The first line contains an integer 𝑛, the next one contains a sequence of 𝑛 non-negative
integers 𝑎0, 𝑎1, . . . , 𝑎𝑛−1
Constraints
1 ≤ 𝑛 ≤ 10^5
0 ≤ 𝑎𝑖 ≤ 10^9 for all 0 ≤ 𝑖 < 𝑛
Output Format
Output 1 if the sequence contains an element that appears strictly more than 𝑛/2 times,
and 0 otherwise."""
a = sorted(a)
max_count = 0
curr_count = 0
curr_num = a[0]
for num in a:
if num == curr_num:
curr_count += 1
# increment count if element is same as previous
else:
if curr_count > max_count:
# count terminates, check if count is better than current max
max_count = curr_count
# reset count to 1 (since we already looked at the different element)
curr_count = 1
# set the current element to the one for comparison
curr_num = num
# final check in case majority element ends the list
if curr_count > max_count:
max_count = curr_count
# check if majority element was found
if max_count > len(a) // 2:
return 1
return 0
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
print(get_majority_element(a))
| true |
fc1b17fe3817d451f0f135e7582cc7bf7ee96756 | carlosbotis27/Aulas-Python-FEI-2021 | /Atividade_4_Exe_2.py | 839 | 4.1875 | 4 | #Faça um programa que cria uma matriz, A, 5 x 5 com números inteiros em sequência e, então, exiba a matriz transposta de A ( At ).
#Determinar a transposta de uma matriz é reescrevê-la de forma que suas linhas e colunas troquem de posições ordenadamente, isto é, a primeira linha é reescrita como a primeira coluna, a segunda linha é reescrita como a segunda coluna e assim por diante, até que se termine de reescrever todas as linhas na forma de coluna.
A = []
At =[]
n = 1
i = 1
for _ in range(5):
An = []
An1 = []
for _ in range(5):
An.append(n)
n = n + 1
A.append(An)
n = 1
for linha in range(len(A)):
An1 = []
An1.append(i)
n = i + 5
for _ in range(4):
An1.append(n)
n = n + 5
i = i + 1
At.append(An1)
print(A)
print(At) | false |
a9d91c2726c57b103bf775c1029b26349a2c1f1a | boricuaboy/code | /reverse_word_order.py | 272 | 4.21875 | 4 | text = str(raw_input("Enter a sentence: "))
def reverse_words(text):
answer = ''
temp = ''
for char in text:
if char != ' ':
temp += char
else:
answer = temp + ' ' + answer
temp = ''
answer = temp + ' ' + answer
return answer
print reverse_words(text) | true |
3c7eb2b5abbd6bf6ac195a2c7d8ccaebe7eb143a | hngkong/class_files | /in_class/additional.py | 887 | 4.25 | 4 | # Instantiate two objects of MyClass as myobj1 and myobj2
# Display the default value of the attribute myVar for both the objects
# Then change the value of the myobj1 attribute to "Passed" and myobj2 to "Failed"
# Then print the attribute myVar for both the objects
class MyClass():
# Initial variable setup
myVar = "Example"
def main():
# Instantiate two objects of the MyClass() type
myobj1 = MyClass()
myobj2 = MyClass()
# Print the default values of myVar for both objects
print("Attribute within myobj1:", myobj1.myVar)
print("Attribute within myobj2:", myobj2.myVar)
# Change the values of myVar for both objects
myobj1.myVar = "Passed"
myobj2.myVar = "Failed"
# Print the values of myVar for both objects again
print("Attribute within myobj1:", myobj1.myVar)
print("Attribute within myobj2:", myobj2.myVar)
main() | true |
a811b7781f235840a83ca551500048cde033ddde | lukefrancis5/Python-Basics | /degreeconverter.py | 416 | 4.3125 | 4 | def convert(temp, unit):
unit = unit.lower()
if unit == "c":
temp = 9.0 / 5.0 * temp + 32
return "%s degrees Fahrenheit"% temp
if unit == "f":
temp = (temp - 32) / 9.0 * 5.0
return "% degrees Celcius"% temp
inputtemp = int(input("What is the temperature?:\n"))
inputunit = str(input("Please enter the unit of measure (c or f):\n"))
print(convert(inputtemp, inputunit))
| true |
95f8d1a2545fd49e40a3690fdf47c9c88703d308 | amilkarcruz13/class-on-python-programing-III-upc-2020 | /registro.py | 1,723 | 4.125 | 4 | class RegistroMateria:
def __init__(self, p_estudiante, p_apellido, p_carrera):
self.estudiante = p_estudiante
self.apellido = p_apellido
self.carrera = p_carrera
self.materias = []
def presentarse(self):
print("****************Presentacion de {} {}****************".format(self.estudiante, self.apellido))
if(self.materias):
for i in self.materias:
print(i)
else:
print("El estudiante todavia no registro materias")
return "Soy el est: {} de la carrera de {}".format(self.estudiante, self.carrera)
def registrarMateria(self):
print("Gestión de registro de materias")
materia = input('Digite la materia: ')
self.materias.append(materia)
print( "Materia {} registrada exitosamente.!".format(materia))
adicional = input("Desea registrar una materia adicional?: y/n: ")
if (adicional == 'y'):
self.registrarMateria()
else:
return "Materias registradas exitosamente.!!"
def menu(self):
opciones = """
Menu de la aplicación
1.- Registrar Materias
2.- Presentarse
"""
print(opciones)
eleccion = int(input('Elija una opción:'))
if(eleccion == 1):
print(self.registrarMateria())
self.menu()
elif(eleccion == 2):
print(self.presentarse())
self.menu()
else:
print("Elija del opcion del menu")
self.menu()
pedro = RegistroMateria("Pedro", "Perez", "Ingeniería de Sistemas")
pablo = RegistroMateria("Pablo", "Mercado", "Ingeniería Comercial")
print(pedro.menu())
| false |
91bf1a6e8a378e07371786908254242044016f8d | mhoov9/480-HW-2 | /HW2_Fibonacci.py | 773 | 4.15625 | 4 | #This function takes a number x and returns the Fibonacci number
#that belongs to the xth term in the Fibonacci sequence
def fib(x):
if x == 1:
return 0
if x == 2:
return 1
return fib(x-1) + fib(x-2)
#fib_seq returns a list of the Fibonacci sequence n terms long
#starting from 0
def fib_seq(n):
i = 1
fib_list = []
while i <= n:
fib_list.append(fib(i))
i += 1
return fib_list
#The next function uses the Fibonacci list that was previously constructed
#to approximate the Golden Ratio. The larger the number, the better
#the approximation will be.
def approx_goldratio(n):
approx = float(((fib_seq(n))[n-1]))/float(((fib_seq(n))[n-2]))
print ((fib_seq(n))[n-1])
print ((fib_seq(n))[n-2])
return approx
| true |
12d51686971c4d743064050e14d1e216db63dc7b | joaocbjr/EXERCICIOS_curso_intensivo_de_python | /exe7.3.py | 317 | 4.15625 | 4 | print('\n7.3 – Múltiplos de dez: \n'
'Peça um número ao usuário e, em seguida, informe se o '
'número é múltiplo de dez ou não.\n')
num = int(input('Digite um número: '))
if (num % 10 == 0):
print('\nEste número é multiplo de 10\n')
else:
print('\nEste número NÃO é multiplo de 10\n') | false |
5cddecb0d5ebaf117ae6690851da24b6e788dc9d | joaocbjr/EXERCICIOS_curso_intensivo_de_python | /exe4.8.py | 388 | 4.15625 | 4 | print()
print('4.8 – Cubos:\n Um número elevado à terceira potência é chamado de cubo. Por exemplo, o cubo de 2 é escrito como 2**3 em Python. Crie uma lista dos dez primeiros cubos (isto é, o cubo de cada inteiro de 1 a 10), e utilize um laço for para exibir o valor de cada cubo.')
print()
cubo = []
for value in range(1,11):
cub = value**3
cubo.append(cub)
print(cubo) | false |
3f24f9249b01bab16715b5e710601235ee57843d | joaocbjr/EXERCICIOS_curso_intensivo_de_python | /exe3.2.py | 399 | 4.15625 | 4 | print()
print('3.2 – Saudações: Comece com a lista usada no Exercício 3.1, mas em vez des implesmente exibir o nome de cada pessoa, apresente uma mensagem a elas. O texto de cada mensagem deve ser o mesmo, porém cada mensagem deve estar personalizada com o nome da pessoa.')
print()
names = ['Celsinho', 'Adenilson', 'Marcos', 'Dernival', 'Driele']
sauda = 'Diga aí '
print(sauda + names[1])
| false |
61cba13e848a1daee2cc3e6a1c52a3b07f72dde9 | Anshikaverma24/if | /if-else/divisible.py | 204 | 4.25 | 4 | # take userinput,check whther its is divisble by 5 or 11
num=int(input("enter the number"))
if num%11==0:
print("divisible by 11")
elif num%5==0:
print("divisible by 5")
else:
print("not divisible") | true |
794834b22ab7e344e2b9755b41e6ff111f5ff531 | Anshikaverma24/if | /if-else/day.py | 306 | 4.15625 | 4 | # print days according to number
number=int(input(" enter the number:"))
if number==1:
print("MONDAY")
if number==2:
print(" TUESDAY")
if number==3:
print("WEDNESDAY")
if number==4:
print("THURSDAY")
if number==5:
print(" FRIDAY")
if number== 6:
print("SATURDAY")
if number== 7:
print("SUNDAY")
| true |
0deab6942e98c0f1ee6a4fa6341ab3caf49583c3 | Surendra81/CodeWars | /build_tower_advanced.py | 1,253 | 4.375 | 4 | def tower_builder(n_floors, block_size):
"""
Build Tower by the following given arguments:
number of floors (integer and always greater than 0)
block size (width, height) (integer pair and always greater than (0, 0))
Tower block unit is represented as *
Python: return a list;
JavaScript: returns an Array;
Have fun!
for example, a tower of 3 floors with block size = (2, 3) looks like below
[
[' ** '],
[' ** '],
[' ** '],
[' ****** '],
[' ****** '],
[' ****** '],
['**********'],
['**********'],
['**********']
]
and a tower of 6 floors with block size = (2, 1) looks like below
[
' ** ',
' ****** ',
' ********** ',
' ************** ',
' ****************** ',
'**********************'
]
"""
w, h = block_size
total = w
result = list()
block_width_per_floor = w
for _ in range(n_floors - 1):
total += 2 * w
for _ in range(n_floors):
for _ in range(h):
result.append(("*" * block_width_per_floor).center(total))
block_width_per_floor += w * 2
return result
| true |
d802c78f587a2b29ba00ffb1ce49556ebfa6b921 | Surendra81/CodeWars | /bouncing_balls.py | 1,097 | 4.1875 | 4 | def bouncingBall(h, bounce, window):
"""A child plays with a ball on the nth floor of a big building.
The height of this floor is known:
(float parameter "h" in meters, h > 0) .
He lets out the ball. The ball rebounds for example to two-thirds:
(float parameter "bounce", 0 < bounce < 1)
of its height.
His mother looks out of a window that is 1.5 meters from the ground:
(float parameters window < h).
How many times will the mother see the ball either falling or
bouncing in front of the window
(return a positive integer unless conditions are not fulfilled
in which case return -1) ?
Note
You will admit that the ball can only be seen if the height
of the rebouncing ball is stricty greater than the window parameter.
Example:
h = 3, bounce = 0.66, window = 1.5, result is 3
h = 3, bounce = 1, window = 1.5, result is -1
"""
if h <= 0 or bounce <= 0 or bounce >= 1 or window >= h:
return -1
count = 1
while h * bounce > window:
h *= bounce
count += 2
return count
| true |
949e4fb5b68606e28047f3b62870a4ad1382c772 | Daniel-Loaiza/M8 | /exercise.py | 2,563 | 4.21875 | 4 | import json, requests, urllib
import os
import pandas as pd
def findPlayers():
"""Searches through NBA player heights based on user input.
The function receives a single integer input. Then it prints
a list of all pairs of players whose height in inches adds up
to the integer input to the application. If no matches are
found, the application will print "No matches found".
Typical usage example:
Type a number
>139
-Nate Robinson Mike Wilks
-Nate Robinson Brevin Knight
Args:
height: A decimal positive integer.
"""
url = 'https://mach-eight.uc.r.appspot.com/'
response = urllib.request.urlopen(url)
data = json.loads(response.read()) # Download data from website
df = pd.DataFrame(data['values']) # Transform data into pandas DataFrame
convert_dict = {'first_name':str,
'h_in':int,
'h_meters':float,
'last_name':str}
df = df.astype(convert_dict)
df=df.sort_values(by=['h_in']) #Sort pandas DataFrame with time complexity O(NlogN)
df.reset_index(drop=True, inplace=True)
try:
height = int(input("Type a number\n"))
# Check input
if isinstance(height, int)!=True:
raise TypeError('Work with Numbers Only')
elif height < 0:
raise ValueError('Work with Positive Numbers Only')
else:
counter = 0
left = 0
right = df.shape[0]-1
temp=right
while(left<right): #Notice we are only using a While loop (Two embedded for loops would take a time complexity of O(N**2)
if((df['h_in'][left]+df['h_in'][right])>height):
right -= 1
temp=right
elif ((df['h_in'][left]+df['h_in'][right])<height):
left += 1
elif((df['h_in'][left]+df['h_in'][right])==height):
counter +=1
print("-{} {}\t{} {}".format(df['first_name'][left],df['last_name'][left],df['first_name'][right],df['last_name'][right]))
right -= 1
if(left==right):
right=temp
left += 1
if counter==0:
print("No matches found")
except ValueError as ve:
print('You are supposed to enter positive number.')
input()
if __name__=="__main__":
findPlayers()
| true |
e3aa663f97280ecf64252505cb41617f297771fa | PerseuSam/FATEC-MECATRONICA-0791811039-SAMUEL | /LTPC1-2020-2/Prova1/exerci3.py | 303 | 4.1875 | 4 | numeros = []
continuar = True
while continuar == True:
numero = int(input("Informe um número: "))
numeros.append(numero)
if input("Deseja continuar (s/n)? ") == 's':
continuar = True
else:
continuar = False
valor_medio = sum(numeros)/len(numeros)
print("Valor médio: ",valor_medio)
| false |
50c7ac81f5b8e8123290ecd3d50df1d6430ac873 | manalelbaz/Test | /Exercise5.py | 423 | 4.125 | 4 | #print out the console the integer numbers from 30 to 300
for num in range(30, 300):
#multiples of 7
if (num%7==0 and num%13!=0):
print num, "-->", "abc"
#multiples of 13
elif(num%13==0 and num%7!=0):
print num, '-->', 'xyz'
#multiples of 7 and 13
elif(num%7==0 and num%13==0):
print num, '-->', 'a-z'
#if not
else:
print num
| true |
fb7a40488fb81d8c5213bec03ae6f52e40ab5dc1 | dmunozbarras/Pr-ctica-5-python | /ej5-11.py | 752 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""DAVID MUÑOZ BARRAS - 1º DAW - PRACTICA 5 - EJERCICIO 11
Escriu un programa per a jugar a endivinar un nombre (l'ordinador “pensa” el
nombre i l'usuari l'ha d'endevinar). El programa comença demanant entre què
nombres està el nombre a endevinar, s'”inventa” un nombre a l'atzar i després
l'usuari va probant valors i el programa va decidint si són massa grans o petits
"""
import random
print 'Bienvenido'
num=0
r=random.randrange(0,100)
while num <> r:
num=input("Adivina el numero entre 0 y 100: ")
if num > r:
print "Ingrese un numero mas pequeno"
if num < r:
print "Ingrese un numero mas grande"
print "Lo acertaste el numero era %d" % (num)
| false |
5e097f03a749d8dc72c5a25666d8b71b42d290f1 | Yesper888/HomeworkSolutions | /hw1.py | 576 | 4.125 | 4 | """
Homework #1 - Simple Calculator
Description: Write a program that takes as input 2 non-zero whole numbers.
Output the result of addition, subtraction, multiplication, normal divison,
floor division, modulo, and exponentiation of those 2 operands.
"""
print("Input 2 non-zero whole numbers")
a = int(input("INPUT THE FIRST NUMBER: "))
b = int(input("INPUT THE SECOND NUMBER: "))
print("Addition:",a+b)
print("Subtraction:",a-b)
print("Multiplication:", a*b)
print("Normal Division:",a/b)
print("Floor Division:",a//b)
print("Modulo:",a%b)
print("Exponentiation:",a**b)
| true |
8559c43f3a7b0d5905c30d80bb83655301986036 | MrCodeManTaylor/dataScience | /DataScience/Lab01.py | 2,013 | 4.1875 | 4 | #Mitchell Taylor | Lab 01 | Dr. Sethi | 22, January 2018
#1
def division():
print("\nNow running the division function\n")
x = 0
y = 1
x = int(input("Please enter your first digit\n"))
y = int(input("Please enter your second digit\n"))
z = x/y
print("Your answer is ",z)
def truncation():
print("\nNow running the truncation function\n")
x = 0
y = 1
x = int(input("Please enter your first digit\n"))
y = int(input("Please enter your second digit\n"))
z = x//y
print("Your answer is", z)
division()
truncation()
#2
def tempConverter():
print("\nNow running the temperature conversion function\n")
convertFactor = int(input("\nPlease enter 1 to convert from Celius to Farenheit, 2 for Farenheit to Celcius, anything else to quit\n"))
if convertFactor == 1:
tempC = int(input("Please input the temperature in Celcius: \n"))
tempF = tempC / (5.0 / 9.0) + 32.0
print(tempC, " C = ", tempF, " F")
elif convertFactor == 2:
tempF = int(input("Input the temperature in Farenheit: \n"))
tempC = (5.0/9.0) * (tempF - 32.0)
print(tempF, " F = ", tempC, " C")
else:
print("\nOkay, quitting.\n")
tempConverter()
#3
def factPrint():
print("\nNow running the factorial printing function\n")
a = 1
b = 0
c = int(input("Please input your desired factorial\n"))
while b < c:
b = b+1
a = a * b
print(b, "! = ", a)
factPrint()
#4
def factPrintLimited():
print("\nNow running the factorial printing (Limited) function\n")
a = 1
b = 0
c = int(input("Please input your desired factorial\n"))
while b < c:
b = b+1
a = a * b
if a > 1000000000:
b = c
print("\nSorry this program will not print values exceeding 1,000,000,000!\n")
else:
print(b, "! = ", a)
factPrintLimited()
x = int(input("Please enter your desired factorial\n"))
facs = [facs[-1] for i in range(1,x) if not facs.append(i*facs[-1] if facs else 1)]
print(facs)
| false |
db3fafe6544510512fff35298fbf3cc5cf9f6c7d | lishuhuakai/demo | /demo_arg_func_ex.py | 594 | 4.1875 | 4 | #!/usr/bin/env python3
def mypower(x):
return x * x
print(mypower(9))
def mypower(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(mypower(9, 6))
#在这边调用mypower(6)的话会出现错误
#print(mypower(6))
def add_end(L=None):
if L is None:
L = []
L.append("END")
return L
print(add_end())
print(add_end())
#下面使用的是可变参数
def calc(numbers):
sum = 0
for n in numbers:
sum += n * n
return sum
print(calc([1, 2, 3, 4, 5]))
print(calc((1, 2, 3, 4, 5)))
def calc_ex(a, b, c):
return a + b + c
nums = [1, 2, 3]
print(calc_ex(*nums))
| false |
9812fb71c2d32f58b75060ffc1c3d9b96d3e7b23 | lishuhuakai/demo | /advanced_func.py | 539 | 4.125 | 4 | #!usr/bin/env python3
#求绝对值的函数
abs(-10)
x = abs(20)
f = abs
#f现在是函数了
print(f)
#结论:函数本身也可以赋值给变量,即变量可以指向函数
print(f(-10))
abs = 10
#下面的函数无法调用,因为abs现在已经指向10了
abs(-10)
#传入函数
def add(x, y, f):
return f(x) + f(y)
#x = -5
#y = 6
#f = abs
add(-5, 6, abs)
#总结:将函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式
| false |
697e4d13b5fbfac484636754aa43cc5f831623e9 | lishuhuakai/demo | /anoumous.py | 808 | 4.25 | 4 | #!/usr/bin/env python3
#当我们在传入函数的时候,不需要显式地定义函数,直接传入匿名函数集客
#python提供了对匿名函数的有限支持
list(map(lambda x : x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
#lambda就是匿名函数,这可真令人吃惊啊
#这样看来,匿名函数lambda x : x * x实际上就是
def f(x):
return x * x
#关键字lambda表示匿名函数,冒号前面的x表示函数参数
#匿名函数有一个限制,就是只能有一个表达式,不用写return
#此外匿名函数也是一个函数对象也可以将匿名函数赋值给一个变量,再利用变量来调用该函数
j = lambda x : x * x
print(j)
print(j(5))
#同样的,也可以将匿名函数作为返回值返回,如:
def build(x, y):
return lambda: x * x + y * y
| false |
6b4e0e3658b62ca911f0fbfb7f29ba77be05572d | ariellacentlivre/Python_exercises | /ex6.py | 1,486 | 4.65625 | 5 | # setting x variable equal to a string containing a raw data value,
# at the end of the string we use the formatter to state the raw data value
x = "There are %r types of people." %10.023
# setting the binary variable equal to a string
binary = "binary"
# setting the do_not variable equal to a string
do_not = "don't"
# setting the y value equal to a string which contains two string formatters
# at the end of the string, we use the formatter to insert these values into the variable string
y = "Those who know %s and those who %s" % (binary, do_not)
# print the variable x
print x
#print the variable y
print y
# print the string with the raw data formatter, at the end we tell it the raw data formatter is x
print "I said: %r." %x
# print the string with the string formatter, at the end we tell it the string formatter is y
print "I also said: '%s'." %y
# setting the variable hilarious equal to a boolean value true
hilarious = True
# setting the variable joke_evaulation equal to a string with a string formatter included in the quotes
joke_evaulation = "Isn't that joke so funny?! %s"
# print to the console, the string with the answer being the variable hilarious
print joke_evaulation %hilarious
# setting the variable w equal to a string
w = "This is the left side of ..."
# setting the varialble e equal to a string
e = "a string with a right side."
# printing w plus e will concatinate the two strings (bring them together to make one string)
print w + e
| true |
223554ad98cc6146321dbc212ae3136aa84eb31e | rizvi/python-tpoint | /LargestNumberAmong3.py | 390 | 4.21875 | 4 | firstNumber = 555
secondNumber = 888
thirdNumber = 555
if firstNumber > secondNumber:
if firstNumber > thirdNumber:
print(firstNumber, 'is the largest number')
else:
print(thirdNumber, "is the largest number")
else:
if secondNumber > thirdNumber:
print(secondNumber, 'is the largest number')
else:
print(thirdNumber, 'is the largest number') | true |
f9efbcb5654a2a4503a0a4450cb45493448bd30b | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day06-shibw/demo02-列表推导式及嵌套.py | 1,162 | 4.1875 | 4 | '''
列表推导式
快速的将可迭代对象变成列表
'''
# list01 = [10,1,15,5,6,7]
# #将list01中的每一个数加一放到list02中
# list02 = []
# for item in list01:
# list02.append(item+1)
# print(list02)
# #从可迭代对象list01中获取元素
# #将元素带入到前面的表达式item+1
# #将结果保存到列表 继续从list01获取下一个元素 直到没有元素为止
# list03 = [item+1 for item in list01]
# print(list03)
#
# list04 = []
# for item in list01:
# if item >= 10:
# list04.append(item+1)
# print(list04)
# #从可迭代对象list01中获取元素
# #先做判断 如果结果为False 取下一个元素继续判断
# #如果结果为True 将元素带入到前面的表达式
# # 将结果保存到列表 重复执行
# list05 = [item+1 for item in list01 if item >= 10]
# print(list05)
#列表推导式嵌套
list01 = [1,2,3]
list02 = [4,5,6]
# list03 = []
# # 将两个列表中所有的值分别相加 将结果保存到list03
# for item1 in list01:
# for item2 in list02:
# list03.append(item1+item2)
#
list03 = [item1+item2 for item1 in list01 for item2 in list02]
print(list03)
| false |
77982311e3b867583ea93779907b205303bb29a7 | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day06-shibw/demo01-索引切片概念区分.py | 361 | 4.125 | 4 | list01 = ['a','b','c']
list01[0] = ['A','B']
print(list01)#[['A','B'],'b','c']
#将右边列表的值赋值给list01的第一个位置
list01[1:2] = ['哪吒']
#序列赋值
print(list01)#[['A','B'],'哪吒','c']
list02 = list01[::-1]
print(list02)#['c','哪吒',['A','B']]
print(list01[0] is list02[-1])#True
list01[0] = '李靖'
print(list02[-1]) #['A', 'B'] | false |
0de07f767f199eab2cd307d4544fb70facad387c | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day19-qitx/review01.py | 2,506 | 4.1875 | 4 | """
python语言基础
1. 程序运行过程:
源代码--编译 -->字节码--解释-->机器码
|----1次-----|
|-----------运行时------------|
2. pycharm常用快捷键(百度搜索)
3. python内存管理
引用计数:
定义:每个对象存储被引用的次数,如果数量为零,则"销毁".
缺点:存在循环引用的现象.
标记清除:
定义:在内存容量不够时,从栈帧中开始扫描内存,标记正在使用的对象.
(不被使用的对象,即为可回收)
缺点:扫描内存耗时长.
分代回收:
定义:根据回收频次将内存分为多个区域("青年代","中年代","老年代")
避免每次扫描时范围过大.
优化:
尽少产生垃圾,对象池(小整数对象池/字符串池..),手动回收(慎重)
4. 容器
种类:字符串(只存字符编码值)/列表(预留空间)/元组(按需分配)/字典(单个元素读写速度最快)/集合(不重复/数学运算)
内存图:......
通用操作:+ * 比较 in 索引/切片
5. 函数
设计原则:单一职责
参数:
实参 -- 调用时
位置实参 (1,2,3)
序列实参 (*[1,2,3]) 备注:拆
关键字实参 (a = 1,b = 2)
字典关键字实参(**{"a":1,"b":2})备注:拆
形参 -- 定义时
默认形参(a = 1,b = "")
位置形参(a,b)
星号元组形参(*args) 备注:合
命名关键字形参(*,b) (*args,b)
双星号字典形参(**kwargs) 备注:合
万能参数(*args,**kwargs)
"""
# 3.内存管理
# 循环拼接字符串
# str_result = ""
# for i in range(100):
# # 两个字符串拼接后产生新字符串,替换str_result存储的引用后,产生垃圾.
# str_result =str_result + str(i)
list_result = []
for i in range(100):
list_result.append(str(i))
str_result = "".join(list_result)
print(str_result)
# 4.容器
list01 = [3,4,54,6,7]
# 切片获取数据时创建新列表(拷贝原始数据)
list02 = list01[1:4]
list02[0] = "qtx"
print(list01)
# 切片修改数据时不创建新列表
list01[1:4] = ["qtx"]
| false |
c15f9b8587ba501996a3cdf245b505fcff5598c4 | Jeremy277/exercise | /pytnon-month01/month01-class notes/day10-fb/demo02.py | 527 | 4.21875 | 4 | class Wife:
pass
w01 = Wife()
w01.name = '赵敏'
print(w01.name)
# w02 = Wife()
# print(w02.name)#AttributeError: 'Wife' object has no attribute 'name'
#可以通过
print(w01.__dict__)#{'name': '赵敏'}
# print(w02.__dict__)
class Wife2:
#构造函数,添加实例变量
def __init__(self,name,age):
self.name = name
self.age = age
#实例方法
def print_self(self):
print(self.name,self.age)
w01 = Wife2('zhaomin',28)
w01.print_self()
Wife2.print_self(w01)#不建议使用 | false |
c993cb19a383c3c40668e3d534961c6269c11c5c | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day03-shibw/exercise01-if.py | 999 | 4.125 | 4 | #练习在控制台获取一个季度 (春夏秋冬)
#显示相应的月份
#春 1月2月3月
#夏 4 5 6
#秋 7 8 9
#冬 10 11 12
season = input('请输入季度:')
#方法一
# if season == '春':
# print('1月2月3月')
# if season == '夏':
# print('4月5月6月')
# if season == '秋':
# print('7月8月9月')
# if season == '冬':
# print('10月11月12月')
#方法二 调试方法一和方法二 观察区别
if season == '春':
print('1月2月3月')
elif season == '夏':
print('4月5月6月')
elif season == '秋':
print('7月8月9月')
elif season == '冬':
print('10月11月12月')
#调试:
# 让程序中断 逐行执行
# 目的 审查程序运行时的变量以及变量取值
# 审查程序运行的流程
#步骤:
#1.加断点 (调试过程中遇到断点就停止程序)
#可能会出问题/你想详细了解的地方加断点
#2.运行调试Shift+F9
#3.程序会在断点处停止 按F8执行一行
#4.按Ctrl+F2停止调试 | false |
508bd2e0ca87f379eab4a52cbec6e1f3ac252a02 | Jeremy277/exercise | /pytnon-month01/month01-class notes/day17-fb/exercise07.py | 570 | 4.34375 | 4 | """
练习3:
自定义生成器函数my_enumerate,实现下列效果.
list01 = ["无忌","翠山","翠翠"]
for item in enumerate(list01):
print(item)# item 是元组类型(索引,元素)
15:30上课
"""
def my_enumerate(iterable_target):
index = 0
for item in iterable_target:
yield (index,item)
index +=1
list01 = ["无忌","翠山","翠翠"]
for item in my_enumerate(list01):
print(item)# item 是元组类型(索引,元素)
for index,element in enumerate(list01):
print(index)
print(element) | false |
1d95915a48153881c3b642d52101e77d189ac4c8 | Jeremy277/exercise | /pytnon-month01/month01-shibw-notes/day07-shibw/demo06-函数return.py | 640 | 4.125 | 4 | #定义一个两个数字相加的函数
#所有函数都有返回值
#函数通过return语句将值返回给函数调用者
#返回的位置就是函数调用的位置
#如果没有写return语句 默认返回None
def myadd(num1,num2):
# result = num1+num2
# return result
#返回结果 退出函数
return num1+num2
#return语句后的代码不会执行
print(num1+num2)
#要不要写return语句取决于用户是否需要再次处理函数的结果
#如果需要再次处理就必须通过return返回结果
# print(myadd(10,20))
result = myadd(10,20)
#输出 结果是30
print('结果是%s' % result ) | false |
53ba07c8833562d9e49f914f8b113194724de300 | Jeremy277/exercise | /资料data/pyth自学预习7.11-7.30/demo24字典英译汉字典游戏.PY | 2,038 | 4.3125 | 4 | #访问字典值
# dictionary = {"love": "爱","hate" : "恨"}
# dictionary["love"]
# print(dictionary["love"])
# if 'hate' in dictionary:
# print('在字典中')
# else:
# print('不在字典中')
# print(dictionary.get('hate'))
# 英译汉游戏
dictionary = {"love": "爱","hate" : "恨"}
choice = None
while choice != '0':
print('''
英译汉字典
0 - 退出
1 - 查询
2 - 添加
3 - 修改定义
4 - 删除
5 - 字典''')
choice = input('请选择:')
if choice == '0':
print('再见')
elif choice == '1':
term = input('请输入需要查询的条目:')
if term in dictionary:
definition = dictionary[term]
print('\n%s的汉语是%s' % (term,definition))
else:
print('\n查无此项')
elif choice == '2':
term = input('请输入需要添加的条目:')
if term not in dictionary:
definition = input('请输入该单词的汉语')
dictionary[term] = definition
print('\n%s添加完成' % term)
else:
print('\n该单词已存在')
elif choice == '3':
term = input('请输入需要修改的单词:')
if term in dictionary:
definition = input('请输入该单词的汉语:')
dictionary[term] = definition
print('\n%s修改完成' % term)
else:
print('\n查无此项')
elif choice == '4':
term = input('请输入需要删除的条目:')
if term in dictionary:
del dictionary[term]
print('\n%s删除完成' % term)
else:
print('\n查无此项')
elif choice == '5':
print(dictionary)
print(dictionary.items())
print(dictionary.keys())
print(dictionary.values())
else:
print('输入非法,请重新选择')
input('\n按下回车键退出。')
| false |
b3579ff4378a7535d3e7c690a23a228d9a6d1e9e | pratikbitmesra/DataStructures-from-Undergrad | /BFS_2.py | 1,450 | 4.28125 | 4 | # -*- coding: cp1252 -*-
'''
BFS_2 Method 2
http://www.geeksforgeeks.org/level-order-tree-traversal/
For each node, first the node is visited and then its child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_nodes children (first left then right children) to q
c) Dequeue a node from q and assign its value to temp_node
'''
import os
import sys
import operator
import csv
import itertools
import math
import collections
import gc
from itertools import groupby
from sys import argv
from operator import itemgetter, attrgetter, methodcaller
from sys import maxsize
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printLevelOrder(root):
if root is None:
return
queue = []
queue.append(root)
while len(queue)>0:
print queue[0].data
node = queue.pop(0)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
def main():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Level Order Traversal of binary tree is -"
printLevelOrder(root)
main()
| true |
400939066713d04cc3350393365dd02b9db1696e | pratikbitmesra/DataStructures-from-Undergrad | /postfix_eval.py | 2,513 | 4.28125 | 4 | # Postfix Exp evaluation
# Python program to evaluate value of a postfix expression
# http://quiz.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/
# Infix expression:The expression of the form a op b. When an operator is in-between every pair of operands.
# Postfix expression:The expression of the form a b op. When an operator is followed for every pair of operands.
import os
import sys
import operator
import csv
import itertools
import math
import collections
from itertools import groupby
from sys import argv
from operator import itemgetter, attrgetter, methodcaller
from sys import maxsize
class Evaluate:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
# check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
# Return the value of the top of the stack
def peek(self):
return self.array[-1]
# Pop the element from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
# Push the element to the stack
def push(self, op):
self.top += 1
self.array.append(op)
# The main function that converts given infix expression
# to postfix expression
def evaluatePostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the scanned character is an operand
# (number here) push it to the stack
if i.isdigit():
self.push(i)
# If the scanned character is an operator,
# pop two elements from stack and apply it.
else:
val1 = self.pop()
val2 = self.pop()
self.push(str(eval(val2 + i + val1)))
return int(self.pop())
def main():
exp = "231*+9-"
obj = Evaluate(len(exp))
print "Value of %s is %d" %(exp, obj.evaluatePostfix(exp))
main()
| true |
712eac28035488ac1ff88461806e82a81262482f | prakashabhinav/Data-Science | /4. UC - Practice - Python Std Dev and Variance.py | 2,578 | 4.5 | 4 | # -*- coding: utf-8 -*-
"""
Udemy Course - Python Basics Std Dev and Var : 28-May-2019
"""
# Standard Deviation and Variance
# Variance - Measures how "spread out" the data is
# Variance - Average of the squared differences from the mean
# Standard Deviation - Square root of the variance
# Variance and Standard Deviation - Helps to identify outliers
# Population Mean : μ = ( Σ Xi ) / N
# Population Variance : σ2
# Sample Mean : M = ( Σ Xi ) / N
# Population and Sample
# Population Variance uses N, Sample Variance uses N- 1
# Import required libraries
import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance
import matplotlib.pyplot as plt # Makes graphs for visualisation
# Generate random income numbers - Set 1
incomes = np.random.normal(100.0, 20.0, 10000) # Generate random income numbers
# Segment the income data into 50 buckets, and plot it as a histogram
plt.hist(incomes, 50) # Segments the data into 50 buckets
plt.show() # Display the histogram
# Calculate Standard Deviation
incomes.std() # Display the standard deviation
# Calculate Variance
incomes.var() # Display the variance
# Generate random income numbers - Set 2
incomes = np.random.normal(100.0, 50.0, 10000) # Generate random income numbers
# Segment the income data into 50 buckets, and plot it as a histogram
plt.hist(incomes, 50) # Segments the data into 50 buckets
plt.show() # Display the histogram
# Calculate Standard Deviation
incomes.std() # Display the standard deviation
# Calculate Variance
incomes.var() # Display the variance
# Generate random income numbers - Set 3
incomes = np.random.normal(100.0, 75.0, 10000) # Generate random income numbers
# Segment the income data into 50 buckets, and plot it as a histogram
plt.hist(incomes, 50) # Segments the data into 50 buckets
plt.show() # Display the histogram
# Calculate Standard Deviation
incomes.std() # Display the standard deviation
# Calculate Variance
incomes.var() # Display the variance
## End of Practice ## | true |
d2da645c317ac25f4902a660b1eeb7e299a54960 | mikefeneley/biomancer | /biomancer/newtrash.py | 712 | 4.59375 | 5 | #print("To numerically investigate the limit of a sequence, I referenced a function that returns the nth element of the sequence:")
#print("t_0 = sqrt(1+0)")
#print("t_1 = sqrt(1+1)")
#print("t_2 = sqrt(1+2)")
#print("t_3 = sqrt(1+2*sqrt(1+3))")
#print("t_4 = sqrt(1+2*sqrt(1+3*sqrt(1+4)))")
#print("t_5 = sqrt(1+2*sqrt(1+3*sqrt(1+4*sqrt(1+5))))")
#print("etc.")
import math
def ramanujan_sqrt_sequence(n):
if n == 1:
t_n = math.sqrt(2)
else:
t_n = 1
for i in range(n,1,-1):
t_n = math.sqrt((i*t_n)+1)
print(t_n)
n = int(input("The nth element of your sequence is:"))
print(ramanujan_sqrt_sequence(n))
print("As n goes to infinity, the value of the nth element of the sequence will tend to 3.")
| true |
ee1c16c73ee1512204b23daec342b93885bf7b96 | arunatma/LearnPythonTheHardWay | /ch03.py | 913 | 4.40625 | 4 | print "Handwritten by Arunram A"
print "Handwrite - Do not copy paste, is the most important rule of this book"
print "Learn Python the Hard Way - Zed A. Shaw"
print "Chapter 3 - Numbers and Math"
print "I will do some arithmetic expressions"
print "Total runs", 45 + 52 + 33
print "Total wickets by bowlers", 22 -2 + 11
print "Batting Average", 25 + 13/2 - 2 * 4/3 *6
print "Now I will count the eggs"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "Is 5 greater than -2?", 5 > -2
print "Is 5 greater than or equal to -2?", 5 >= -2
print "Is 5 less than or equal to -2?", 5 <= -2
print "13/2 is 6 in python2.x, but 6.5 in python3.x"
print "1 + 2 - 3/4 evaluates to be equal to ", 1 + 2 - 3/4
print "1 + 2 - 3.0/4 evaluates to be equal to ", 1 + 2 - 3.0/4
dummy_variable = raw_input("Keyboard stroke; use raw_input in python2.x and input in python3.x") | true |
12ea5ae394e81a9d218dc55104f25971ee43fbca | arunatma/LearnPythonTheHardWay | /ch21.py | 836 | 4.5 | 4 | print "Chapter 21 - Functions can return something"
def add(a, b):
print "Addition of %d and %d" % (a, b)
return a + b
def subtract(a, b):
print "Subtract %d from %d i.e (%d - %d)" % (b, a, a, b)
return a - b
def multiply(a, b):
print "Multiplication: %d * %d" % (a, b)
return a * b
def divide(a, b):
print "Division: %d / %d" % (a, b)
return a / b
print "Now, the fuction calls for the defined functions!"
sum = add(3, 4)
difference = subtract(6, 2)
product = multiply(3, 7)
quotient = divide(19, 8)
print "Sum: %d, Difference: %d, Product: %d, Quotient: %d" % (sum, difference,
product, quotient) # Going above 80 characters, so cutting it out
# Using all the functions together!
final_value = add(sum, subtract(difference, multiply(product,
divide(quotient, 2))))
print "The final value is: ", final_value
| true |
20d06ca62193636592e1ba973090ccd670770e4c | arunatma/LearnPythonTheHardWay | /ch16.py | 1,741 | 4.28125 | 4 | print "Chapter 16 - Reading and Writing Files"
# open - opens a file for operations (read / write) - default is read
# close - closes the file handle
# read - reads the entire contents of the file
# readline - reads a single line
# truncate - deletes the entire content of the file referenced by the filehandle
# write("...") - writes the quoted string into the given file handle
# 'sys' is the module from which just 'argv' class is imported
from sys import argv
script, filename = argv
print "We're going to erase %r" % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you are okay with the erasing, hit ENTER"
raw_input("?")
# w for write, r for read and a for append
# Also there is w+, r+ and a+ to open in both read and write mode
print "Opening the file... (with write access)"
# Opening in write mode itself, would truncated the file
# target.truncate() is just redundant
target = open(filename, 'w')
print "Truncating the file."
target.truncate()
print "The file is now truncated - Contents Erased!"
print "Okay, let us write some new lines into the file."
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
print "These three lines are to be written to %r" % filename
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
# The following is another way of writing the same contents
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
# Okay, that was with concatenation, now this is with string formatting
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
print "Final Step: Close the file!"
target.close()
# Execute the script from the command line. This script takes in 1 argument
| true |
ea07612e165eef2e1dba2d166b87670d523277a8 | Mav-erick99/very-basic-python-stuff | /lists.py | 646 | 4.25 | 4 | friends=["tom","dick","harry","rick","tim"]
print(friends)
print(friends[2])
print(friends[-1]) #no from the back
print(friends[1:3]) #all elements upto but not 3
friends[1]="dom"
print(friends[1])
enemies=["emienem","rocky","rambo",50,"gaga",69,"gaga"]
print(enemies)
friends.extend(enemies)
print(friends)
friends.append("dre")
print(friends)
friends.insert(2,"kesha")
print(friends)
friends.pop() #gets rid of last element
print(friends)
print(friends.index("rocky"))
print(friends.count("gaga"))
num=[76,45,72,34,53,56]
#print(num.sort())
#print(num.reverse())
num2=num.copy()
print(num2)
friends.clear
print(friends) | true |
0a6f7ec6cddb45d86839463f283e038c1fa8832a | HanSolo7/online-python-aug-2016 | /Solutions/Fundamentals/scores_grades.py | 822 | 4.1875 | 4 | # Write a function that collects a bunch of inputs
def collect_inputs(times):
scores = []
for i in range(times):
scores.append(input("Enter a score:"))
# Scores is a list of numbers
return scores
# Run a loop based on the times variable
# Collect an input each time
def print_scores(scores):
print "Scores and Grades: "
for score in scores:
# This will print out a sentence
print_score_string(score)
print "End of program"
# Write a function that can generate score string
def print_score_string(score):
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print "Score: {} .... Your grade is {}".format(score, grade)
print_scores( collect_inputs(10) )
| true |
b59c43b98a96bda788c975db90a8345ac7feea87 | nikolajlauridsen/SimpleClassicAlgorithms | /collatz_conjecture.py | 602 | 4.25 | 4 | """
A python implementation of the collatz conjecture
"""
def collatz(number):
if number % 2 == 0:
number //= 2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
run_throughs = 0
int_number = int(input("Please input a whole number: "))
while True:
if int_number != 1:
int_number = collatz(int_number)
run_throughs += 1
elif int_number == 1:
print("You've reached " + str(int_number) )
print("It took: " + str(run_throughs) + " steps")
break
| true |
ac54c01d2a899e9c1b075c11d4080640f8823deb | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio182.py | 1,016 | 4.28125 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
import random
"""
Confeccionar una programa con las siguientes funciones:
1) Generar una lista con 4 elementos enteros aleatorios comprendidos entre 1 y 3. Agregar un quinto elemento con un 1.
2) Controlar que el primer elemento de la lista sea un 1, en el caso que haya un 2 o 3 mezclar la lista y volver a controlar hasta que haya un 1.
3) Imprimir la lista.
"""
def generar():
lista = []
for x in range(4):
valor = random.randint(1,3)
lista.append(valor)
lista.append(1)
print(lista)
return lista
def imprimir(lista):
print(lista)
"""
def checar(lista):
if lista[0] == 1:
pass
else:
while lista[0] > 1:
imprimir(lista)
if lista[0] == 1 or lista[0] == 2 or lista[0] == 3:
lista = random.shuffle(lista)
print(lista)
"""
def checar(lista):
while lista[0]!=1:
random.shuffle(lista)
lista = generar()
checar(lista)
imprimir(lista)
| false |
35a01faee79192b1c520d96b0cf2483b2070d0fb | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio82.py | 532 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Ingresar por teclado los nombres de 5 personas y almacenarlos en una lista. Mostrar el nombre de persona menor en orden alfabético. """
nombres=[]
for x in range(5):
nom=input("Ingrese nombre de persona:")
nombres.append(nom)
nombremenor=nombres[0]
for x in range(1,5):
if nombres[x]<nombremenor:
nombremenor=nombres[x]
print("La lista completa de nombres ingresado son")
print(nombres)
print("El nombre menor en orden alfabetico es:")
print(nombremenor)
| false |
4c6e8b2941fb07beedf8749f9db3f57b78ba670a | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio189.py | 1,986 | 4.5 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Desarrollar un programa que cargue los lados de un triángulo e implemente los siguientes métodos: inicializar los atributos,
imprimir el valor del lado mayor y otro método que muestre si es equilátero o no. El nombre de la clase llamarla Triangulo.
"""
#Se hace la clase Triangulo
class Triangulo:
#Hacemos el primer metodo que es para inicializar los valores
def inicializar(self):
#Hacemso una lista vacia
lista = []
#Se hace un for para ingresar en la lista tres valores
for x in range(3):
#Ingresamos en la variable valor el valor que queramos
valor = float(input("Ingrese el valor del lado:"))
#Agregamos a la lista el valor que acabamos de ingresar
lista.append(valor)
#Hacemos el atributo lado y en este le agregamos la lista
self.lados = lista
#Hacemos el segundo metodo para imprimir la la lista en este caso el atributo lados
def imprimir(self):
#En este metodo lo que se hace es dar opciones, hacemos una variable para ir en una de las dos opciones
s = input("¿Quiere ver su lados impresos verticalmente? [s/n]")
#Nos dice que si la variable s es igual a s o S o tambien a si, esta va a ejecutar el for que en teoria va a listar los datos de la lista
if s == "s" or s == "S" or s == "si":
for elemento in self.lados:
print(elemento)
#Si no se imprime la lista normal que es el atributo lados
else:
print(self.lados)
#Hacemos un metodo para checa los datos que estan en la lista
def checar(self):
if self.lados[0] == self.lados[1] and self.lados[0] == self.lados[2]:
print("Es equilatero")
else:
print("No es equilatero")
def main():
lista_lados = Triangulo()
lista_lados.inicializar()
lista_lados.imprimir()
lista_lados.checar()
main()
| false |
35b59f182c7139a841db1529fb5f8543197501b5 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio15.py | 1,408 | 4.6875 | 5 | """ Se cargan por telcado tres numeros distintos. MOStrar por pantalla el mayor de ellos """
num1 = int(input("Ingrese el primer numero: "))
num2 = int(input("Ingrese el segudo numero: "))
num3 = int(input("Ingerse el tercer numero: "))
"""
if num1>num2 & num1>num3:
print("El numero mayor es el uno : " + num1)
else:
if num2>num1 & num2>num3:
print("El numero mayor es el dos :" + num2)
else:
print("El numero tres es el mayor") """
"""
if num1>num2:
if num1>num3:
print("El numero uno es el mas grade")
else:
if num2>num1:
if num2>num3:
print("El numero dos es el numero mas grande")
else:
if num3>num1:
if num3>num2:
print("El numero tres es el numero mayor")
print(num3)
"""
if num1>num2: #Se hace la primera condicion, si esta no pasa, no se puede ir a chechar a la segunda condicion
if num1>num3: #Ya que se cumplio la condicion anterior, esta se tiene que cumplir para imprimir el numero
print(num1)
else:
print(num3) #Si la segunda condicion no se cumple se va a ir al esle, ya teniendo en cuenta de que la primera condicion se cumplio y teniendo en cuenta de que la segunda condicion no se cumplio es porque el numero es mas grande que 1 y mas que 2
else: #Si el primer bloque de condicion no se cumple, pasara al siguiente que estaria comparando al numero 2
if num2>num3:
print(num2)
else:
if num2<num3:
print(num3)
| false |
bdab8f7f3dc97535fb348faadc694e2140f91e51 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio201.py | 2,196 | 4.34375 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Ahora plantearemos otro problema empleando herencia. Supongamos que necesitamos implementar dos clases que llamaremos Suma y Resta. Cada clase tiene como atributo valor1, valor2 y resultado. Los métodos a definir son cargar1 (que inicializa el atributo valor1), carga2 (que inicializa el atributo valor2), operar (que en el caso de la clase "Suma" suma los dos atributos y en el caso de la clase "Resta" hace la diferencia entre valor1 y valor2), y otro método mostrar_resultado.
Si analizamos ambas clases encontramos que muchos atributos y métodos son idénticos. En estos casos es bueno definir una clase padre que agrupe dichos atributos y responsabilidades comunes.
La relación de herencia que podemos disponer para este problema es:
Operacion
Suma Resta
"""
class Operacion:
def __init__(self):
self.valor1 = 0
self.valor2 = 0
self.resultado = 0
def cargar1(self):
self.valor1 = int(input("Ingrese el valor numero uno:"))
def cargar2(self):
self.valor2 = int(input("Ingrese el segundo valor: "))
def mostrar_resultado(self):
print(self.resultado)
def operar(self):
pass
"""
En Python para indicar que un método está vacío se utiliza la palabra clave "pass".
En el bloque principal de nuestro programa no creamos objetos de la clase Operación. La clase Operación tiene sentido que otras clases hereden de esta.
Tanto la clase Suma y Resta heredan de la clase Operación y reescriben el método operar con la funcionalidad que le corresponde a cada clase:
"""
class Suma(Operacion):
def operar(self):
self.resultado=self.valor1 + self.valor2
class Resta(Operacion):
def operar(self):
self.resultado = self.valor1 - self.valor2
# bloque princpipal
suma1=Suma()
suma1.cargar1()
suma1.cargar2()
suma1.operar()
print("La suma de los dos valores es")
suma1.mostrar_resultado()
resta1=Resta()
resta1.cargar1()
resta1.cargar2()
resta1.operar()
print("La resta de los valores es:")
resta1.mostrar_resultado()
| false |
0d049a79167e09853f33c6cd47e9e1cfe2e36293 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio67.py | 1,193 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Ingresar una oración que pueden tener letras tanto en mayúsculas como minúsculas.
Contar la cantidad de vocales. Crear un segundo string con toda la oración en minúsculas para que sea más fácil disponer la condición que verifica que es una vocal."""
oracion_normal = input("Ingrese su oracion: \n")
x = 0
contador_vocales = 0
while x < len(oracion_normal):
if oracion_normal[x] == "a" or oracion_normal[x] == "e" or oracion_normal[x] == "i" or oracion_normal[x] == "o" or oracion_normal[x] == "u":
contador_vocales += 1
x += 1
print("El numero de vocales que tiene su frase es de {} vocales".format(contador_vocales))
def volver_mayus():
decision = input("Quiere volver su oracion en mayúsculas? [y/n]: ")
if decision == "y":
decision_bool = True
if decision == "n":
decision_bool = False
if decision_bool == True:
print("Vamos volver a su frase a mayúsculas")
oracion_mayusculas = oracion_normal.upper()
print(oracion_mayusculas)
else:
print("Pues no se va a poder convertir en mayuscula su frase {}".format(oracion_normal))
volver_mayus()
| false |
30ea9f5dedcbb1c730220fb88a04d2bc8ee7d7ed | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio185.py | 1,148 | 4.375 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Calcular el factorial de un número ingresado por teclado.
El factorial de un número es la cantidad que resulta de la multiplicación de determinado número natural por todos los números naturales que le anteceden excluyendo el cero. Por ejemplo el factorial de 4 es 24, que resulta de multiplicar 4*3*2*1.
No hay que implementar el algoritmo para calcular el factorial sino hay que importar dicha funcionalidad del módulo math.
El módulo math tiene una función llamada factorial que recibe como parámetro un entero del que necesitamos que nos retorne el factorial.
Solo importar la funcionalidad factorial del módulo math de la biblioteca estándar de Python.
"""
#Del modulo math importamos la funcion factorial y le ponemos como alias a esta la palabra k_l
from math import factorial as k_l
#Ingresamos el valor que va a hacer la funcion factorial
valor = int(input("Ingrese el valor: "))
#Guardamos en una variable el resultado de la funcion con el valor para asi despues mostrarla
resultado = k_l(valor)
#Imprimos el valor de la funcion
print("El factorial es {}".format(resultado))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.