blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1a4070828915c305dddb9d6fd3652a834c1e795c
vasudha921/pythonclass3
/fileorganizer.py
1,105
4.34375
4
import os import shutil # write the name of the directory here that needs to go sorted path = input("Enter the name of the directory to be sorted") # This will create a properly organized list with all the files that are in the directory listoffiles = os.listdir(path) # This will go through each and every file in the directory for file in listoffiles: # splittext() will split the file name into its name and extension in respective variables name,ext = os.path.splitext(file) # this is going to store the extension type # it takes out only the extension excluding '.' ext= ext[1:] # this forces the next iteration that is if it is a directory if ext == '': continue # this will move the file to the directory where the name 'ext' already exists if os.path.exists(path+'/'+ ext): shutil.move(path+'/'+file, path + '/'+ ext+ '/'+ file ) # this will create a new directory if the directory does not exist else : os.makedirs(path + '/'+ ext) shutil.move(path+'/'+file, path + '/'+ ext+ '/'+ file )
true
dc6340c1548a0c055c35784fdcff7d120f518b53
Fengzhengyong/syudy_doc
/python/collatz.py
421
4.125
4
def collatz(number): if number%2==0: print(number//2) return number//2 elif number%2==1: print(3*number+1) return 3*number+1 else: return def userInput(): print('Enter number:') num=input() try: num=int(num) except ValueError: print('ValueError: please input a int number!') while num!=1: num=collatz(num) userInput()
false
5e747b0e6e6745dad44b69b0b0a0a8e58f9882a2
theHinneh/Algorithms
/Multiples_of_3_and_5.py
487
4.375
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' add = 0 # a variable to store values for i in range(1000): # count from the range 0<= i < 1000 if i % 3 == 0 or i % 5 == 0: # check if there's a remainder when the value of 'i' is divided by 3 or 5 add += i # if true, add the value of i to add print(add) # display the final value of add
true
7e61dc3c02dc16e17e1fadb9075d2631313f4ed7
Tahlia-Jones/dto
/primary.py
2,686
4.75
5
#author: <Tahlia Jones> # date: <July 1, 2021> # --------------- Section 1 --------------- # # ---------- Integers and Floats ---------- # # you may use floats or integers for these operations, it is at your discretion # addition # instructions # 1 - create a print statement that prints the sum of two numbers # 2 - create a print statement that prints the sum of three numbers # 3 - create a print statement the prints the sum of two negative numbers print('the sum of 51 + 29 =', 51 + 29 ) print('the sum of 34 + 45 + 21 =', 34 + 45 + 21) print('the sum of -83 + -24 =', -83 + -24) # subtraction # instructions # 1 - create a print statement that prints the difference of two numbers # 2 - create a print statement that prints the difference of three numbers # 3 - create a print statement the prints the difference of two negative numbers print('the difference of 73 - 58 =', 73 - 58) print('the difference of 101 - 15 - 65 =', 101 - 15 - 65) print('the difference of -99 - -49 =', -99 - -49) # multiplication and true division # instructions # 1 - create a print statement the prints the product of two numbers # 2 - create a print statement that prints the dividend of two numbers # 3 - create a print statement that evaluates an operation using both multiplication and division print('the product of 25 * 7 =', 25 * 7) print('the dividend of 245 / 24 =', 245 / 24) print('24 * 35 / 12', 24 * 35 / 12) # floor division # instructions # 1 - using floor division, print the dividend of two numbers. print('the integer dividend of 245 / 34 =', 245 // 34) # exponentiation # instructions # 1 - using exponentiation, print the power of two numbers print('the power of 212 ^ 3 =', 212 ** 3) # modulus # instructions # 1 - using modulus, print the remainder of two numbers print('the reminder of 368 / 56 =', 368 % 56) # --------------- Section 2 --------------- # # ---------- String Concatenation --------- # # concatenation # instructions # 1 - print the concatenation of your first and last name # 2 - print the concatenation of five animals you like # 3 - print the concatenation of each word in a phrase print('Tahlia' + 'Jones') print('dogs' + 'tigers' + 'foxes' + 'starfish' + 'seahorses') print('it is raining cats and dogs') # duplication # instructions # 1 - print the duplpication of your first 5 times # 2 - print the duplication of a song you like 10 times print('baby snow tigers' * 5) print('wish I had it' * 10) # concatenation and duplpication # instructions # 1 - print the concatenation of two strings duplicated 3 times each
true
862baa083deee92f49c9ccab1a44c43648313411
aust10/smallProjects
/grading_practice.py
929
4.15625
4
print("Lets get to grading") def grading(): user_input= input("What is the grade 0-100? ") user_input = int(user_input) #grabs the last number of user grade and gives it a above or below grade = user_input % 10 if grade >= 6: grade = "+" elif grade == 5: grade = "" else: grade = "-" #below gives the final grade with the above or below if user_input >= 90: print(f"{grade}A") elif user_input >= 80 < 89: print(f"{grade}B") elif user_input >= 70 < 79: print(f"{grade}C") elif user_input >= 60 < 69: print(f"{grade}D") elif user_input >= 0 < 59: print(f"{grade}F") else: print("Invalid answer, Enter a valid number") grading() answer= input("Do you have more to do? y or n: ") if answer == "y": grading() else: print("Thank you for grading with me!") grading()
true
8b09d14f9295715a45c1b6b94257583f8297303a
pranavj1001/LearnLanguages
/python/SortingAlgorithms/ShellSort/ShellSort.py
1,031
4.1875
4
# Shell Sort # O(n(log(n))^2) for worst and average case def shell_sort(array): # length of the sublist of array sublistCount = int(len(array)/2) print(array) # loop till the sublist's length becomes 1 while sublistCount > 0: # perform insertion sort to every sublist for start in range(sublistCount): array = gap_insertion_sort(array, start, sublistCount) print("After gaps of ", sublistCount) print(array) sublistCount = int(sublistCount/2) print("\nSorted Array") return array # Logic for insertion sort def gap_insertion_sort(array, start, gap): for i in range(start + gap, len(array), gap): currentValue = array[i] pos = i while pos >= gap and array[pos-gap] > currentValue: array[pos] = array[pos-gap] pos = pos - gap array[pos] = currentValue return array array = [190, 2, 42, 8, 21, 11, 200, 13, 19] print(shell_sort(array))
true
5eaff4ec84bacd591ce6497e7c4ed1e4acfbb717
pranavj1001/LearnLanguages
/python/SortingAlgorithms/BubbleSort/BubbleSort.py
513
4.21875
4
# Bubble Sort # O(n^2) for worst and average case # a lot of swapping takes place here def bubble_sort(array): # for(int i = array.length - 1; i <= 0; i--) for i in range(len(array)-1, 0, -1): # for(int j = 0; j < i; j++) for j in range(i): # swap whenever a larger element is found if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array array = [14, 143, 53, 37, 453] print(bubble_sort(array))
true
1e9dc39451d30d35129422421c2a58ec1fe0d10d
pranavj1001/LearnLanguages
/python/DataStructures/AVLTrees/Node.py
2,008
4.15625
4
class Node(object): # constructor # here we will create a node and initialize its left and right child with None # also balance is used here to balance the AVL tree def __init__(self, data, parentNode): self.data = data self.parentNode = parentNode self.leftChild = None self.rightChild = None self.balance = 0 # method to insert nodes def insert(self, data, parentNode): # if the value of the data to be inserted is less than the current Node then go left if data < self.data: # if the leftChild is none then create node below it and the currentNode as its parentNode if not self.leftChild: self.leftChild = Node(data, parentNode) # traverse more else: self.leftChild.insert(data, parentNode) # if the value of the data to be inserted is more than the current Node then go right else: # if the rightChild is none then create node below it and the currentNode as its parentNode if not self.rightChild: self.rightChild = Node(data, parentNode) # traverse more else: self.rightChild.insert(data, parentNode) return parentNode # method to traverse in IN-ORDER way i.e. the left child + root node + the right child def traverseInorder(self): if self.leftChild: self.leftChild.traverseInorder() print(self.data) if self.rightChild: self.rightChild.traverseInorder() # method to get the maximum value def getMax(self): if not self.rightChild: return self.data else: return self.rightChild.getMax() # method to get the minimum value def getMin(self): if not self.rightChild: return self.data else: return self.leftChild.getMin()
true
2bae40380af6487804b922f933b26bc1dd00f93a
jhwsx/liaoxuefeng_python_tutorial_learning
/python_2/func_call.py
1,944
4.40625
4
# 调用 abs() 函数, 返回一个指定值:整数或浮点数的绝对值 print(abs(100)) print(abs(-20)) print(abs(12.34)) print(abs(-56.789)) # 错误演示一: # print(abs(1, 2)) # 报错:参数个数不对 ''' Traceback (most recent call last): File "func_call.py", line 8, in <module> print(abs(1, 2)) TypeError: abs() takes exactly one argument (2 given) ''' # 错误演示二: # print(abs('hello')) # 报错:错误的参数类型 ''' Traceback (most recent call last): File "func_call.py", line 17, in <module> print(abs('hello')) TypeError: bad operand type for abs(): 'str' ''' # 调用 max() 函数,它可以接收任意多个参数,返回最大的那个 print(max(1, 2, 3)) # 3 print(max(1, 0, -3, 7, 9, 12)) # 12 grades = [100, 0, 9, -10] # 接收一个 Iterable print(max(grades)) # 数据类型转换函数 # 把 str 转换成整数 print(int('123')) # 123 # 把浮点数转换成整数 print(int(12.34)) # 12 # 把 str 转换成浮点数 print(float('12.34')) # 12.34 # 把浮点数转换成 str print(str(12.3)) # 12.3 # 把整数转换成 str print(str(1234)) # 1234 # 把 str 转成布尔 print(bool('')) # False print(bool('a')) # True # ord(c) 函数:Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. print(ord('A')) # 65 # chr(i) 函数:Return the string representing a character whose Unicode code point is the integer i. print(chr(97)) # a # len(s) 函数:Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, # or range) or a collection (such as a dictionary, set, or frozen set). print(len('abc')) # 3 print(len(b'1234')) # 4 print(len((1, 2, 3, 4, 5))) # 5 print(len(['a', 'b', 1, 4, True])) # 5 print(len(range(10))) # 10 # 函数名 a = abs # 变量 a 指向 abs 函数 print(a(-1)) # 1,这里是通过 a 调用 abs 函数
false
c9363241884a797e69d2fad4b01ecff8c2227d5d
jhwsx/liaoxuefeng_python_tutorial_learning
/python_1/tuple.py
736
4.375
4
classmates = ('Michael', 'Bob', 'Tracy') # 获取 tuple 中的元素 print(classmates[0]) print(classmates[1]) print(classmates[2]) # 倒着取 print(classmates[-1]) print(classmates[-2]) print(classmates[-3]) # 获取元素个数 print(len(classmates)) # 3 # 没有追加,插入,删除,替换的方法 # 定义一个空的 tuple t = () print(t) # () # 定义一个一个元素的 tuple # 不正确的写法 t = (1) print(t) # 1, 从打印结果看,这并不是一个 tuple,而是数值 1。 # 正确的写法 t = (1,) # 只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 print(t) # (1,) # "可变"的 tuple t = ('a', 'b', ['A', 'B']) t[2][0] = 'X' t[2][1] = 'Y' print(t) # ('a', 'b', ['X', 'Y'])
false
a40bd55fb6c118a1a920fabb15c32234f7582d2e
AKHILESH1705/programing_questions
/pro4.py
281
4.4375
4
#4. Write a Python program which accepts the radius of a circle from the user and compute the area. from math import pi radius=float(input("enter redies = ")) print("area of circle=",pi*radius**2) print("area of circle with radius " + str(radius) + " is : " + str(pi*radius**2) )
true
92f03947cce2691d40dc217d115c51a94378dbfc
haciz/Mission-Python
/helloworld.py
230
4.15625
4
student_names = ["Jasmina", "Stefan", "Jasna", "Natalija", "Vanja", "Tanja", "Jasna Macka"] for name in student_names: if name == "Vanja": continue print("Found her " + name) print("Currently testing " + name)
false
72a50e330cd00b9cbcf467c7eab6d5c07c1289f1
dhairyachandra/CSEE5590-Python-Deep-Learning-Programming
/ICP3/Source/employee.py
940
4.125
4
# Parent Employee class class Employee: # Count number of employees noOfEmployee = 0 # Store salary of all employees tSalary = 0 # Constructor of parent class def __init__(self): self.name = input('Name: ') self.family = input('Family: ') self.salary = int(input('Salary: ')) self.department = input('Department: ') Employee.noOfEmployee += 1 Employee.tSalary += int(self.salary) # Function to return data of employee def empDetails(self): empDetails = {} empDetails['Employee'] = Employee.noOfEmployee empDetails['Name'] = self.name empDetails['Family'] = self.family empDetails['Salary'] = self.salary empDetails['Department'] = self.department return empDetails # Function for finding Average of salaries def avgSalary (self): avg = Employee.tSalary/Employee.noOfEmployee return avg
true
2d83f942b28eb5f351fa4d29c33f80ee27658937
dhairyachandra/CSEE5590-Python-Deep-Learning-Programming
/ICP2/Source Code/wordcount.py
412
4.34375
4
# Write a python program to find the wordcount in a file for each line and then print the output. # Finally store the output back to the file. file = open("words.txt", 'r') data = file.read() words = data.split() wordcount = [words.count(w) for w in words] # Count the number of word frequency for x in (zip(words, wordcount)): # Zip used to combine two list print(x, file=open("output.txt", "a"))
true
be9fac24ad01a04736ffa42f9aeead553536665e
jixinfeng/leetcode-soln
/python/397_integer_replacement.py
1,033
4.15625
4
""" Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 """ class Solution(object): def integerReplacement(self, n): """ :type n: int :rtype: int """ return self.replace(n, 0) def replace(self, n, step): if n == 1: return step if n % 2 == 0: return self.replace(n // 2, step + 1) else: return min(self.replace(n + 1, step + 1), self.replace(n - 1, step + 1)) a = Solution() print(a.integerReplacement(8) == 3) print(a.integerReplacement(7) == 4)
true
f6f80c7a3715c5bf06227b72dea27fb98150b835
jixinfeng/leetcode-soln
/python/339_nested_list_weight_sum.py
1,931
4.125
4
""" Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Example 1: Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1) Example 2: Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27) """ # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution(object): def depthSum(self, nestedList): """ :type nestedList: List[NestedInteger] :rtype: int """ if len(nestedList)==0: return 0 nestedSum=0 depth=0 while len(nestedList)>0: listElements=[] depth+=1 for element in nestedList: if element.isInteger(): nestedSum+=depth*element.getInteger() else: for nestedElement in element.getList(): listElements.append(nestedElement) nestedList=listElements return nestedSum
true
ea74a86bb0b28a3a53747024ac26ee8dd11d2b60
jixinfeng/leetcode-soln
/python/190_reverse_bits.py
880
4.1875
4
""" Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Follow up: If this function is called many times, how would you optimize it? Related problem: Reverse Integer Credits: Special thanks to @ts for adding this problem and creating all test cases. """ class Solution: def reverseBits(self, n: int) -> int: result = 0 power = 31 while n: n, bit = divmod(n, 2) result += bit * 2 ** power power -= 1 return result a = Solution() for i in range(10): print(i, bin(i)[2:], a.reverseBits(i)) """ class Solution: def reverseBits(self, n: int) -> int: return int(bin(n)[2:].zfill(32)[::-1], base=2) """
true
2cb1d9e382b0394b6809d714ad2206eb9d96097a
jixinfeng/leetcode-soln
/python/071_simplify_path.py
1,061
4.125
4
""" Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". """ class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ soln = [] for folder in path.split('/'): if folder == '.' or folder == '': continue elif folder == '..': if len(soln) > 0: soln.pop() else: soln.append(folder) return '/' + '/'.join(soln) a = Solution() print(a.simplifyPath("/home/") == "/home") print(a.simplifyPath("/a/./b/../../c/") == "/c") print(a.simplifyPath("/../") == "/") print(a.simplifyPath("/home//foo/") == "/home/foo")
true
31e538a63d7d4ddd18d81e7843fa1d55bf9426f7
jixinfeng/leetcode-soln
/python/117_populating_next_right_pointers_in_each_node_ii.py
1,405
4.1875
4
""" Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra space. For example, Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL """ # Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): if root is None: return level = [] nextlevel = [root] root.next = None while True: level = nextlevel nextlevel = [] for node in level: if node.left: nextlevel.append(node.left) if node.right: nextlevel.append(node.right) if len(nextlevel) == 0: break elif len(nextlevel) > 1: for i in range(len(nextlevel) - 1): nextlevel[i].next = nextlevel[i + 1] nextlevel[-1].next = None
true
bd2629518c3889941d1ea266b45325fa37e993aa
jixinfeng/leetcode-soln
/python/007_reverse_integer.py
1,292
4.3125
4
""" Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. Update (2014-11-10): Test cases had been added to test the overflow behavior. """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x == 0: return x if x < 0: neg = True x = -x else: neg = False revx = 0 while x > 0: revx = revx * 10 + x % 10 x //= 10 if len(bin(revx)[2:]) >= 32: return 0 else: return -revx if neg else revx a = Solution() print(a.reverse(0) == 0) print(a.reverse(123) == 321) print(a.reverse(-123) == -321) print(a.reverse(2 ** 32 + 2) == 0)
true
ad79611b072dd345fc1facb381e25cdd562f767c
jixinfeng/leetcode-soln
/python/247_strobogrammatic_numbers_ii.py
1,207
4.25
4
""" Given an integer n, return all the strobogrammatic numbers that are of length n. You may return the answer in any order. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Example 1: Input: n = 2 Output: ["11","69","88","96"] Example 2: Input: n = 1 Output: ["0","1","8"] Constraints: 1 <= n <= 14 """ class Solution: def findStrobogrammatic(self, n: int) -> List[str]: if n == 1: return ["0", "1", "8"] flip_dict = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'} candidates = ['1', '6', '8', '9'] for i in range(1, n // 2): new_candidates = [] for c in candidates: for d in flip_dict.keys(): new_candidates.append(c + d) candidates = new_candidates new_candidates = [] for left in candidates: right = "".join([flip_dict[ch] for ch in reversed(left)]) if n % 2: for mid in ["0", "1", "8"]: new_candidates.append(left + mid + right) else: new_candidates.append(left + right) return new_candidates
true
60492b06e49d2445f1cb863aa65a7464354bc60f
aldebaran561/Python_OOP
/Inheritance.py
1,796
4.1875
4
#!/usr/bin/env python # coding: utf-8 # In[6]: class Human: def __init__(self,name): self.name = name def nombre(self): return self.name def trabajador(self): return False class Mayor(Human): def trabajador(self): return True # In[7]: Persona1 = Human('Victor') Persona2 = Mayor('Felipe') print(Persona1.nombre(), Persona1.trabajador()) print(Persona2.nombre(), Persona2.trabajador()) # In[23]: class Animal(): def __init__(self,patas,cola, ojos): self.patas = patas self.cola = cola self.ojos = ojos def tiene_patas(self): #Inheritance return self.patas def tiene_cola(self): return 'Este animal no tiene cola' class Cat(Animal): def tiene_cola(self): return 'Este animal tiene cola' # In[24]: araña = Animal(8,False,8) print(araña.tiene_cola()) print(araña.tiene_patas()) gato = Cat(4,True,2) print(gato.tiene_cola()) print(gato.tiene_patas()) # In[ ]: class Father: def __init__(self, name): self.father_name = name class Mother: def __init__(self, name): self.mother_name = name class Son(Father, Mother): def __init__(self, name, father_name, mother_name): self.name = name Father.__init__(self, father_name) Mother.__init__(self, mother_name) def sexo(self, sexo): self.sexo = sexo def presentacion(self): if self.sexo == "M": return '{} es hijo de {} y {}'.format(son.name, son.father_name, son.mother_name) else: return '{} es hija de {} y {}'.format(son.name, son.father_name, son.mother_name) son = Son('Amalia', 'Víctor', 'Estefa') son.sexo('F') print(son.presentacion())
false
1930a450c27257cc8e4ea542f9352798978f5af4
MattheusOliveiraBatista/Python3_Mundo02_CursoEmVideo
/AulasPython/Aula013_Estrutura_De_Repetição_For_02.py
456
4.40625
4
''''''''' Nessa aula, vamos começar nossos estudos com os laços e vamos fazer primeiro o “for”, que é uma estrutura versátil e simples de entender. Por exemplo: for c in range(0, 4): print(c) print(‘Acabou’) ''' #For incrementa i++ for c in range(0,6,1): print('{} = Oi'.format(c)) print('Fim! :)') #For decrementa i-- print('\n\n') for c in range(6,0,-1): print('{} = Oi'.format(c)) print('Fim! :)')
false
c635f340f8258de1f25058c88e5d8d3989fa3b14
MattheusOliveiraBatista/Python3_Mundo02_CursoEmVideo
/AulasPython/Aula015_Interrompendo_Repetições_While.py
918
4.25
4
''' Nessa aula, vamos aprender como utilizar a instrução break e os loopings infinitos a favor das nossas estratégias de código. É muito importante saber usar o break no Python, já que em alguns casos precisamos interromper um laço no meio do caminho. Além disso, vamos aprender como trabalhar com as novas fstrings do Python. #EXEMPLO DO COMANDO Break while True: if terra: passo if vazio: pula if moeda: pega if trofeu: pula break pega ''' ''' cont = 1 #while cont <= 10: while True: print(cont, ' -> ', end='') cont += 1 print('Acabou') ''' num = s = 0 while True: num = int(input('Digite um número: ')) if num== 999: break s += num print(f'A soma vale {s}') #PYTHON 3.6+ #print('A soma vale {}'.format(s)) #PYTHON 3 #print('A soma vale %d',%(s)) #PYTHON 2
false
091c8f71baed630e640cf90251c2e78bcf37cb40
MattheusOliveiraBatista/Python3_Mundo02_CursoEmVideo
/ExerciciosPython/Ex063_Sequência_De_Fibonacci.py
622
4.1875
4
''' Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Exemplo: 0 – 1 – 1 – 2 – 3 – 5 – 8 ''' print(25* '\033[1;34m=\033[m') print('\033[1;40mSequência de Fibonacci\033[m') print(25* '\033[1;34m=\033[m') n = int(input('Quantos termos você quer mostrar? ')) a = 0 b = 1 cont = 2 print('{} \033[1;34m->\033[m '.format(a), end='') while cont <= n: fibo = a + b print('{} \033[1;34m-> \033[m'.format(fibo),end = '') b = a a = fibo n -= 1 print('Fim da Sequência de Fibonacci')
false
f07c3ec62a902781dc9ac4504ad29c57d0a58ee2
0001SID/Python
/practice/while loop.py
294
4.125
4
i = 0 numbers = [] def while_loop(): i = 0 while i<8: print('The value of i is{}'.format(i)) h = numbers.append(i) i += 1 return h,i h,i = while_loop() print('At last the value of i is {}'.format(i)) print(f'The list of numbers of i is {numbers}')
true
f7854c8388f032138ed4a23cc49120d5b973c902
bhavya4official/Python
/string_index.py
235
4.125
4
course = 'Python course' print(course) print(course[:]) # by default start from index 0 print(course[2:]) print(course[-2:]) print(course[:6]) print(course[:-2]) print(course[1:-1]) # start from index 1 to 1st character from the end
true
14a313c753b6abfb07e9aee782ffa67c188db40f
HeedishMunsaram/ASSIGNMENT
/QUESTION3.py
319
4.21875
4
x = input("Enter number: ") def reversenumber(x): reverse = 0 while True: y = str(x) if y == y[::-1]: break else: z = int(y[::-1]) x = z+1 reverse = reverse + 1 return x print("The reverse of number is: ", reversenumber(x))
true
202d05974da435ab90c86f7c4f87923295f46469
rahulsomani26/python-istanbul
/day5/dictionaries/what-is.py
2,403
4.65625
5
# ''' # Dictionary is a data structure # It is a sequence of key:value pair # Syntax 1 {} --> Empty dict # 2. dict() # Properties of a dictionary # The key should not change # ''' # empty_dict = {} # print(type(empty_dict)) # print(len(empty_dict)) # one_element = {'name':'rahul somani'} # print(one_element) # print(len(one_element)) # multiple_element = {'name':'rahul somani','age':40,'address':'Patna, India',30:'Ali'} # # accessing elements in a dict # # accessing elements in a dict # # # accessing elements in a dict # # print(multiple_element['name']) # # print(multiple_element['age']) # # print(multiple_element['address']) # # print(multiple_element[30]) # print(multiple_element) # print(multiple_element.get('age')) # accept a key and return the corresponding value # # Finding keys in a dict # print(multiple_element.keys()) # # Adding / Updating --- using subscript notation[] / update() # multiple_element['name'] = 'Ali Mohemmad' # multiple_element.update({'address':'Mumbai'}) # print(multiple_element) # # getting values in a dict # # using values() # print(multiple_element.values()) # # Getting Items ---- items() method # print(multiple_element.items()) # if "age" in multiple_element: # print('The key is present') # else: # print('The key is not present') ''' Deleting items 1. pop() ---> takes a key as an argument i.e input 2. popitem() --> removes the last inserted item ''' # phoneNumbers = {'rahul':'8210638822', 'Ujjwal':'9867445626','shweta':'8969150666'} # poppedValue = phoneNumbers.pop('shweta') # print(poppedValue) # print(phoneNumbers) # lastValue = phoneNumbers.popitem() # print(lastValue) # print(phoneNumbers) # phoneNumbers = {'rahul':'8210638822', 'Ujjwal':'9867445626','shweta':'8969150666'} # del phoneNumbers['rahul'] # del phoneNumbers # print(phoneNumbers) phoneNumbers = {'rahul':'8210638822', 'Ujjwal':'9867445626','shweta':'8969150666'} # phoneNumbers.clear() # print(phoneNumbers) # Looping through the dictionary for i in phoneNumbers: # we will get the keys print(i) for i in phoneNumbers: # we get the value of the key print(phoneNumbers[i]) for k,v in phoneNumbers.items(): print(f'The key is {k} and the corresponding value is {v} ')
true
578d7145b305fb40699e0980588f35196b9473b3
rahulsomani26/python-istanbul
/solv.py
557
4.25
4
''' Sum and Multiplication of numbers in a list sum = 0 mult = 1 ''' # dummy = [2,2,1,1,3] # sum the numbers # sum =1 # for val in dummy: # sum = sum * val # print(f' The value in this iteration is {sum}') # print(f' The final sum = {sum}') ''' Min and max numbers in a list ''' dummy = [2,4,1,0,3,-7,-1] max = 1 for item in dummy: if item < max : max = item print(f' The maximum value in this iteration is {max}') print(f' The max value in the list is {max}')
true
c2e75a22a72ac812fb4aa739f527f81c12d33d56
rahulsomani26/python-istanbul
/example1.py
2,248
4.125
4
# msg = 'Ali Turkey' # temp = msg # print(temp) # print(id(msg)) # print(id(temp)) # # msg[0]='B' # # print(msg) ''' We cannot change a string once created Strings are immutable in nature ( we cannot change a string once created ) ''' ''' Some string methods () ''' # msg = ' Hello world ! ' # print(msg.upper()) # It will change all char in upper case # print(msg.title()) # It will change all char in upper case # # print(msg.lower()) # It will change all char in upper case # print('RAHUL'.lower()) # print('rahul somani'.capitalize()) # print('rAhUL SOmaNi'.swapcase()) ''' Sequence operation len() max(), min() s in b ''' # msg = 'Hello I am there for you ' # result = 'fr' in msg # print(result) # test_string = 'Aabc' # ASCII values A 65 B 66 a 65+32 = 97 # print(min(test_string)) # print(max(test_string)) ''' What are literals ( variables / constants ) ''' # m = 'x' # print('li' + 'mi'+ m ) ''' Some more string methods strip() split() replace() rsplit() # can u write a program that mimics rsplit and lsplit lsplit() ..... ''' # strip_test = '.....Ali Mohammad.....?' # print(strip_test.strip('?.')) # order is not important # your_name = 'Ali+Mohammad' # splitted_val = your_name.split() # print(splitted_val) # print(your_name.split('+')) ''' find() ''' # my_name = 'My name is rahul somani and I stay in India' # result = my_name.find('stay',14) # if result == -1: # print(' not found') # else: # print('found') # test_string = 'Apple is my fav fruit' # print(test_string.replace('Apple','Orange')) print('#'.join('rahul')) ''' couple of more methods ''' msg_1 = '123' msg_2 = 'Rahul123' msg_3 = 'somani.classes@outlook.com' print(msg_2.isalnum()) print(msg_3.isalnum()) print(msg_1.isalnum()) print('-'*20) print(msg_1.isalpha()) # False print(msg_2.isalpha()) # True print(msg_3.isalpha()) # False print('--'*20) print(msg_2.startswith('a')) print(msg_2.startswith('Ra')) print(msg_2.startswith('Rah')) print(msg_2.startswith('u')) print('-'*20) print(msg_3.endswith('om'))
true
3b2e6d22a6d7758404350e9c07069be3ee21a4ed
viks8dm/basic_algorithms_python
/problem_6_max_min_in_unsorted_array.py
2,351
4.15625
4
""" find smallest and largest integer from a given unsorted array The code should run in O(n) time. Do not use Python's inbuilt functions to find min and max. """ # ############# # def get_min_max_recursive(arr, l, r): # if (l==r): # return (arr[l], arr[l]) # if l + 1 == r: # if arr[l] <= arr[r]: # return (arr[l], arr[r]) # return (arr[r], arr[l]) # mid = (l + r) // 2 # (l_min, l_max) = get_min_max_recursive(arr, l, mid) # (r_min, r_max) = get_min_max_recursive(arr, mid+1, r) # n_min = l_min if (l_min<=r_min) else r_min # n_max = l_max if (l_max>=r_max) else r_max # return (n_min, n_max) # ############# # def get_min_max(ints): # """ # Return a tuple(min, max) out of list of unsorted integers. # Args: # ints(list): list of integers containing one or more integers # """ # # corner cases # if len(ints) == 0: # return (None, None) # return get_min_max_recursive(ints, 0, len(ints)-1) ############# def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return (None, None) min_val, max_val = ints[0], ints[0] for i in ints: if (i<min_val): min_val = i elif (i>max_val): max_val = i return (min_val, max_val) ############# if __name__=="__main__": import random # test -1: print('------ test 1') l = [i for i in range(0, 10)] # a list containing 0 - 9 random.shuffle(l) print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail") # test -2: print('------ test 2') print ("Pass" if ((None, None) == get_min_max([])) else "Fail") # test -3: print('------ test 3') print ("Pass" if ((8, 8) == get_min_max([8])) else "Fail") # test - 4 to 99: random cases for i in range(100-4): m = random.randint(1, 20) n = random.sample(range(-1000, 1000), m) print('------ test ' + str(i+4)) print("array: " + str(n)) print("min, max = " + str(get_min_max(n))) result = "PASS" if ((min(n), max(n)) == get_min_max(n)) else "FAIL" print(result) if result == "FAIL": break
true
50277cd015fdfbc40626a9679ece36bff6baaeec
vermadev54/Python-oops
/class-decorator-6.py
1,143
4.375
4
""" # Checking error parameter using class decorator : This type of class decorator is most frequently used. This decorator checks parameters before executing the function preventing the function to become overloaded and enables it to store only logical and necessary statements. """ # Python program checking # error parameter using # class decorator class ErrorCheck: def __init__(self, function): self.function = function def __call__(self, *params): if any([isinstance(i, str) for i in params]): raise TypeError("parameter cannot be a string !!") else: return self.function(*params) @ErrorCheck def add_numbers(*numbers): return sum(numbers) if __name__ == '__main__': # returns 6 print(add_numbers(1, 2, 3)) # raises Error. print(add_numbers(1, '2', 3)) """ 6 Traceback (most recent call last): File "class-decorator-6.py", line 33, in <module> print(add_numbers(1, '2', 3)) File "class-decorator-6.py", line 18, in __call__ raise TypeError("parameter cannot be a string !!") TypeError: parameter cannot be a string !! """
true
fd54314ae6256926931fc15829c50c92b9f4d998
asaish019/python
/leapyearelif.py
246
4.1875
4
year=int(input(" input year to check is it is a Leap-year: ")) if (year%100==0)and(year%400==0): print("This year is a leap year") elif (year%4==0): print(" it is leap year") else: print("it is not a leap year")
false
a2d51e46391ccc192b373375d496b9c9f09f2027
qpakzk/problem-solving
/Codewars/bits-battle.py
1,751
4.25
4
""" The odd and even numbers are fighting against each other! You are given a list of positive integers. The odd numbers from the list will fight using their 1 bits from their binary representation, while the even numbers will fight using their 0 bits. If present in the list, number 0 will be neutral, hence not fight for either side. You should return: odds win if number of 1s from odd numbers is larger than 0s from even numbers evens win if number of 1s from odd numbers is smaller than 0s from even numbers tie if equal, including if list is empty Please note that any prefix that might appear in the binary representation, e.g. 0b, should not be counted towards the battle. Example: For an input list of [5, 3, 14]: odds: 5 and 3 => 101 and 11 => four 1s evens: 14 => 1110 => one 0 Result: odds win the battle with 4-1 """ def bits_battle(numbers): odd = 0 even = 0 for n in numbers: if n % 2 == 0: flag = True else: flag = False binary = str(bin(n))[2:] if flag == True: for i in range(0, len(binary)): if binary[i] == '0': even += 1 else: for i in range(0, len(binary)): if binary[i] == '1': odd += 1 if odd > even: return "odds win" elif odd == even: return "tie" else: return "evens win" from unittest import TestCase class TestBitsBattle(TestCase): def test_bits_battle(test): test.assertEqual(bits_battle([5, 3, 14]), 'odds win') test.assertEqual(bits_battle([3, 8, 22, 15, 78]), 'evens win') test.assertEqual(bits_battle([]), 'tie') test.assertEqual(bits_battle([1, 13, 16]), 'tie')
true
837110d9bb9bfda745d70d43bbdcbf1f16b07b30
jaggersystems/py_learn
/ifs.py
319
4.28125
4
is_male = False is_tall = False #if is_male or is_tall: if is_male and is_tall: print("You are a male and tall") elif is_male and not (is_tall): print("You are male and not tall") elif not(is_male) and is_tall: print("You are not a male but are tall") else: print("You are not a male and not tall")
false
05aaba66c85ec969684b9f10e1814ee170b6ae99
Ushakek/2017
/code/course2/functions/practice.py
1,856
4.15625
4
# 1. Написать функцию, которая выбрасывает одно из трех исключений: ValueError, TypeError или RuntimeError случайным образом. В месте вызова функции обрабатывать все три исключения import random def raise_random_error(): ex = random.choice([ValueError, TypeError, RuntimeError]) raise ex('Message for a user') try: raise_random_error() except ValueError as e: print('Value', e) except TypeError as e: print('Type', e) except RuntimeError as e: print('Runtime', e) # 2. Написать функцию, которая принимает на вход список, если в списке все объекты - int, сортирует его. Иначе выбрасывает ValueError def sort_numbers(numbers): for num in numbers: if not isinstance(num, int): raise ValueError('{} is not a number'.format(num)) numbers.sort() # Or: # if any(not isinstance(num, int) for num in int): try: values = [1, 'a', 3] sort_numbers(values) print(values) except ValueError as e: print(e) # 3. Написать функцию, которая принимает словарь, преобразует все ключи словаря к строкам и возвращает новый словарь def keys_to_str(data): result = {} for key, value in data.items(): result[str(key)] = value return result print(keys_to_str({1: 'one', None: True})) # 4. Написать функцию, которая принимает список чисел и возвращает их произведение def multiply_all(numbers): res = 1 for num in numbers: res *= num return res print(multiply_all([3, 4, 2]))
false
8e28b064c4d37cab9fe8c6df2bca346d5523e494
MaratAG/GB_mains_of_python
/lesson_1_6.py
1,234
4.40625
4
""" 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил а километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составит не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число - номер дня. """ start = float(input('Введите результат спортсмена в первый день (км): ')) finish = float(input('Введите ожидаемый результат спортсмена (км): ')) percent = 1.1 # приращение в увеличении результата day = 1 result = start while True: if result >= finish: break result *= 1.1 day += 1 print('На {} день спортсмен достиг результата - не менее {} км'.format(day, finish))
false
f6abf39df29d0adbce4588c0a06934598a6d71db
MaratAG/GB_mains_of_python
/lesson_3_6.py
1,326
4.21875
4
""" 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). """ def int_func(words_in_low): """Вернуть слово с прописной первой функцией.""" capitalize_words = [word.capitalize() for word in words_in_low.split()] result = ' '.join(capitalize_words) return result string_of_words = input('Введите строку из слов, разделенных пробелом: ') result_string = int_func(string_of_words) print('Обработанная строка: {}'.format(result_string))
false
38662a6c62a2c03100cdf9ca2372509aad7e6164
MaratAG/GB_mains_of_python
/lesson_5_3.py
1,211
4.1875
4
""" 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. """ min_wage = 20000 wage_fund = 0 count_employees = 0 file_name = 'wage_file.txt' try: with open(file_name, 'r') as wage_file: strings = wage_file.readlines() except FileNotFoundError: print(f'Файл {file_name} не найден!') else: for line in strings: wage_data = line.split() if len(wage_data) == 2: employees = wage_data[0] wage = float(wage_data[1]) wage_fund += wage count_employees += 1 if wage < min_wage: print(f'Сотрудник {employees} - {wage:.2f} USD') if count_employees: print(f'Cредняя величина дохода сотрудников - {wage_fund / count_employees:.2f} USD')
false
f3594a77d75b4294e495a45875a28d2794d46c28
Akhand6886/Python-Lab-Experiment
/Lab 2&3/a list of scores for N students in a list data type.py
662
4.15625
4
# Q2. WAP to input a list of scores for N students in a list data type. Find the score of the runner-up and print the output. # Sample Input # N = 5 # Scores= 2 3 6 6 5 # Sample output # 5 NumList = [] Number = int(input("How many students you want to enter: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d student : " %i)) NumList.append(value) first = second = NumList[0] for j in range(1, Number): if(NumList[j] > first): second = first first = NumList[j] elif(NumList[j] > second and NumList[j] < first): second = NumList[j] print("The Runner_up score is : ", second)
true
ad91ea9d8eae9c7305dfbe1671a41b9a3164289a
Akhand6886/Python-Lab-Experiment
/Lab 1/Conditional actions.py
517
4.3125
4
#Q1. Given an integer n perform the following conditional actions: #• If n is odd, print Weird #• If n is even and in the inclusive range of 2 to 5 , print Not Weird #• If n is even and in the inclusive range of 6 to 20, print Weird #• If n is even and greater than 20, print Not Weird n = int(input("Enter the number")) if (n%2 == 0): if(n>=2 and n<=5): print("Not Weird") if (n>=6 and n<=20): print("Weird") if (n>20): print("Not Weird") else: print("Weird")
false
a8a527b7cee49701ff75990097410a3186111554
rinabaral/python
/dictionary exercises.py
2,180
4.40625
4
"""Question 1: Below are the two lists convert it into the dictionary""" keys = ['Hello', 'How', 'you'] values = ['Sana', 'are', '?'] dictionary=dict(zip(keys, values)) print(dictionary) """Question 2: Merge following two Python dictionaries into one""" dict1 = {'Hi': 12, 'Are': 20, 'You': 30} dict2 = {'Hey': 34, 'You': 40, 'Fine': 50} dict3 =dict1.copy() dict3.update(dict2) print(dict3) """Question 3: Access the value of key ‘history’""" sampleDict = { "class":{"student":{"name":"Mike","marks":{"physics":70,"history":80}}}} print(sampleDict['class']['student']['marks']['history']) """Question 4: Initialize dictionary with default values""" employees = ['Jova', 'Elson', 'John'] defaults = {'Application Developer', 6000} print(dict.fromkeys(employees, defaults)) """Question 5: Create a new dictionary by extracting following keys name and salary from a given dictionary""" sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york" } new = {key: sampleDict[key] for key in sampleDict.keys()& {'name', 'salary'}} print("The new dictionary is :", str(new)) """6: Delete set of keys from Python Dictionary""" #lets use the dictionary of question 5 toremove = {key: sampleDict[key] for key in sampleDict.keys()- {'name', 'salary'}} print("The new dictionary with keys removed :", str(toremove)) """Question 7: Check if a value 200 exists in a dictionary""" Dict = {'a': 100, 'b': 200, 'c': 300} print(200 in Dict.values()) """Question 8: Rename key city to location in the following dictionary""" Dict1 = { "name": "John", "age":25, "salary": 8000, "city": "New york" } Dict1['location'] = Dict1.pop('city') print(Dict1) """Question 9: Get the key corresponding to the minimum value from the following dictionary""" Subject = { 'Physics': 82, 'Math': 65, 'history': 75 } print(min(Subject, key=Subject.get)) """Question 10: Given a Python dictionary, Change Brad’s salary to 8500""" Employees = { 'emp1': {'name': 'Jhon', 'salary': 7500}, 'emp2': {'name': 'Emma', 'salary': 8000}, 'emp3': {'name': 'Brad', 'salary': 6500} } Employees['emp3']['salary']= 8500 print(Employees)
true
4ef38ad9517b85d4569cb15610039e21522e5a28
rinabaral/python
/Loop exercises.py
1,188
4.1875
4
"""1: Print the following pattern 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 """ for i in range(1,6): #for row in range for j in range(1,i+1): #for column in range of (1,row+1) print(j, end = " ") print() """2: Accept n number from user and calculate the sum of all number between 1 and n including n. """ n= int(input("Enter a range:")) sum= 0 for i in range(1,n+1,1): sum = sum + i print(sum) """Question 3: Given a list iterate it and display numbers which are divisible by 5 and if you find number greater than 120 stop the loop iteration""" list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200] for i in list1: if(i > 120): break; if i%5==0: print(i) """Question 4: Display a message “Done” after successful execution of for loop""" n=int(input("Enter the number of range:")) for i in range(n): print(i) else: print("Done!") """Question 5: Print the following pattern using for loop 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 """ x=5 y=5 for i in range(0,x+1): for j in range(y-i,0,-1): print(j,end =' ') print() """Question 6: Display -10 to -1 using for loop""" for i in range(-10,0): print(i)
true
4192b4b153244e7e47bd5f34da87456070fea2b5
liangb-dev/Learn-Python
/battleship.py
2,527
4.5
4
from random import randint """ Codecademy/Learn Python 7 Lists and Functions ============================================= Battleship! ============================================= Extra Credit: X 1. Make multiple battleships. 2. Make battleships of different sizes. 3. Make your game a two-player game. 4. Use functions to allow your game to have more functions like rematches, statitstics and more. """ def print_board(board_in): """prints the board""" for row in board_in: print " ".join(row) def random_row(board_in): """gets a random row within range of board""" return randint(0, len(board_in)-1) def random_col(board_in): """gets a random column within range of board""" return randint(0, len(board_in[0])-1) def main(): board = [] for i in range(0,5): board.append(["O"]*5) difficulty = { "easy" : 30 / 100.0, "medium" : 60 / 100.0, "hard" : 90 / 100.0 } user_difficulty = raw_input("Choose difficulty level(easy, medium, hard): ").lower() num_ships = 3 battleships = [] while len(battleships) != num_ships: ship_row = random_row(board) ship_col = random_col(board) add = ship_row*10 + ship_col if not add in battleships: battleships.append(add) board[ship_row][ship_col] = "G" print_board(board) turns_range = int(num_ships/difficulty[user_difficulty]) for turn in range(turns_range): print "turn %d out of %d"%(turn+1, turns_range) guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Coloumn: ")) add = guess_row*10 + guess_col if add in battleships: print "Congratulations! You sank a battleship!" battleships.remove(add) if len(battleships) == 0: print "Victory! You sank all my battleships!" break else: if guess_row not in range(len(board)) or guess_col not in range(len(board[0])): print "Oops, that's not even in the ocean." elif board[guess_row][guess_col] == "X": print "You guesses that one already." else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print_board(board) if turn+1 == turns_range: print "Game Over" if __name__=="__main__": main()
true
78c77d663b37b54e6ebc6e5529fe02c5804b66d6
kgoebber/met330_examples
/read_commandline.py
705
4.28125
4
# This python script is designed to illustrate how to read in a parameter from the command line # # By: Kevin Goebbert # To input from the command line, use the raw_input() command # The prompt for the input goes inside of the raw_input command and is bounded by quote marks. firstname = input('Type your first name: ') # Same as the above command, but with a newline (\n) character to make it look nicer on the screen. lastname = input('Type your last name \n') # The print command works similar to that of Fortran, except no need for the *, # Here you are essentially creating a string and so the command looks a little different than the Fortran print command print('Your name is '+firstname+' '+lastname)
true
0761ddc586829af9ff460490a07c9f6ef7af13fe
tqi-data/Leetcode_Practice
/Stack/ValidParentheses.py
957
4.25
4
# Python program to determine if parentheses in a string match # The string only contains parentheses characters class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ # use stack to store the left only stack = [] dic = {'{':'}', '[':']', '(':')'} for c in s: # if it is left in the string, put it in the stack if c in dic: stack.append(c) # if it is right in the string else: # if the stack is empty or (not-empty-stack and c does not match the key for value of last element in the stack) if not stack or(stack and dic[stack.pop()] != c): return False return not stack s = '()[{}]' a = Solution() Ans = a.isValid(s) if Ans: print "Parentheses match" else: print "Parentheses do not match"
true
5362cdaf0695163900b973cd0c8fdaca6a6123ed
willianvm/poo_python
/ejercicioclase_basico.py
795
4.28125
4
"""Cree una clase perro con los atributos raza, edad, color, nombre, que pueda ladrar, correr, dormir, comer, saltar. luego instanciela y imprima lo siguiente: La raza del perro, y su comportamiento en determinado momento""" class Perro: def __init__(self, raza, edad, color, nombre, velocidad): self.raza = raza self.edad = edad self.color = color self.nombre = nombre self.velocidad = velocidad def ladrar(self): print("el perro esta ladrando") def correr(self): print(f"Está corriendo a una velocidad de {self.velocidad} m/s y luego"), self.ladrar() def dormir(self): print("el perro esta dormido") perro1 = Perro("pincher",3, "negro", "roky", 3) print(f"El perro es {perro1.raza} y"), perro1.correr()
false
7180a85027d23ce09d394ec07c6f0ed6553f3b36
rutup1595/Machine-learning
/HW2/mapFeature.py
808
4.125
4
import numpy as np def mapFeature(x1, x2): ''' Maps the two input features to quadratic features. Returns a new feature array with d features, comprising of X1, X2, X1 ** 2, X2 ** 2, X1*X2, X1*X2 ** 2, ... up to the 6th power polynomial Arguments: X1 is an n-by-1 column matrix X2 is an n-by-1 column matrix Returns: an n-by-d matrix, where each row represents the new features of the corresponding instance ''' ##### m=0; degree=6 n=x1.shape[0] final_out=np.ones((n,27)) for i in range(1, degree + 1): for j in range(0,i + 1): final_out[:,m] = np.power(x1,(i - j)) *np.power(x2,j) m=m+1 return np.matrix(final_out)
true
53c152c4be759a9818beff974daa0594b1fc4a92
SunilVarmaCS/IBM-Python-For-Data-Science
/COGNATIVE_2_.py
1,753
4.375
4
#Conditions and Branching #Loops #Functions #Objects and Classes a = 6 print(a==6) print(6==6) print(7==7) #Another Example i = 6 print(i > 5) print(i >= 5) #i = 2 print(i < 2) print(i <= 2) #Inequality Test uses a Explanation Mark i!=6 print(i!=6) #Equality Test (==) and Inequality Test (!=) print("Same" == "Creativity") print("Same" != "Creativity") #Branchings #Branching allows us to run different statements for different input. #The "if" Statement age = 19 if (age > 18): print("You can Enter the concert") print("You can Move on") #The "else" Statement age = 17 if (age > 18): print("You can Enter the Concert") else: print("Meet to the Staff Members") print("Then You can Go the Concert") #The Elif Statement age = 20 if(age > 18): print("You can Enter") elif(age == 18): print("Go to the Pink Floyd") else: print("Go to Staff Office") print("Then you can move on") #Logic Operators #Logic Operations take boolean values and produce different boolean values #Not Operator print(not(True)) print(not(False)) #or Operator A = False B = False print(A or B) A = False B = True print(A or B) A = True B = False print(A or B) A = True B = True print(A or B) album_year = 1990 if (album_year < 1980) or (album_year > 1989): print("The Album was made in the 70's or 90's") else: print("The album was made in the 1980's") #And Operations A = False B = False print(A and B) print(A & B) album_year = 1983 if (album_year > 1979) and (album_year < 1990): print("This album was made in the 80's") #Branching allows to different statements to different inputs #Loops #For Loops and While Loops #range() Function i = [10,20,(30)] name = 20 print(type(name))
true
7b21a2d6c57e6c7d66147dde00f4a74d0764e8da
koquimotto/CursePython
/fibonacci.py
991
4.125
4
# -----------Fibonacci basic level----------------------- # def Fibonacci(n): # if n<0: # print('Incorrect input') # elif n==1: # return 0 # elif n==2: # return 1 # else: # return Fibonacci(n-1) + Fibonacci(n-2) # print(Fibonacci(10)) # ----------------------------------------------- # -----------Fibonacci nivel intermedio---------- # FibArray = [0,1] # def fibonnacci(n): # if n<0: # print ('Incorrect input') # elif n<=len(FibArray): # return FibArray[n-1] # else: # temp_fib = fibonnacci(n-1) + fibonnacci(n-2) # FibArray.append(temp_fib) # return temp_fib # print(fibonnacci(120)) # --------------------------------------------------- # -----------------------Fibonacci hard level-------- def Fibonacci(n): a,b = 0,1 for _ in range(n): yield a a, b = b, a + b n=100000 print(list(Fibonacci(n)) [n-1]) # ---------------------------------------------------
false
c7387be5314bc86a80ed4360d2ac0b3a202355bd
UWSEDS/homework-2-python-functions-and-modules-Mewoy666
/Homework2_JingXu.py
912
4.125
4
# Homework 2 Jing Xu # T1. Write a python reads creates a dataframe from a URL that points to a CSV file import pandas as pd def read_and_create(data_url): data = pd.read_csv(data_url) return data # T2. Create the function test_create_dataframe that takes as input: # (a) a pandas DataFrame and (b) a list of column names. The function returns True if the following conditions hold # The DataFrame contains only the columns that you specified as the second argument. # The values in each column have the same python type # There are at least 10 rows in the DataFrame. def test_create_dataframe(dataframe, columns_names): if dataframe.shape[0] < 10: return False if list(dataframe.columns) != columns_names: return False for i in columns_names: for j in dataframe[i]: if type(j) != type(dataframe[i][0]): return False return True
true
a8dd37214f124d674619e716cd4b5d0a27b8c108
michaelamartin/LPTHW
/ex6.py
789
4.15625
4
#Defining variables x and y x = "There are %d types of people." %10 #Defining the binary and do_not variables binary = "binary" do_not = "don't" #Defining the y variable with binary and do_not as string inputs y = "Those who know %s and those who %s." % (binary, do_not) #Printing variables x and y print x print y #Printing strings referencing formatted variables x and y print "I said: %r." % x print "I also said: '%s'." % y #Defining the hilarious and joke_evaluation varibles hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" #Printing joke_evaluation with formated variable hilarious print joke_evaluation % hilarious #Defining w and e variables w = "This is the left side of..." e = "a string with a right side." #Concatenating strings w and e print w + e
true
45b9e7171392a07822653e094936d26dd591882d
LukeMowry/Projects
/Project18-DecimalBinaryConverter.py
334
4.25
4
""" Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. """ number = input("Enter your integer or binary number? >> ") if "0b" in number: print(int(number, 2)) else: transformed = int(number) print(bin(transformed))
true
e4ea2cf0192521b878e2fd9c5188913593b14fe4
learnwithbilal/python
/hello.py
507
4.125
4
# num = int(input("Enter Number: ")) # if num > 0: # print("The Number is Positive") # elif num < 0: # print("The Number is Negative") # else: # print("Number is Zero") # name = input("Enter Your Name: ") # print("Hello {} , How Are You Today ?!".format(name)) friends = ["Mahmoud", "Eyhab", "Ali", "Osama", "Shams", "Humam", "Kaser", "Ritta", "Riham"] # friends.sort() # friends.append("Bilal") # friends.sort() # print(friends) # friends = {"key01": "Bilal", "Key02": "Nour"}
false
7ea358e48e3b32439c04309c7ad4534a3a863f7b
SpacedKage/Import-dataframe
/importtask.py
478
4.1875
4
import pandas as pd frame = pd.DataFrame([[8.96, 1884], [7.87, 1149], [7.13, 428]], index = ["Copper", "Iron", "Zinc"], columns = ["Density g/cm3", "Melting Point BC"]) print(frame) print() print(frame.loc["Copper"]) # if we were to create a dataframe using the previous method then metals = {"Metal": ["Copper", "Iron", "Zinc"], "Density g/cm3": [8.96, 7.87, 7.13], "Melting Point BC": [1884, 1149, 428]} frame2 = pd.DataFrame(metals) print (frame2)
true
56280d432e54da9acdd4ed2326a0b1860944d973
Aubrey-Tsorayi/Calculator
/calc.py
2,759
4.25
4
from math import * run = True option = input("Do you want a simple calculator (Y/n): ") while run == True: if option.lower() == "y": try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) op = input("Enter an operator: ") if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "/": try: print(num1 / num2) except ZeroDivisionError: print("You cant divide by zero") elif op == "*": print(num1 * num2) else: print("operator not registered, Try again") except ValueError: print("Enter a valid number") elif option.lower() == "n": print("Please select an option") print( """ pi: to get the value of pi pow: calculate power sq: to get the sqaure root si: sin of an angle co: cos of an angle ta: tan of an angle quit: quits calculator """ ) command = input(">>: ") if command == "pi": print("The value of pi is " + str(pi)) elif command == "pow": try: base = eval(input("Enter base number: ")) power = eval(input("Enter power number ")) print(pow(base, power)) except NameError as err: print("Enter an valid number") elif command == "sq": try: sqa = eval(input("Enter number to be squared: ")) print(sqrt(sqa)) except NameError as err: print("Enter an valid number") elif command == "si": try: si = eval(input("Enter an angle: ")) print(round(sin(si))) except NameError as err: print("Enter an valid number") elif command == "co": try: si = eval(input("Enter an angle: ")) print(round(cos(si))) except NameError as err: print("Enter an valid number") elif command == "ta": try: si = eval(input("Enter an angle: ")) print(round(tan(si))) except NameError as err: print("Enter an valid number") elif command == "quit": print("THANK YOU") break else: print("Invalid option, please select a valid option")
true
1b19a85dfb4374da38899c5bbc39d8ad78aed878
Nilesh-5282/Nilesh
/shopping.py
827
4.1875
4
#code refactoring def show_help(): #print the instructions print("What should we pick?:") #have a SHOW command #Have a HELP command print('''Enter'Done' to stop adding the items. Enter 'Help' for any help. Enter 'Show' to show the item''') def show_items(): print("Here's your List") for items in shopping_list: #print the objects print(items) #make a list to hold the items shopping_list=[] show_help() while True: #ask for new items new_items= input("> ") #To quit the app if new_items== "Done": break elif new_items=="Help": show_help() continue #add the items to the list elif new_items=="Show": show_items() else: shopping_list.append(new_items) show_items()
true
b51917641ecd8817e971e475a3509ec8bc540111
Skrekliam/rubbish-bucket
/BMI.py
825
4.25
4
print ("BMI вважається оптимальним показником для оцінки розмірів тіла (ваги та зросту)," "\nякі дозволяють оцінити ризики для здоров’я." "\nПоказники ІМТ в межах норми свідчать про низький ризк" "\nсерцево-судинних захворювань та діабету." ) mass = float(input("\nВедіть вашу вагу в кг. : ")) height = float (input("\nВведіть ваш зріст в M. : ")) BMI = mass / height **2 if BMI <= 18.5: print("Недостатня маса тіла") elif BMI >= 18.5 and BMI < 25: print("Нормальна маса тіла") else: print("\nНадлишкова вага") input()
false
b259eed4be76150cdb7bb39c7bded66aa6b78bfd
nipunsharma30/python-leetcode
/02 fibonacci.py
335
4.3125
4
def fibonacci(n): list = [] for i in range(n): if i <= 1: list.append(i) else: x = (list[i - 1] + list[i - 2]) list.append(x) return list num_of_elements = int(input('Enter the number of elements: ')) fibonacci_series = fibonacci(num_of_elements) print(fibonacci_series)
true
fdbb50e0506964430ae16b9c21b09cc6c7b13ee6
wirelessjeano/py4kids
/lesson-07-std-libs/sample-07.py
2,623
4.3125
4
# https://docs.python.org/3/tutorial/stdlib.html # Brief Tour of the Standard Library # Which Version of Python Am I Using? import sys print(sys.version) ## Date and Time # tell me the time import time print(time.time()) # number of seconds since January 1, 1970, at 00:00:00 AM # measure time lapse of each loop t1 = time.time() for x in range(0, max): print(x) t2 = time.time() print('it took %s seconds' % (t2-t1)) print(time.asctime()) t = (2020, 2, 23, 10, 30, 48, 6, 0, 0) print(time.asctime(t)) local_time = time.localtime() print(local_time) year, month, day = t[0], t[1], t[2] # time to sleep for x in range(1, 61): print(x) time.sleep(1) # dates are easily constructed and formatted from datetime import date now = date.today() now datetime.date(2003, 12, 2) now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") # '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' # dates support calendar arithmetic birthday = date(1964, 7, 31) age = now - birthday age.days #14368 ## Random number generator import random print(random.randint(1, 100)) # pick a number randomly between 1 and 100 print(random.randint(100, 1000)) # pick a number randomly between 100 and 1000 # Guess a number between 1 and 100 num = random.randint(1, 100) while True: print('Guess a number between 1 and 100') guess = input() i = int(guess) if i == num: print('You guessed right') break elif i < num: print('Try higher') elif i > num: print('Try lower') desserts = ['ice cream', 'pancakes', 'brownies', 'cookies', 'candy'] print(random.choice(desserts)) random.shuffle(desserts) print(desserts) # pickle python stuff import pickle game_data = { 'player-position' : 'N23 E45', 'pockets' : ['keys', 'pocket knife', 'polished stone'], 'backpack' : ['rope', 'hammer', 'apple'], 'money' : 158.50 } save_file = open('py-pickle.dat', 'wb') pickle.dump(game_data, save_file) save_file.close() # look at the file load_file = open('py-pickle.dat', 'rb') loaded_game_data = pickle.load(load_file) load_file.close() print(loaded_game_data) ## math import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] statistics.mean(data) statistics.median(data) statistics.variance(data) ## read internet from urllib.request import urlopen with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: for line in response: line = line.decode('utf-8') # Decoding the binary data to text. if 'EST' in line or 'EDT' in line: # look for Eastern Time print(line)
true
90628ddd369669a20a04fd89cdb8f5cf1d877705
dada99/python-learn
/functions/lambda1.py
440
4.1875
4
lam = lambda x,y: (x+y)*2 print(lam(2,3)) high_ord_func = lambda x, func: x + func(x)# A lambda function can be a higher-order function by taking a function (normal or lambda) as an argument high_ord_func(2, lambda x: x * x) #Python exposes higher-order functions as built-in functions or in the standard library. Examples include map(), filter(), functools.reduce(), as well as key functions like sort(), sorted(), min(), and max().
true
69d2376a896d78024e056a50b0d57073a9211b27
dada99/python-learn
/builtin/int_bit.py
335
4.375
4
# example for int's bitwise operation a = 1 a_bin = "0b00000001" b = 2 b_bin = "0b00000010" print("a: "+str(a)) print("a_bin: "+str(int(a_bin,2))) print("b: "+str(b)) print("b_bin: "+str(int(b_bin,2))) print("a|b: "+str(a|b)) print("a^b: "+str(a^b)) print("a&b: "+str(a&b)) print("b << 2: "+str(b << 2)) print("b >> 1: "+str(b >> 1))
false
bef9a4909a68a5a9b5b6f1a9a26aa47ceb4e8821
dicodoci/numerosity_estimation
/temp.py
293
4.21875
4
for a in range(10): print("a:", a) for b in range(20): print("b:", b) if a==5: # Break the inner loop... break else: # Continue if the inner loop wasn't broken. continue # Inner loop was broken, break the outer. break
true
13bfebda92512418c1372e77b2855bafca6177f1
dambergn-codefellows/py401_data-structures-and-algorithms
/challenges/array_binary_search/array_binary_search.py
720
4.34375
4
def binary_search(array, value): ''' Use a binary search method to look for a values position in a sorted list. ''' left = 0 right = len(array) - 1 while(left <= right): mid = (left + right) // 2 if array[mid] is value: print(mid) return mid elif value < array[mid]: right = mid - 1 elif value > array[mid]: left = mid + 1 print(-1) return -1 # binary_search([1,2,3,4,5,6,7,8,9], 5) # 4 # binary_search([1,2,3,4,5,6,7,8,9], 2) # 1 # binary_search([1,2,3,4,5,6,7,8,9], 8) # 7 # binary_search([1,2,3,4,5,6,7,8,9], 4.5) # -1 # binary_search([2,4,6,8,10,12,14,16,18], 10) # 4 binary_search([4,8,15,16,23,42], 15) # 2 # binary_search([11,22,33,44,55,66,77], 90) # -1
true
01fc7f68deba266ccaab0933594cfec5958df43f
Anujsewani/python-tasks
/prob5.py
356
4.1875
4
#!/usr/bin/python3 import datetime time=datetime.datetime.now() name=input("enter your name ") if time.hour<12 and time.hour>4: print('good morning ',name) elif time.hour>=12 and time.hour<16: print('good afternoon ',name) elif time.hour>=16 and time.hour<22: print('good evening ',name) elif time.hour>=22 and time.hour<=4: print('good night ',name)
true
cc324e1ab782d08076dd8a0eb75c46a1aa508112
spark721/ds_al
/AlgoExpert/Tries/suffix_trie_construction.py
1,693
4.3125
4
# Suffix Trie Construction # Write a class for a suffix-trie-like data structure. # The class should have a "root" property set to be the root node of the trie. # The class should support creation from a string and the searching of strings. # The creation method (called populateSuffixTrieFrom()) will be called # when the class is instantiated and should populate the "root" property of the class. # Note that every string added to the trie should end with # the special "endSymbol" character: "*". # Do not edit the class below except for the # populateSuffixTrieFrom and contains methods. # Feel free to add new properties and methods # to the class. class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrieFrom(string) def populateSuffixTrieFrom(self, string): for i in range(len(string)): self.insert(i, string) def insert(self, i, string): node = self.root for j in range(i, len(string)): letter = string[j] if letter not in node: node[letter] = {} node = node[letter] node[self.endSymbol] = True def contains(self, string): node = self.root for letter in string: if letter not in node: return False node = node[letter] return self.endSymbol in node word = 'invisible' # word = 'test' trie = SuffixTrie(word) # print(trie.root) def test_case(word): for i in reversed(range(len(word))): substring = word[i:] print(f'substring: {substring}') print('\t',trie.contains(substring)) # test_case(word)
true
75965525cd9a54b44f47221084f5c01bafecf666
tijugeorge/Python-code-practice
/DB-API.py
387
4.40625
4
import sqlite3 # Fetch some student records from the database. db = sqlite3.connect("students") c = db.cursor() query = "select name, id from students order by name;" c.execute(query) rows = c.fetchall() # First, what data structure did we get? print "Row data:" print rows # And let's loop over it too: print print "Student names:" for row in rows: print " ", row[0] db.close()
true
be9ba7ba9d1a0b18d39e15061eeefed588964300
gravyboat/python-exercises
/exercises/ex18.py
302
4.34375
4
#!/usr/bin/python def check_if_pangram(string_to_check): ''' Check if a string is a pangram (uses all letters of alphabet) ''' alphabet = 'abcdefghijklmnopqrstuvwxyz' for char in alphabet: if char not in string_to_check: return(False) return(True)
true
1ddef769c15cfcddbdcd6cb854f18fb87dee9e44
gravyboat/python-exercises
/exercises/ex6.py
357
4.25
4
#!/usr/bin/python def sum(*args): ''' Adds all arguments together ''' final_sum = 0 for number in args: final_sum += number return(final_sum) def multiply(*args): ''' Multiplies all arguments together ''' final_sum = 1 for number in args: final_sum = final_sum * number return(final_sum)
true
a426600a76f39ccc9286e6b36f96a22844812450
relativelyIntuitive/Notes
/Algos/recursion.py
1,161
4.1875
4
# def sigma(numInput): # #BASE CASE # if numInput == 1: # return 1 # else: # #implement forward progress by recursively calling the function itself with input(s) that take us one step closer to the base case # return numInput + sigma(numInput-1) # print(sigma(4)) #4+3+2+1 = 10 # print(sigma(3)) #3+2+1 = 6 # print(sigma(2)) #2+1 = 3 # print(sigma(1)) #1 BASE CASE def sigma(num): if num == 1: return 1 else: return num + sigma(num - 1) print(sigma(3)) # “ Recursive Fibonacci # Write rFib(num). Recursively compute and return numth Fibonacci value. As earlier, treat first two (num = 0, num = 1) Fibonacci vals as 0 and 1. # Examples: rFib(2) = 1 (0+1); rFib(3) = 2 (1+1); rFib(4) = 3 (1+2); rFib(5) = 5 (2+3). rFib(3.65) = rFib(3) = 2, rFib(-2) = rFib(0) = 0.” # Excerpt From: Martin Puryear. “Algorithm Challenges: E-book for Dojo Students.” iBooks. import math def rFib(input): num = math.floor(input) if num < 0: return 0 if num == 0: return 0 if num == 1: return 1 else: return rFib(num - 1) + rFib(num - 2) print(rFib(5.9))
true
ce01e52bd7523ffb8ed5778da71f175c6298bf33
benzispawn/Python_Programs
/rock_scissor_paper.py
1,539
4.21875
4
def game(): print("You are about to begin a Rock, scissor and paper game! \ Put the name of the players above") player_1 = input("What's is your name?") player_2 = input("What's is the name of the second player?") play_1 = input(player_1+" choose rock, scissor or paper:") play_2 = input(player_2+" choose rock, scissor or paper:") def winner(): rock = "rock" paper = "paper" scissor = "scissor" if (rock and paper): print("Paper wins!") if (player_1 is rock and player_2 is paper): print(player_2+" won the game!Congrats!!!") else: print(player_1+" won the game!Congrats!!!") elif (rock and scissor): print("Rock wins!") if (player_1 is rock and player_2 is scissor): print(player_1+" won the game!Congrats!!!") else: print(player_2+" won the game!Congrats!!!") else: print("Scissor wins") if (player_1 is scissor and player_2 is paper): print(player_1+" won the game!Congrats!!!") else: print(player_2+" won the game!Congrats!!!") while (play_1 == play_2): print("Oops! Play again!") play_1 = input(player_1+" choose rock, scissor or paper:") play_2 = input(player_2+" choose rock, scissor or paper:") break else: print(player_1+" and "+player_2+" typed "+play_1+" and "+play_2) winner() game()
true
9835133c5bd78955c3383b12ea2e70f3ec1f11df
samarthdave/coe332
/hw01/generate_animals.py
1,998
4.375
4
# https://coe-332-sp21.readthedocs.io/en/main/homework/homework01.html import random import json import petname # python3 -m pip install petname """ { "animals": [ { "head": "snake", "body": "sheep-bunny", "arms": 2, "legs": 12, "tail": 14 }, ... A head randomly chosen from this list: snake, bull, lion, raven, bunny A body made up of two animals randomly chosen using the petname library A random number of arms; must be an even number and between 2-10, inclusive A random number of legs; must be a multiple of three and between 3-12, inclusive A non-random number of tails that is equal to the sum of arms and legs """ SEED_HEADS = ["snake", "bull", "lion", "raven", "bunny"] def build_animal(): random_head = random.choice(SEED_HEADS) random_body = petname.Generate() # random, even number between 2 and 10 # choices: - generate random between 1-5 then multiply by 2 # ex. 2*randint(1,5) # - or # ex. list(range(2, 11, 2)) --> [2, 4, 6, 8, 10] # then random.choice(... list/iterable here) random_arms = random.choice(range(2, 11, 2)) # start @ 2 --> 11 (exclusive end), step by 2 # multiple of three and between 3-12, inclusive random_legs = 3 * random.randint(1, 4) random_tails = random_arms + random_legs new_animal = dict( head=random_head, body=random_body, arms=random_arms, legs=random_legs, tail=random_tails ) return new_animal def main(): # make result list result_lst = list() # add 20 new animals for _ in range(20): result_lst.append(build_animal()) # convert to json & write to file write_content = { "animals": result_lst } OUT_FILE = 'animals.json' # write the file with tab size 4 with open(OUT_FILE, "w") as outfile: json.dump(write_content, outfile, indent=4) if __name__ == '__main__': main()
true
1f15744d140f6b86922648f74b05fa1d0c516aaf
gonzaemon111/python-practice
/base/conditinal_branch.py
1,116
4.15625
4
# x < y xがyより小さければTrue # x <= y xがyより小さいか等しければTrue # x > y xがyより大きければTrue # x >= y xがyより大きいか等しければTrue # x == y xとyの値が等しければTrue # x != y xとyの値が等しくなければTrue # x is y xとyが同じオブジェクトであればTrue # x is not y xとyが同じオブジェクトでなければTrue # x in y xがyに含まれていればTrue # x not in y xがyに含まれていなければTrue def if_test(num): if num > 100: print('100 < num') elif num > 50: print('50 < num <= 100') elif num > 0: print('0 < num <= 50') elif num == 0: print('num == 0') else: print('num < 0') if_test(1000) # 100 < num if_test(70) # 50 < num <= 100 if_test(0) # num == 0 if_test(-100) # num < 0 # 以下のように二つの条件文を同時にも可能 def if_test2(num): if 50 < num < 100: # ここ print('50 < num < 100') else: print('num <= 50 or num >= 100') if_test2(70) # 50 < num < 100 if_test2(0) # num <= 50 or num >= 100
false
87dd1cb2615d85e22a2e617a8c9e91f8307e0912
emrullahgulcan/8.hafta_odevler-Fonksiyonlar
/8Hafta-Odevler.py/9-HarfSorgulama.py
727
4.25
4
"""Kullanıcıdan bir input alan ve bu inputun içindeki büyük ve küçük harf sayılarının veren bir fonksiyon yazınız.""" def sorgulamafonksiyon(s): lower =0#kucuk harfleri tutan degisken upper = 0#buyuk harfleri tutan degisken for c in s:#butun harflere tek tek bak if c.islower():#kucuk harf varsa kucuk harf degiskenine gonder lower+=len(c) if c.isupper():#buyuk harf varsa buyuk harf degiskenine gonder upper += len(c) print("kucuk harf sayisi:", lower, "buyukharf sayisi", upper) while True: try:#string disinda bir degerde uyar s = input("bir sozcuk giriniz") print(sorgulamafonksiyon(s)) except: print("bir hata olustu")
false
a8950bbe90ee572abfb4981f288eb8a6d6e8e259
vitaliksokil/pythonlabs
/lab61.py
488
4.125
4
import math def triangleArea(AB,BC,CA): if AB + BC > CA: s = (AB+BC+CA)/2 A = math.sqrt(s*(s-AB)*(s-BC)*(s-CA)) return A else: exit('Incorrect lengths!!!') try: AB = float(input('Enter length of AB side of triangle: ')) BC = float(input('Enter length of BC side of triangle: ')) CA = float(input('Enter length of CA side of triangle: ')) A = triangleArea(AB,BC,CA) print('Area of the triangle is : ',A) except ValueError: print('Please enter a number!!!')
true
499201f1025dd1534fb1327296d7b6635a9467c7
brandeddavid/pandas-videos
/moviesLensUsers.py
1,612
4.3125
4
import pandas as pd headers = ["user_id", "age", "gender", "occupation","zip_code"] data = pd.read_csv('data/u.user', sep = '|', names = headers) data.set_index('user_id', inplace=True)#sets user_id as the index #SLICING DATA FRAMES print(data[5:10])#Carrying out slicing operation just like on other data types ofinterest = ['age','gender','occupation']#Speciffy the columns you are interested in print(data[ofinterest].head())#head function prints the first 5 entities of the interested fileds in the dataframe print(data[data.age>30].tail(15)) """ The concept of boolean indexation. Data can be manipulated to make queries of specific interest. In the example above the last 15 entries whose age are over 30 years will be printed out. The head and tail functions can take parameters specifying the number needed. Multiples queries can be made in a single statement. See below """ print(data[(data.gender == 'M') & (data.age>30)].head())#the first 5 male users over 30 years of age #We would also want to know just their occupations print(data['occupation'][(data.gender == 'M') & (data.age>30)].head())#Occupations of the first 5 male users over 30 years of age #The count function. #1. List all male and female occupations and count number of people in each print("All male occupations and number of people in each\n") print(data['occupation'][data.gender == 'M'].value_counts()) print("All female occupations and number of people in each\n") print(data['occupation'][data.gender == 'F'].value_counts()) #Gender comparison print("Gender Count: \n") print(data.gender.value_counts())
true
aa132368ccdd4eb94b87d625a4bcd60932b98e3e
xcaptain/leetcode
/binary_tree.py
1,241
4.1875
4
# python binary tree class BinaryNode: def __init__(self, value = None): self.value = value self.left = None self.right = None def add(self, val): if val <= self.value: if not self.left: # 左子树为空,直接设置左子树 self.left = BinaryNode(val) else: self.left.add(val) else: if not self.right: self.right = BinaryNode(val) else: self.right.add(val) class BinaryTree: def __init__(self): self.root = None def add(self, value): if self.root is None: self.root = BinaryNode(value) else: self.root.add(value) def __contains__(self, target): node = self.root while node: if target < node.value: node = node.left elif target > node.value: node = node.right else: return True return False if __name__ == '__main__': t = BinaryTree() t.add(5) t.add(3) t.add(6) t.add(2) t.add(4) t.add(7) print(t.__contains__(3)) print(t.__contains__(4)) print(t.__contains__(1))
true
be87af26502dcfa12edfd85fc82f149e8a84629e
tjsperle-matc/python
/week6-flowcontrol.py
2,202
4.15625
4
#!/usr/bin/env python3 print("""You enter a dark froom with two doors. Do you go through door #1, door #2, or door #3?""") door = input("-> ") # == Door Number 1 logic ======================= if door =="1": print("There's a giant fire breathing dragon in front of you guarding her eggs.") print("What do you do?\n") print("1. Take an egg.") print("2. Say what's up to the dragon.") # == dragon logic ============================ dragon = input("-> ") if dragon == "1": print("1) The dragon incinerated you alive. Good job!") elif dragon == "2": print("2) The dragon waives hello with her little arm. Nice!") else: print(f"N)Well, doing {dragon} is probably better.") print("The dragon flew away.") # == Door Number 2 logic ======================= elif door == "2": print("You find yourself at the top of Mt. Everest.") print("What are you gonna do?\n") print("1. Snowboard/Ski down.") print("2. Climb down.") print("3. Jump off.") # == Insanity logic ======================== insanity = input("-> ") if insanity == "1" or insanity == "2": print("1) You somehow survive, but with severe frostbite.") print("1) Good Job!") elif insanity == "3": print("N) You get some sick air time on the way down, but didn't quite stick the landing.") print("N) You're dead!") else: print("N) You decide to walk back through the door.") print("N) Good decision!") # == Door Number 3 logic ======================= elif door =="3": print("You find yourself getting chased by a tiger.") print("What do you do?\n") print("1. Stop in your tracks, and pet the tiger.") print("2. Run like hell.") # == Tiger logic ============================ tiger = input("-> ") if tiger == "1": print("1) All he wanted was a rub, he's purring like a kitten!") elif tiger == "2": print("2) The tiger catches you and rips you to shreds. Good job!") else: print(f"N)Well, doing {tiger} is probably better.") print("The tiger fled away.") else: print("You did not select a door??? Good Call :)")
true
452140caeea7b05f75a71956b07f4bb5bfcb8f3f
vishnupanikar/Data-Structure
/Data Structures/Python/linked_list.py
2,876
4.3125
4
# Python does not support pointers so we store the object location in another object #---------------Node for the linked list--------- class Node: def __init__(self): self.data = None self.next = None #-------------Create linked list-------------- def create(head , data): node = Node() node.data = data if head == None: head = node else: temp = head # this is correct as temp is a label pointing to the object same as head # change in temp means temp is now pointing to a new object and head is still pointing to the original object #so retaining the start of the linked list while(temp.next != None): temp = temp.next temp.next = node return head #------------Inserting new head--------------- def insert_head(head,data): node = Node() node.data = data node.next = head head = node return head #-----------Inserting at index------------- def insert_index(head , data , pos): i = 0 while(i < (pos -2)): head = head.next i += 1 node = Node() node.data = data node.next = head.next head.next = node #------------Deleting head-------------- def delete_head(head): head = head.next return head #-------------Deleting at index--------------- def delete_index(head , pos): i = 0 while(i < (pos -2)): head = head.next head.next = head.next.next #------------Displaying Linked list------------- def display(head): print() while head != None: print(head.data , end = '-->') head = head.next print() #--------------Main------------------- if __name__ == '__main__': head_node = None #----------------Creating Linked List------------------- node_count = int(input("Enter Number of nodes :: ")) for i in range(node_count): data = int(input("Enter node Value :: ")) head_node = create(head_node , data) #----------------Displaying the list----------------- display(head_node) #--------------Inserting new head--------------- data = int(input("Enter node Value :: ")) head_node = insert_head(head_node , data) display(head_node) #------------inserting at index------------ data = int(input("Enter node Value :: ")) pos = int(input('Enter Position :: ')) insert_index(head_node,data,pos) display(head_node) #------------deleting head-------------- head_node = delete_head(head_node) display(head_node) #------------deleting at index----------- pos = int(input('Enter Position :: ')) delete_index(head_node , pos) display(head_node)
true
3f7ae26797f22a364b6e066adb43b20db70ad078
Chavz24/sql
/SQL/sql.py
360
4.125
4
import sqlite3 # create a db or if it does not exist # or connects to a db if it exist conn = sqlite3.connect("new.db") # create a cursor to eecute sql commands cursor = conn.cursor() # create a table cursor.execute( """CREATE TABLE IF NOT EXISTS population (city TEXT, state TEXT, pupulation INT)""" ) # close the connection to db conn.close()
true
2a07ff791aac6d4174290b9ac16d9b7aec304972
danielwu37/data_visualization
/ifelse.py
447
4.25
4
#条件判断 age = 20 if age >= 18: print("your age is " ,age) print("adult") #条件判断 age = 3 if age >= 18: print('your age is', age) print('adult') else: print('your age is', age) print('teenager') #加上输入 birth = input('birth:') birth = int(birth) if birth < 2000: print("00前") else: print('00后') s = input('birth:') birth = int(s) if birth < 2000: print("00前") else: print('00后')
false
c799a6ac79093e49b18c09befd00911e69bd9de1
Nikhil8595/python-programs
/assignment1-fab.py
328
4.125
4
"""make fibonacci series by comprehension""" n=int(input("enter the number :")) l=[0,1] print(l[-1]) print(l[-2]) list1=[l.append(l[-1]+l[-2]) for a in range(2,n)] print(l) """without comprehension""" """n=(int(input("enter the digit:"))) n1=0 n2=1 for key in range(n): print(n1,end=' ') n1,n2=n2,n1+n2"""
false
32806220553410ca796ec971bb678e9d57119b03
jimcarson/datascience
/assignment3/matrix_multiply.py
1,778
4.15625
4
import MapReduce import sys """ Matrix multiply. Assume two matrices A and B in a sparse matrix format, where each record is of the form i, j, value. Compute the matrix multiplication A x B Each list will be in th eform: [matrix, i, j, value] where matrix is a string ("a" from matrix A, "b" from B), and i,j, value are integers. Per this discussion (and that we are told the matrix is sparse), we can assume we know the dimensions. https://class.coursera.org/datasci-002/forum/thread?thread_id=1436 """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line MATDIM = 5 def mapper(record): key = record[0] i = record[1] j = record[2] value = record[3] if key == "a": mr.emit_intermediate(key, [i,j,value]) elif key == "b": mr.emit_intermediate(key, [j,i,value]) else: print "Error." def reducer(key, list_of_values): A = {} B = {} result = 0 if key == "a": for a in list_of_values: A[(a[0], a[1])] = a[2] for b in mr.intermediate["b"]: B[(b[0], b[1])] = b[2] # fill in zeros for i in range(0,MATDIM): for j in range(0,MATDIM): k = (i,j) if k not in A.keys(): A[k] = 0 if k not in B.keys(): B[k] = 0 # now do the multiply. for i in range(0,MATDIM): for j in range(0,MATDIM): result = 0 for k in range(0,MATDIM): result += A[(i,k)] * B[(j,k)] mr.emit((i,j,result)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
true
fa3907792e886693da7c0c0c233f00bf0870ecbe
iziumska/Softserve_tasks
/file_parser/task4_file_parser/main_file_parser.py
1,019
4.5
4
# !/usr/bin/env python """ File parser The program operates in two modes: 1. Reads the number of occurrences of a string in a text file. 2. Makes changing a string to another in the specified file The program accepts input arguments at startup: 1. <path to file> <string for counting> 2. <path to file> <string to search> <string to replace> """ import sys from validation_argv_file import is_validation_argv from work_with_file import counting_string, replace_string def main(): if not is_validation_argv(): print('Enter the correct data for processing:\n' '<path to file> <string for counting> or <path ' 'to file> <string to search> <string to replace>') quit() file_name = sys.argv[1] sourse_text = sys.argv[2] if len(sys.argv) == 3: counting_string(file_name, sourse_text) elif len(sys.argv) == 4: replace_text = sys.argv[3] replace_string(file_name, sourse_text, replace_text) if __name__ == '__main__': main()
true
86b8ce2b7fcfb0a2909ab5487d064175a50de4e9
wwt0805/ai04
/p16_sqrt_newton.py
852
4.15625
4
""" coding=utf-8 @Author : Wu Wentong @Time : 2021/2/24 9:24 下午 @Site : @File : p16_sqrt_newton.py @Software: PyCharm """ def sqrt(a, n=2): # 牛顿法求平方根函数 x = 1 # 赋初值,如果初值为正则求得正平方根,否则为负平方根 y = lambda x: x ** n # lambda函数定义所求函数式 注意lambda表达式必须有返回值(y)!!! dy_dx = lambda x: 2 * x # lambada函数定义导函数式 delta_y = lambda x: a - y(x) delta_x = lambda x: delta_y(x) / dy_dx(x) # 牛顿法定义 # dx = dy / y' = (a - x ** 2) / 2x # x' = x + dx = (a + x ** 2) / 2x for _ in range(10): x += delta_x(x) return x if __name__ == "__main__": for x in range(1, 10 + 1): print("sqrt({}) = {}".format(x, sqrt(x)))
false
deea527fda79375596fbf66685d144d766f0cabe
kislitsind/kursovaya-1-31
/2.py
587
4.15625
4
Задача: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами. Найти наибольшее значение среди средних значений для каждой строки матрицы. import numpy as np print("Введите число строк:") n = int(input()) print("Введите число столбцов:") m = int(input()) arr = np.random.randint(10,20,(n,m)) arrav=arr.mean(axis=1) print(arrav) arrmax = arrav.max() print(arrmax)
false
01b6ae91c62bd3020fec66b6798535ebe3073af7
dhananjay1438/Python
/Basic/conditions/ternery_operator_1.py
228
4.21875
4
# This is how ternary operator works in python # There is no ?: operator in python # It just uses if and else at the end of the statement a = 10 b = 20 print("b is greater than a ") if b > a else print("a is greater than b")
true
e62a525ae4ab366cbba09708d693a9a6ec1be67d
TsymbaliukOleksandr1981/Python-for-beginners
/lesson_3/task_3.py
270
4.125
4
year = int(input("Input year: ")) if year > 0: day = 365 if year % 4 == 0: day = 366 if year % 100 ==0: day = 365 if year % 400 ==0: day = 366 print("Days number = ", day) else: print("Sorry but you input negative year")
false
5c2f8c6344ce84c0134ff4da8d2861b2ec66f1d5
TsymbaliukOleksandr1981/Python-for-beginners
/lesson_3/additional task_4.py
362
4.125
4
number = int(input("Input number: ")) part_1 = number // 100000 part_2 = number % 100000 // 10000 part_3 = number % 10000 // 1000 part_4 = number %1000 // 100 part_5 = number %100 // 10 part_6 = number %10 // 1 if part_1 == part_6 and part_2 == part_5 and part_3 == part_4 : print(number, " is palindrome") else: print(number, " not palindrome")
true
6bd005cabb4c2e5e64cec34fb21bd9277067478e
joshma25/hangman
/venv/Hangman.py
2,139
4.15625
4
import random import string from words import words def get_word(): word = random.choice(words) while '-' in word or ' ' in word: word = random.choice(words) return word.upper() def game(word): numberofTries = 6 word = get_word() word_list = set(word) letterstried = set() alphabet = set(string.ascii_uppercase) wordcorrect = False hints = 0 while not wordcorrect and numberofTries > 0: word_print = [letter if letter in letterstried else '_' for letter in word] word_print_list = list(word_print) print(' '.join(word_print)) if word_print_list.count('_') == 0: wordcorrect = True break letterguess = input("Guess a letter or type * for a hint: ").upper() #print("The word is ", word) if letterguess == '*': while True: if hints < 3: while True: letterhint = random.choice(word) if letterhint not in letterstried: hints += 1 print('Hints used: ', hints) break else: print('You have used up all 3 of your hints') break break print(letterhint, ' is in the word') elif len(letterguess) == 1 and letterguess.isalpha(): if letterguess in alphabet - letterstried: letterstried.add(letterguess) if letterguess not in word_list: numberofTries -= 1 print(letterguess, ' is not in the word') else: print("Good guess, ", letterguess, " is in the word") elif letterguess in letterstried: print('You have already used that letter') else: print("That's not a valid input") if numberofTries == 0: print('You lose') elif wordcorrect is True: print('You win!') def main(): word = get_word() game(word) if __name__ == '__main__': main()
true
3b3c3b9bf2d1968ce13eb231c5071a8986523df9
qq1295334725/zheng
/第一周/7-23/全局变量和局部变量的作用域.py
1,689
4.3125
4
""" 座右铭:将来的你一定会感激现在拼命的自己 @project:预科 @author:Mr.Chen @file:全局变量和局部变量的作用域.PY @ide:PyCharm @time:2018-07-23 11:24:48 """ # 变量的作用域:指一个变量所产生的作用范围,也就是说在哪一个范围内变量能够被解释器所识别。 # 变量分为:全局变量和局部变量 # 全局变量:一般声明在函数外部。 # 全局变量的作用域:整个.py文件内部都可以使用,都可以被识别。 # 局部变量:一般声明在函数内部。 # 局部变量作用域:只能在函数的内部使用,超出范围,变量就不能再使用。 # list1相当于全局变量,作用域是整个.py文件。 list1 = [] def add_test(): # a是局部变量,只能在函数内部使用 a = 1 list1.append(a) print('局部变量:%s'%a) print(list1) add_test() list1.append(2) print('全局变量:%s'%list1) name = '郑三' def show_name(): # 默认情况下,如果全局变量和局部变量变量名相同,在函数内部是无法识别到函数外部的全局变量的。 # local variable 'name' referenced before assignment:局部变量在声明之前被引用 # 因为变量的引用会采取就近原则,会看最近的变量在那,发现最近的变量是name='李四',但是提前使用了name这个变量,然后声明了name=‘李四’,所以出现了先引用后声明的错误。 # global:将一个已经声明好的全局变量在函数内部重新声明,可以避免和同名的局部变量重名。 global name print('姓名:%s'%name) name = '李四' print('姓名_1:%s'%name) show_name()
false
040041350cc5c2948a3c7aecd2edb3c3bd631827
qq1295334725/zheng
/第一周/7-23/生成器函数.py
1,769
4.375
4
""" 座右铭:将来的你一定会感激现在拼命的自己 @project:预科 @author:Mr.Chen @file:生成器函数.PY # @ide:PyCharm @time:2018-07-23 14:34:05 """ # 生成器函数:当一个函数带有关键字的时候,那么它将不再是一个普通的函数,而是一个生成器generator. # yield和return:这两个关键字十分相似,yield每次只返回一个值,而return则会把最终的结果一次性返回。 # 每当代码执行到yield的时候就会直接将yield后面的值返回出去,下一次迭代的时候,会从上一次遇到yield之后的代码开始执行。 def test(): list1 = [] for x in range(1, 10): list1.append(x) return list1 res = test() print(res) def test_1(): for x in range(1, 10): yield x generator = test_1() print(generator) print(next(generator)) print(next(generator)) print(next(generator)) print(next(generator)) print(next(generator)) print(next(generator)) # 生成器函数的例子,母鸡下蛋。 # 1.一次性把所有的鸡蛋全部下下来。 # 如果一次性把所有的鸡蛋全部下下来,一是十分的占地方,二是容易坏。 def chicken_lay_eggs(): # 鸡蛋筐列表 basket = [] for egg in range(1, 101): basket.append(egg) return basket eggs = chicken_lay_eggs() print('一筐子鸡蛋:',eggs) # 这样做的好处:第一是省地方,第二是,下一个吃一个,不会让鸡蛋坏掉。 def chicken_lay_eggs_1(): for egg in range(1,101): print('战斗母鸡正在下第{}个蛋'.format(egg)) yield egg print('我给{}蛋给吃了!'.format(egg)) eggs_1 = chicken_lay_eggs_1() print(next(eggs_1)) print(next(eggs_1)) print(next(eggs_1)) # for x in eggs_1: # print(x)
false
0fc17360b4e51a3ec59a075d944c1b86ed19af24
ckennedy546x/MIS3640
/quiz1.py
1,564
4.28125
4
# Question 1 import math def crazy_about_9(a, b): """ a, b: two integers Returns True if either one is 9, or if their sum or difference is 9. """ if a or b == 9: return True elif a + b == 9: return True elif b - a == 9: return True elif a - b == 9: return True else: return False # When you've completed your function, uncomment the # following lines and run this file to test! print(crazy_about_9(2, 9)) print(crazy_about_9(4, 5)) print(crazy_about_9(3, 8)) # Question 2 def leap_year(year): """ year(int): a year Returns True if year is a leap_year, False if year is not a leap_year. """ if year % 4 == 0: return True elif year % 400 == 0: return True elif year % 100 == 0: return False else: return False # When you've completed your function, uncomment the # following lines and run this file to test! print(leap_year(1900)) print(leap_year(2016)) print(leap_year(2017)) print(leap_year(2000)) #Question 3 """ ----------------------------------------------------------------------- Question 3: Write a function with loops that computes The sum of all squares between 1 and n (inclusive). """ def sum_squares(n): result = 0 for i in range(1, n+1): result print(math.s # When you've completed your function, uncomment the # following lines and run this file to test! print(sum_squares(1)) print(sum_squares(100))
true
356f4957f4989b9a7a11bd4e85f9aa13046c3ba9
chr1sbest/ctci
/python/Assorted_Algorithms/3sum.py
712
4.1875
4
def three_sum(target, array): """ Given an array of integers, return all three-integer combinations that total up to the target value. Time complexity: O(n^2) """ array = sorted(array) solutions = [] for index, val in enumerate(array[:-2]): begin = index + 1 end = len(array) - 1 while begin < end: total = val + array[begin] + array[end] if total == target: solutions.append([val, array[begin], array[end]]) if total > target: end -= 1 else: begin += 1 return solutions if __name__ == "__main__": print three_sum(3, [-1, -2, -3, 0, 1, 2, 3, 4, -5])
true
d92a6ce176bdeedcd8741ce5f89a98639c8d414b
chr1sbest/ctci
/python/8_Object_Oriented_Design/8_1.py
2,618
4.1875
4
""" Design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack. """ class Deck(object): def __init__(self, shuffle=False): self.cards = self.build_deck() self.discards = [] if shuffle == True: self.shuffle() def build_deck(self): """Builds standard deck of 52 cards with four suits""" spades = [Card("Spade", x) for x in range(1, 13)] hearts = [Card("Heart", x) for x in range(1, 13)] diamonds = [Card("Diamond", x) for x in range(1, 13)] clubs = [Card("Club", x) for x in range(1, 13)] return spades + hearts + diamonds + clubs def draw(self): """Pops card at end, returns the card, and adds to discard""" card = self.cards.pop() self.discards.append(card) return card def shuffle(self): """Implemenets Knuth Shuffle to randomly shuffle cards""" self.cards.append(self.discards) self.discards = [] class Card(object): def __init__(self, suit, value): self.suit = suit self.value = value ############################################## class BlackJackDeck(Deck): def __init__(self): super(BlackJackDeck, self).__init__() def build_deck(self): """ Builds special deck to take into account the special values of blackjack cards. 10-K are 10, Ace is 1. """ values = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] spades = [Card("Spade", x) for x in values] hearts = [Card("Heart", x) for x in values] diamonds = [Card("Diamond", x) for x in values] clubs = [Card("Club", x) for x in values] return spades + hearts + diamonds + clubs class BlackJackHand(object): def __init__(self, deck): self.cards = [] self.deck = deck self.draw() self.draw() def draw(self): self.cards.append(self.deck.draw()) self.total = sum(self.cards) self.check_total() def check_total(self): """Define draw/stand strategy depending on sum""" if self.total < 17: self.draw() elif 17 <= self.total < 21: self.stand() elif self.total > 21 and 11 in self.cards: self.ace_switch() self.check_total() else: self.bust() def ace_switch(self) """Switches the value of Ace from 11 to 1""" index = self.cards.index(11) self.cards[index] = 1 def stand(self): pass def bust(self): pass
true
256dd4fce1421607d480e70fe624712ef52ee2d3
chr1sbest/ctci
/python/Assorted_Questions/power.py
600
4.28125
4
def naive_pow(base, exp): """ Calculate base^exp using naive iteration. Time complexity: O(n) """ result = 1 for value in xrange(0, exp): result = result * base return result def pow(base, exp, tmp=1): """ Calculate base^exp by using "exponentiation by squaring". Time complexity: O(logn) """ if exp == 1: return base * tmp if exp % 2 == 0: return pow(base * base, exp / 2, tmp) else: return pow(base * base, (exp - 1) / 2, tmp * base) if __name__ == "__main__": print naive_pow(2, 3) print pow(2, 7)
false
87e0936961102fd6a6bfa651747f589db286c52e
xia0nan/LeetCode
/test/test_002.py
1,526
4.15625
4
from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: carry = 0 dummy = ListNode(0) curr = dummy while l1 or l2 or carry: val1 = l1.val if l1 else 0 val2 = l2.val if l2 else 0 carry, sum_val = divmod(val1 + val2 + carry, 10) curr.next = ListNode(sum_val) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None return dummy.next def list_to_listnode(input_list): """ Build ListNode from list """ # initialize node, not to be included in the final result node = ListNode() # keep node at the beginning of the linked list temp = node if len(input_list) == 1: # if single node, return as it is node.next = ListNode(val=input_list[0], next=None) else: for i in input_list: current_node = ListNode(val=i) # next node is current node temp.next = current_node # move node to next node to build the linked list temp = temp.next # exclude the root node return node.next def test_addTwoNumbers(): list_node_1 = list_to_listnode([2, 4, 3]) list_node_2 = list_to_listnode([5, 6, 4]) target_node = list_to_listnode([7, 0, 8]) assert addTwoNumbers(list_node_1, list_node_2) == target_node
true
ecbf69a8d1cdb2319792fa0007153c5459403684
MattRahlfs/Python-Projects
/tip_calc.py
1,340
4.34375
4
#generate a number for the bill #ask if they want to split the bill (how many ways) #let the user choose what percent of a tip to leave ( is it the same for each person?) # import random bill_cost = round(random.uniform(10.0, 1000.00), 2) print ("Your bill is: $" + str(bill_cost) ) input_value = input("Do you want to split you bill? y/n\n") def get_tip_percent(): tip_percent = int(input('Enter the tip percent you would like to apply to your bill.\n')) tip_percent = tip_percent / 100 return tip_percent def get_total_cost(bill_cost, tip_percent): total_bill = (bill_cost * tip_percent) total_bill = total_bill + bill_cost return round((total_bill), 2) def split_bill(total_cost): split_n_ways = 0 while split_n_ways not in [2, 3]: try: split_n_ways = int(input("How many ways do you want to split the bill? You can only split it 2 or 3 ways.\n")) continue except ValueError: continue bill_split_total = round((total_cost / split_n_ways), 2) return bill_split_total if input_value == 'n': print(get_total_cost(bill_cost, get_tip_percent())) elif input_value == 'y': split_bill(get_total_cost(bill_cost, get_tip_percent()))
true
f67e19f14e3c2bc347a543a1681469625805db8c
aaevan/aaevan_rc_files
/scripts/cards.py
2,957
4.4375
4
from random import sample # pick n cards from a full shuffled deck from random import choice # pick one random card, put it back in the deck numbers = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A') suits = ('♠', '♥', '♣', '♦') deck = [] #enumerate allows us to step through "numbers" with an incrementing index: #inside the curly brackets we're doing a dictionary comprehension: card_vals = {number:index + 1 for index, number in enumerate(numbers)} print(card_vals) for number in numbers: for suit in suits: card = (card_vals[number], number, suit) deck.append(card) #(number string, suit string, value of card) for run in range(5): #5 here is how many times we're repeating the below loop hand = sample(deck, 6) #6 here is how many cards we're pulling #each card is a tuple of three values of type (int, str, str) hand_val = sum([card[0] for card in hand]) print(f'hand: {hand}, hand sum: {hand_val}') #the zero after the lambda here means that we're sorting on the first element of the tuple: #the lambda is just a temporary nameless function we use to return something trivial sorted_hand = sorted(hand, key=lambda x: x[0]) #take just the lowest three: print("just the first three:", sorted_hand[:3]) #inside sum (line 37) I'm doing a list comprehension: it's enclosed in some square brackets # what we make a list of is before the 'for' # in this case it's the first (zeroth?) item of our card # 'card' is what we're calling each item (between 'for' and 'in') # after the 'in' is what we're looping over, # sorted_hand[:3] means we're taking a slice of sorted_hand up to but not including the third element sum_of_three_lowest = sum([card[0] for card in sorted_hand[:3]]) print(f"sum of the lowest three:{sum_of_three_lowest}") #print statements are super slow, so when doing a bunch of something, we'll want to comment them out with a '#' #so let's do that again without the fluff, and keep track of our results: print('----------------------------------------------------------------------------') print('okay, actually running the interesting stuff now:\n') #keep our results in a dictionary: results = { 'less than 10':0, 'more than 10':0, } runs = 1000000 hand_size = 6 sum_from_n = 3 #this is the number of lowest-valued cards we're summing for run in range(runs): hand = sample(deck, hand_size) #the below line is taking the sum of the hand, we don't need it: #hand_val = sum([card[0] for card in hand]) sorted_hand = sorted(hand, key=lambda x: x[0]) sum_of_three_lowest = sum([card[0] for card in sorted_hand[:sum_from_n]]) if sum_of_three_lowest < 10: results['less than 10'] += 1 else: results['more than 10'] += 1 #every 100000 runs, give us an update: if run % 100000 == 0: print(f'run: {run}') print(f'results: {results}')
true