blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a516c8d763aad72944dd59d8395b06a9aa1b56b6
dineshkumarkummara/my-basic-programs-in-java-and-python
/folders/python/javatpoint/factorial.py
254
4.15625
4
n=int(input("enter any number:")) factorial=1 if n<0: print("number can not be negative") elif n==0: print("the factorial of 0 is 1") else: for i in range(1,n+1): factorial*=i print("the factorial of" , n ,"is" ,factorial, "." )
false
d3ec9f8db3eceae68a3392d8de84c8acd9155de2
muskanmahajan486/communication-error-checksum
/parity/index.py
409
4.40625
4
# Python3 code to get parity. # Function to get parity of number n. # It returns 1 if n has odd parity, # and returns 0 if n has even parity def getParity( n ): parity = 0 while n: parity = ~parity n = n & (n - 1) return parity # Driver program to test getParity() n = 0 print ("Parity of no ", n," = ", ( "odd" if getParity(n) else "even"))
true
706f75c1b7da25049bdc240b0620b8303fcc8e72
rahulcode22/Data-structures
/Arrays/BubbleSort.py
583
4.4375
4
''' Bubble sort is a example of sorting algorithm . In this method we at first compare the data element in the first position with the second position and arrange them in desired order.Then we compare the data element with with third data element and arrange them in desired order. The same process continuous until the data element at second last and last position ''' def bubbleSort(arr,n): for i in range(0,n): for j in range(0,n): if arr[j]>arr[i]: arr[i], arr[j] = arr[j], arr[i] return arr arr = [3,2,6,4,1] print bubbleSort(arr,5)
true
709312e9a2f50148b6393f5adc5bb9c59d722fb8
rahulcode22/Data-structures
/Two Pointers/RemoveElements.py
660
4.1875
4
''' Given an array and a value, remove all the instances of that value in the array. Also return the number of elements left in the array after the operation. It does not matter what is left beyond the expected length. Example: If array A is [4, 1, 1, 2, 1, 3] and value elem is 1, then new length is 3, and A is now [4, 2, 3] Try to do it in less than linear additional space complexity. ''' def removeElement(arr,target): i = 0 j = 0 n = len(arr) while i < n: if arr[i] != target: arr[j] = arr[i] j += 1 i += 1 return len(arr[0:j]) arr = [4,1,1,2,1,3] target = 1 print removeElement(arr,target)
true
387179e6134508a1d71e818542318548d568258b
rahulcode22/Data-structures
/Math/FizzBuzz.py
670
4.125
4
''' Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. Also for number which are multiple of 3 and 5, prints “FizzBuzz”. ''' class Solution: # @param A : integer # @return a list of strings def fizzBuzz(self, num): lis = [] for i in range(1,num+1): if i%3 == 0 and i%5 == 0: lis.append("FizzBuzz") elif i%3 == 0: lis.append("Fizz") elif i%5 == 0: lis.append("Buzz") else: lis.append(i) return lis
true
f675a20b4fb1b4acd7b8ca903097b07a666909f2
rahulcode22/Data-structures
/Tree/level-order-traversal.py
952
4.125
4
class Node: def __init__(self,key): self.val = key self.left = None self.right = None def printLevelOrder(root): h = height(root) for i in range(1,h+1): printGivenOrder(root,i) def printGivenOrder(root,level): if root is None: return if level == 1: print "%d" %(root.val), elif level >1: printGivenOrder(root.left,level-1) printGivenOrder(root.right,level-1) def height(node): if node is None: return 0 else: #Compute Height of each subtree lheight = height(node.left) rheight = height(node.right) if lheight>rheight: return lheight+1 else: return rheight+1 # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print "Level order traversal of binary tree is -" printLevelOrder(root)
true
ba2d6b6297ea813c6fbfd92782aada21cb368555
rahulcode22/Data-structures
/Doublylinkedlist/DLL_insertion.py
1,145
4.28125
4
#Insertion at front def insertafter(head,data): new_node=node(data) new_node.next=head new_node.prev=None if head is not None: head.prev=new_node head=new_node #Add a node after a given node def insertafter(prev_node,data): if prev_node is None: return #Allocate new node new_node=node(data) #Make ne xt of new_node as next of prev_node new_node.next=prev_node.next #Make next of prev_node as next of new_node prev_node.next=new_node.next #Make prev_node as previous of new_node new_node.prev=prev_node if (new_node.next is not None): new_node.next.prev=new_node #Add a Node at end def insertend(head,data): new_node=Node(data) last=head #This new node is going to be last node,so make it as NULL new_node.next=None if head is not None: new_node.prev=None head=new_node return while (last.next is not none): last=last.next #Change next of last node last.next=new_node #Make last node as previous of new node new_node.prev=last return
true
18208ba62478503b314bb7cae82f24194e732050
cassiakaren/Manipulando-Textos
/aula09.py
867
4.5
4
#FATIAMENTO '''frase='Curso em Video Python' print(frase[3])#vai printar a quarta letra frase='Curso em Video Python' print(frase[:13])#vai de um caracter a outro frase='Curso em Video Python' print(frase[0:15:2])#vai de um caracter a outro pulando de 2 em 2 frase='Curso em Video Python' print(frase[::2]) frase='Curso em Video Python' print(frase.upper().count('O'))#conta quantas vezes tem 'o' e deixa tudo maiuscul frase=' Curso em Video Python ' print(len(frase.strip()))#ler e imprime o tamanho da frase''' '''frase='Curso em Video Python' print(frase.split())#cria uma lista para cada caracter #NA PRÁTICA frase='Curso em Video Python' dividido=frase.split() print(dividido[0])#dividido é uma lista 0= é o primeiro item da lista''' frase='Curso em Video Python' dividido=frase.split() print(dividido[2][3])#um elemento dentro de uma lisgta especifica
false
d3123c6a569f57767865a6972bde32d3b858d348
SamanehGhafouri/Data-Structures-and-Algorithms-in-python
/Experiments/find_largest_element.py
676
4.3125
4
# ######### Find the largest element in array ######## def largest_element(arr): if len(arr) == 0: return None max_num = arr[0] for i in range(len(arr)): print(i, arr[i]) if arr[i] > max_num: max_num = arr[i] return max_num ar = [90, 69, 23, 120, 180] print(largest_element(ar)) # ############# Test Cases ############## test_data = [ ([1, 45, 23, 5, 67], 67), ([-3, -7, 1, 4, 2, -9], 4), ([-4, -1, -9, -3], -1), ([1, 45, 23, 5, 67, 97, 35], 97), ([], None) ] for item in test_data: expected = item[1] computed = largest_element(item[0]) print(expected, computed, expected == computed)
true
5692a8e56f59808656816b733166021af8f5d3c1
SamanehGhafouri/Data-Structures-and-Algorithms-in-python
/Sorting/bubble_sort.py
682
4.3125
4
# Bubble sort: takes an unsorted list and sort it in ascending order # lowest value at the beginning by comparing 2 elements at a time # this operation continues till all the elements are sorted # we have to find the breaking point # Time Complexity: best case: O(n) # average and worst case: O(n^2) def bubble_sort(li): sorted_li = False while not sorted_li: sorted_li = True for i in range(len(li) - 1): if li[i] > li[i+1]: sorted_li = False li[i], li[i+1] = li[i+1], li[i] return li if __name__ == '__main__': l = [9, 3, 1, 6, 8, 22, 0] result = bubble_sort(l) print(result)
true
e35fd14187b0b277064bfc4d2019079376ba4781
SamanehGhafouri/Data-Structures-and-Algorithms-in-python
/Recursion/reverse_str.py
516
4.15625
4
# C-4.16 reverse a string def reverse_str(string): if len(string) == 0: return '' # we cut the first character and put it in # the back of the string each time else: # call the recursive function on the string except the first return reverse_str(string[1:]) + string[0] # character 'amaneh' + 's' and so on st = reverse_str('samaneh') print(st)
true
7a37455274916403acdee17331216be6d7cc0810
SachinKtn1126/python_practice
/11_better_calculator.py
905
4.40625
4
# Title: Creating a better calculator # Author: Sachin Kotian # Created date (DD-MM-YYYY): 07-12-2018 # Last modified date (DD-MM-YYYY): 07-12-2018 # # ABOUT: # This code is to create a better calculator using if else statement and user input. # Input values from the user and store it in variables num1 = float(input("Enter num 1: ")) op = input("Enter operator: ") num2 = float(input("Enter num 2: ")) # Performing mathematical functions using the if else statement if op == "+": print("The sum is " + str(num1 + num2)) elif op == "-": print("The difference is " + str(num1 - num2)) elif op == "/": print("The division is " + str(num1 / num2)) elif op == "*": print("The multiple is " + str(num1 * num2)) elif op == "%": print("The modulus is " + str(num1 % num2)) else: print("Invalid operator")
true
ab0ca448a75ff4094c8c7cfe7f112647a22ec37d
SachinKtn1126/python_practice
/10_if_statements_comparisons.py
1,217
4.15625
4
# Title: If statement in python # Author: Sachin Kotian # Created date (DD-MM-YYYY): 07-12-2018 # Last modified date (DD-MM-YYYY): 07-12-2018 # # ABOUT: # This code is to try and test the working of if statement # Defining boolean variables is_male = False is_tall = False # If statement if is_male: print("You are male") else: print("You are female") # If else statement if is_male and is_tall: print("You are a tall male") elif is_male and not(is_tall): print("You are a short male") elif not(is_male) and is_tall: print("Ypu are a tall female") else: print ("you are a short female") # Defining a function to return the maximum number from 3 numbers def max_num(num1,num2,num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 # Input values from the user num1 = input("Enter num1: ") num2 = input("Enter num2: ") num3 = input("Enter num3: ") # calling the function to get the max number and printing it print("The maximum number is " + str(max_num(int(num1), int(num2), int(num3))))
true
7dccc8e023f5abc096fc502e0d456b73cf052aaa
alfredvoskanyan/Alfred_homeworks
/Homeworks/Shahane/Alfred_Voskanyan_homework2/ex_1.py
226
4.125
4
list1 = [3, 6, True, True, -1, "abc", (1, 2), [2, 3], 6] for i in range(len(list1)): if isinstance(list1[i], tuple): print("Count of elements are ", i) print("Tuple's index in list is :", i) break
false
71111a542b32a7815b1dd9c7f55ea93d3e75c2b0
green-fox-academy/criollo01
/week-02/day-05/palindrome_maker.py
299
4.3125
4
#Create a function named create palindrome following your current language's style guide. # It should take a string, create a palindrome from it and then return it. word = str(input("Write a word! ")) def palin_maker(word): new_word = word + word[::-1] print(new_word) palin_maker(word)
true
601f2398b30c816fb76ee389a8a93995b98d2fa5
green-fox-academy/criollo01
/week-02/day-02/reverse.py
306
4.5625
5
# - Create a variable named `aj` # with the following content: `[3, 4, 5, 6, 7]` # - Reverse the order of the elements in `aj` # - Print the elements of the reversed `aj` aj = [3, 4, 5, 6, 7] # ---solution 1--- for i in reversed(aj): print(i) # # ---solution 2--- (nicer) print(list(reversed(aj)))
true
d00d45e57e5f130d3356cefa7bc7b50d63a185fe
saikrishna96111/StLab
/triangle.py
516
4.1875
4
print("enter three sides of a Triangle in the range (0 to 10)") a=int(input("Enter the value of a ")) b=int(input("Enter the value of b ")) c=int(input("Enter the value of c ")) if a>10 or b>10 or c>10: printf("invalid input values are exceeding the range") if (a<(b+c))and(b<(a+c))and(c<(a+b)): if a==b==c: print("Equilateral Triangle") elif (a==b)or(b==c)or(a==c): print("Isosceles Triangle") else: print("Scalene Triangle") else: print("Not a Triangle")
true
abc28cc6001d0f1c626995ec69eda14235636446
brybalicious/LearnPython
/brybalicious/ex15.py
2,707
4.4375
4
# -*- coding: utf-8 -*- # This line imports the argv module from the sys package # which makes the argv actions available in this script # Interestingly, if you run a script without importing argv, yet you type # in args when you run the script in shell (!= python interpreter), it # still runs and just ignores the args... from sys import argv # Here we unpack argv and store them in variables script, filename = argv # Here we open a file which we're passed as an argv, but don't do anything # with it yet besides storing the open file in a file object variable 'txt' # The contents of the file aren't returned here... txt = open(filename) # The following block is good practice, so that any opened file is always closed in the end, regardless of what happens in between... #>>> with open('workfile', 'r') as f: #... read_data = f.read() #>>> f.closed #True # Just telling you what the file is, to show how argv works print "Here's your file %r:" % filename # Here's the magic.. we read the file we've opened, and display it print txt.read() # This bit's just a useless way of showing you can take a filename from # raw_input... and store that name in the file_again variable, then open # a file object by passing the filename, and storing the open file object # in txt_again print "Type the filename again:" file_again = raw_input("> \a") txt_again = open(file_again) # And then print the contents to shell in the same way - using read() # On the opened file object... print txt_again.read() # Here we will close the file instances we have opened and stored in 'txt' and 'txt_again' file object variables txt.close() txt_again.close() #The following prints a confirmation of whether the objects have been closed... print "Is txt closed?:", txt.closed print "Is txt_again closed?:", txt_again.closed # The sample exercise wants you to type 'python' into shell to open the python interpreter # Then, you're supposed to type the following at the prompt - note the '': #>>> open('ex15_sample.txt').read() # Then you should expect this output: #"This is stuff I like to write.\nComes out when called up by a python script.\nA'ight!" #The mistake I was making is that I was trying to open the python script ex15.py inside the interpreter... that requires something like #>>> execfile('ex15.py') #I guess we'll soon see, but that would be what you'd call to execute a script from inside another script, right? #Pay attention to where you need to pass filenames as strings (bounded by '') and where you don't. I couldn't figure out how to pass the argv elements to execfile, but maybe because I was a n00b trying to pass them to open()
true
712b189becdfd3d7e3d7c4d86d745425e839345c
mkaanery/practicepython.org
/13.py
329
4.1875
4
num = int(input("Number of fibonacci numbers: ")) def fibonacciNumberGenerator(thisMany): fib = [] counter = 0 cur = 0 prev = 1 while(counter != thisMany): cur = cur + prev prev = cur - prev counter = counter + 1 fib.append(cur) print(fib) fibonacciNumberGenerator(num)
false
a9ac682716f455dad84f242ae37a76b5e732d4b4
breadpitt/SystemsProgramming
/python_stuff/simple_calculator.py
472
4.34375
4
#!/usr/local/bin/python3 numone = input("Please enter number one ") op = input("Please enter an operator ") numtwo = input("Please enter number two ") numone = int(numone) numtwo = int(numtwo) if op == "+": result = numone + numtwo print(result) elif op == "*": result = numone * numtwo print(result) elif op == "/": result = numone / numtwo print(result) elif op == "-": result = numone - numtwo print(result) else: print("Not an operator") #print(result)
false
25bc4acccf3f18d73ef6b5a3fa6ea39dd4ba329e
ABradwell/Portfolio
/Language Competency/Python/Basic_Abilities/Arrays, Lists, and Selection sort/Occurances in List.py
1,226
4.3125
4
''' Count the number of an element occurrences in a list • Create a function that takes a list and an integer v, and returns the number of occurrences of v is in the list. Add the variable NP as to count number of times the loop runs (and display a message). • The main program should generate a list, call the function, and display the result. >>> l = 52 14 14 8 85 69 1 77 94 96 51 65 35 32 87 92 74 47 27 88 11 11 26 14 100 37 62 3 63 5 20 53 28 10 43 16 94 6 82 49 74 55 89 97 12 38 72 94 3 77 42 26 25 16 89 10 8 63 93 77 68 56 74 45 54 50 80 33 69 95 2 79 73 6 3 41 38 81 88 12 39 77 49 30 18 22 40 40 12 51 69 32 76 77 90 60 41 12 30 65 >>> account (l3,6) Number of steps 100 2 ''' def account(M, v): NP = 0 count = 0 breakout = False for w in M: NP = NP + 1 if w== v: count = count + 1 return(count, NP) M = [] run = True entered = input('Please enter a series of integers, split by spaces to add to the list: ').strip().split() for v in entered: inty = int(v) M.append(inty) v = int(input('Please enter a number to be searched for: ')) count, NP = account(M, v) print('Number of steps:', NP) print(count)
true
d75e6cfdd1f826e8cbd9c8c8ca744f38b4c4e8fd
ABradwell/Portfolio
/Language Competency/Python/Basic_Abilities/Matricies/Matrix Trandformation.py
876
4.125
4
##– Exercise 1: Matrix transposed ##– Exercise 2: Sum of an array ##– Exercise 3: Multiplication with arrays #Exercise One #November 6th, 2018 ''' for example use... 1 2 3, 4 5 6 ''' def transform(A): AT = [] collums = len(A) rows = len(A[0]) i = 0 for i in range(0, rows): newrow = [] for j in range(0, collums): newrow.append(A[j][i]) AT.append(newrow) return(AT) rows = int(input('Please enter the number of rows you would like the matrix to have: ')) A = [] index = 0 while index < rows: newrow = input('Please enter the row integer values, seperated by spaces: ').strip().split() for i in range(0, len(newrow)): newrow[i] = int(newrow[i]) A.append(newrow) index = index + 1 AT = transform(A) print(AT)
true
1d0ba82cfb5a76e6b7efd43a3b1266cf658dbca5
JennifferLockwood/python_learning
/python_crash_course/chapter_9/9-13_orderedDict_rewrite.py
860
4.1875
4
from collections import OrderedDict glossary = OrderedDict() glossary['string'] = 'simply a series of characters.' glossary['list'] = 'is a collection of items in a particular order.' glossary['append'] = 'is a method that adds an item to the list.' glossary['tuple'] = 'is an immutable list.' glossary['dictionary'] = 'is a collection of key-value pairs.' glossary['items()'] = 'this method returns a list of key-value pairs.' glossary['sorted()'] = 'function that displays a list in a particular order.' glossary['values()'] = 'method that return a list of values without any keys.' glossary['append()'] = 'this method add a new element to the end of a list.' glossary['reverse()'] = 'reverses the original order of a list permanently.' for word, meaning in glossary.items(): print("\n" + word.upper() + ":" + "\n\t" + meaning.capitalize())
true
9082625477c61bdd518483945261039e3868c49d
JennifferLockwood/python_learning
/python_crash_course/chapter_10/10-8_cats_and_dogs.py
610
4.28125
4
def reading_files(filename): """Count the approximate number of words in a file.""" try: with open(filename) as file_object: lines = file_object.readlines() except FileNotFoundError: msg = "\nSorry, the file " + filename + " does not exist." print(msg) else: # Print the contents of the file to the screen. print("\nThe file " + filename + " has the following names:") for line in lines: print("\t" + line.rstrip()) filenames = ['cats.txt', 'birds.txt', 'dogs.txt'] for filename in filenames: reading_files(filename)
true
f9a57cf4fbffe700b4f0c15111c0e78479f0a263
Jinsaeng/CS-Python
/al4995_hw3_q1.py
382
4.21875
4
weight = float(input("Please enter your weight in kilograms:")); height = float(input("Please enter your height in meters:")); BMI = weight / (height ** 2) if (BMI < 18.5): status = ("Underweight") elif (BMI < 24.9 ): status = ("Normal") elif (BMI <29.9): status = "Overweight" else: status = "Obese" print("Your BMI is", BMI, ". Status:",status);
true
d1c7ab2c0a3a608ff42596a52315fced6f632d00
Jinsaeng/CS-Python
/al4995_hw2_q1b.py
383
4.21875
4
weight = float(input("Please enter your weight in pounds:")); height = float(input("Please enter your height in inches:")); BMI = (weight*0.453592) / ((height*0.0254) ** 2) #conversion using the note in the hw, pounds to kilo and inches to meters #the example BMI is close to the one produced by the program but not exact? #possible due to rounding issues? print(BMI)
true
233187ddede43970dd98411b388c2f2c863fd215
mihirkelkar/languageprojects
/python/double_ended_queue/doubly_linked_list.py
899
4.15625
4
""" Implementation of a doubly linked list parent class """ class Node(object): def __init__(self, value): self.next = None self.prev = None self.value = value class DoublyLinked(object): def __init__(self): self.head = None self.tail = None def addNode(self, value): if self.head == None: self.head = Node(value) self.tail = self.head else: curr = Node(value) self.tail.next = curr curr.prev = self.tail self.tail = self.tail.next def printList(self): curr = self.head while(curr != None): print "The value of the this node is %s" %curr.value print "------------" curr = curr.next def main(): Doubly = DoublyLinked() Doubly.addNode(12) Doubly.addNode(23) Doubly.addNode(34) Doubly.addNode(45) Doubly.addNode(56) Doubly.printList() if __name__ == "__main__": main()
true
95ef2bf61ad082eb270342a36b2f32a2ed5044b7
mihirkelkar/languageprojects
/python/check_anagram.py
692
4.125
4
#!/usr/bin/python def make_map(string): map = {} for ii in string: try: map[ii] += 1 except: map[ii] = 1 return map def check_anagram(string_one, string_two): map_one = make_map(string_one) map_two = make_map(string_two) if map_one == map_two: print "Confirmed anagrams" else: print "Not anagrams" def anagram_check_two(string_one, string_two): string_one = string_one.lower() string_two = string_two.lower() if sorted(string_one) == sorted(string_two): print "Confirmed anagrams by second function" else: print "Not anagrams" def main(): check_anagram('racecar', 'carrac') anagram_check_two('racecar', 'carrac') if __name__ == "__main__": main()
false
851d77deec23c2cf86d338bc831ec253065f056b
mihirkelkar/languageprojects
/python/palindrome.py
280
4.25
4
def check_palindrome(string): if len(string) > 1: if string[0] == string[-1]: check_palindrome(string[1:][:-1]) else: print "Not a palindrome" else: print "Palindrome" text = raw_input("Please enter your text string") check_palindrome(text.lower().replace(" ",""))
true
371272def74700f4b43de365e35cb961abe73b1c
InYourFuture/tree
/tree.py
2,858
4.15625
4
# 循环实现二叉树的前序遍历 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution1: def preorderraversal(self, root): ret, stack = [], [root] while stack: node = stack.pop() if node: ret.append(node.val) # 注意压入栈的顺序,先压入右节点,再压入左节点 stack.append(node.right) stack.append(node.left) return ret # 循环实现二叉树的中序遍历 class Solution2(object): def inorderraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ret,stack=[],[] while stack or root: if root: stack.append(root) root=root.left else: root = stack.pop() ret.append(root.val) root = root.right return ret # 循环实现二叉树的后序遍历 class Solution3: def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ret, stack = [], [] while root or stack: if root: stack.append(root) ret.insert(0, root.val) root = root.right else: node = stack.pop() root = node.left return ret # 递归实现二叉树的前序遍历 class Solution4(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right) # 递归实现二叉树的中序遍历 class Solution5(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return self.preorderTraversal(root.left)+[root.val]+self.preorderTraversal(root.right) # 递归实现二叉树的后序遍历 class Solution6(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return self.preorderTraversal(root.left)+self.preorderTraversal(root.right)+[root.val] # 二叉树层序遍历 class Solution: def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ans, level = [], [root] while any(level): ans.append([node.val for node in level]) level = [kid for n in level for kid in (n.left, n.right) if kid] return ans
false
bfe427c331a3d1982b2aa13cf45707e063356568
mwpnava/Python-Code
/My_own_Python_package/guesser_game/numberGuesserGame.py
2,373
4.28125
4
from random import randrange from .GuesserGame import Guesser class GuessMyNumber(Guesser): """ GuessMyNumber class for calculating the result of arithmetic operations applied to an unknow number given by the player Attributes: numberinMind represents the number a player has in mind at the end of the game magicNumber represents the most important number in this game, it will be used to 'guess' the numberinMind """ def __init__(self, number=0): Guesser.__init__(self,number) self.magicNumber = 2 def play(self): '''Function to play GuessMyNumber Args: None Returns: None ''' self.giveInstructions() self.numberinMind = self.guessingNumber() print('...') print('Your result is {}'.format(int(self.numberinMind))) def giveInstructions(self): '''Function to display directions to play Args: None Returns: None ''' self.magicNumber = self.generateMagicNumber() print('Follow these steps and I will guess your result') input("Press Enter to continue...") print('Let''s play!') print('Think a number greater than 0, do not tell me') input("Press Enter to continue...") print('Multiple your number times 2') input("Press Enter to continue...") print('Add {}'.format(self.magicNumber)) input("Press Enter to continue...") print('Divide your result by 2') input("Press Enter to continue...") print('Last step, subtract to your result the number you initially though') input("Press Enter to continue...") print('...') print('Guessing your result...') def generateMagicNumber(self): '''Function to generate an even random number between 4 and 24 Args: None Returns: Integer: An even number between 4 and 24 ''' n = randrange(4, 24, 2) return int(n) def guessingNumber(self): '''Function to 'guess' the result of arithmetic operations calculated during the GuessMyNumber game. Args: None Returns: Integer: the result of arithmetic operations ''' return self.magicNumber / 2
true
4e97f7e8c80fedb802649a3e1c51c60800a15bee
mwpnava/Python-Code
/missingValue3.py
453
4.25
4
''' Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. Approach 3 ''' def missingValue(arr1,arr2): arr1.sort() arr2.sort() for n1,n2 in zip(arr1,arr2): if n1 != n2: return n1 return arr1[-1] x = missingValue([1,4,3,2,5],[1,5,2,3]) print(x)
true
05f62b6c58e5b56bbcd2a09007aab7c536e1142b
a-benno/randomizer-cli-tool
/randomize/randomizer.py
2,205
4.15625
4
""" ######################################################################################################################## ## ## ## Copyright (C) 2021 Adjust GmbH. All rights reserved. ## ## Created on 06.07.2021 by @author: amr.banna@gmail.com ## ## ## ######################################################################################################################## """ import os import sys import random import argparse from .colors import Colors class RandomizeException(Exception): pass class Randomizer: def __init__(self, randomize=True, start=1, end=10): self.start = start self.end = end self.randomize = randomize # Create an empty list self.numbersList = [] self.build_list() self.randomize_list() def build_list(self): """ This method build a list using start and end values :param: none :return: none """ # Check if start value is smaller than end value if self.start < self.end: # unpack the result self.numbersList.extend(range(self.start, self.end)) # Append the last value self.numbersList.append(self.end) def randomize_list(self): """ This method... 1. randomizes if True 2. print random or sorted list :param: none :return: List """ if self.randomize: print(f'Displaying {Colors.OKBLUE}{Colors.UNDERLINE}randomized{Colors.ENDC} list: ' f'[ startValue={self.start} -- endValue={self.end} ]') random.shuffle(self.numbersList) else: print(f'Displaying {Colors.OKBLUE}{Colors.UNDERLINE}sorted{Colors.ENDC} list: ' f'[ startValue={self.start} -- endValue={self.end} ]') return self.numbersList
false
8362df19e83ad9aa361557272d9abed226133853
vzqz2186/DAnA_Scripts
/Arrays.Lists/vazquez_hw021218_v1.00.py
2,015
4.15625
4
""" Program: Arrays/List Author: Daniel Vazquez Date: 02/10/2018 Assignment: Create array/list with 20 possible elements. Fill with 10 random integers 1 <= n <= 100. Write a function to insert value in middle of list. Due Date: Objective: Write a function to insert value in middle of list.\ (WORKS: v1.00) Execute via: >>python vazquez_hw021218_v1.00.py Sample output: vazquez_hw021218_v1.00.py lista before insertion: [4, 48, 31, 15, 94, 29, 89, 88, 21, 95] Type number to insert to lista: 54 n = 54 lista after insertion: [4, 48, 31, 15, 94, '54', 29, 89, 88, 21, 95] 02/10/2018 10:35 ** Template based on Dr. Nichols program example. ** """ #-----------------------------------------------------------------------------80 import time # Used to get current time and the timer for the program. import random # Used to fill the list with the 10 random numbers. def main(): print("vazquez_hw021218_v1.00.py\n") """ Source for creating the list: https://www.youtube.com/watch?v=G_-ZR-B9STw up until minute 0:50 lista means list in Spanish """ lista = random.sample(range(1, 100), 10) print("lista before insertion: \n",lista,"\n") n = input("Type number to insert to lista: ") print("\nn =",n, "\n") """ This bit splices the list in two at the middle so n can be inserted into the list without the need of using the .append() tool. Source for splicing idea: https://stackoverflow.com/questions/42936941/insert-item-to-list- without-insert-or-append-python/42937056 """ lista = lista[:5] + [n] + lista[5:] print("lista after insertion: \n", lista,"\n") disDate() # Prints date # Source: # https://www.pythoncentral.io/how-to-display-the-date-and-time-using-python/ def disDate(): print(time.strftime('%m/%d/%Y %H:%M')) #Call Main--------------------------------------------------------------------80 main()
true
950737cb22b6aec643d62fe81cbb7ef6c446fb20
frostming/ShowMeTheCode
/q4/count_words.py
532
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 # @Author: Frost Ming # @Email: mianghong@gmail.com # @Date: 2016/3/6 import re def count_words(file): pattern = re.compile(r'\b[a-zA-Z\']+\b') target = open(file, 'r').read() res = pattern.findall(target) print res return len(res) if __name__ == '__main__': file = 'test.txt' words_num = count_words(file) print 'The file "%s" contains %d words in total' %(file, words_num)
false
b7757a06f89cacb51cb96eba0c685b4cf31a9b4a
jdobner/grok-code
/find_smallest_sub2.py
1,537
4.21875
4
def find_substring(str, pattern): """ Given a string and a pattern, find the smallest substring in the given string which has all the characters of the given pattern. :param str: :param pattern: :return: str >>> find_substring("aabdec", 'abc') 'abdec' >>> find_substring("abdbca", 'abc') 'bca' >>> find_substring('adcad','abc') '' """ freq_map = dict.fromkeys(pattern, 0) found_indexes = None window_start = 0 chars_found = 0 for window_end in range(len(str)): nextChar = str[window_end] if nextChar in freq_map: if nextChar in freq_map: freq = freq_map[nextChar] + 1 freq_map[nextChar] = freq if freq == 1: chars_found += 1 while chars_found == len(freq_map): charToRemove = str[window_start] if charToRemove in freq_map: newFreq = freq_map[charToRemove] - 1 freq_map[charToRemove] = newFreq if newFreq == 0: chars_found -= 1 newLen = window_end - window_start + 1 if not found_indexes or found_indexes[0] > newLen: found_indexes = (newLen, window_start, window_end + 1) window_start += 1 if found_indexes: return str[found_indexes[1]:found_indexes[2]] else: return "" if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
true
02c484b6cb30a7187b1b67585dfb0158747db857
jamestonkin/file_storage
/car_storage.py
1,195
4.34375
4
class Car_storage: """ This adds functionality and stores car list makes and models""" def __init__(self): self.car_makes = list() self.car_models = list() def read_car_makes(self): """ Reads car makes from car-makes.txt file """ with open('car-makes.txt', 'r') as makes: for make in makes: self.car_makes.append(make[:-1]) return self.car_makes def read_car_models(self): """ Reads car models from car-models.txt file """ with open('car-models.txt', 'r') as models: for model in models: self.car_models.append(model[:-1]) return self.car_models def create_car_dict(self): """ Combines the makes with models and stores them into a dictionary in model: make format""" car_dict = dict() demo.read_car_makes() demo.read_car_models() for make in self.car_makes: for model in self.car_models: if model[:1] == make[:1]: car_dict[make] = model[2:] print(car_dict) demo = Car_storage() demo.create_car_dict() # demo.read_car_makes() # demo.read_car_models()
true
febdf1ea7d39be0fd144488b75c2f145d07a5677
iumentum666/PythonCrashCourse
/Kapittel 10 - 11/word_count.py
894
4.46875
4
# This is a test of files that are not found. If the file is not present, # This will throw an error. We need to handle that error. # In the previous file, we had an error. Here we will create the file # In this version we will work with several files # So the bulk of the code is put in a function def count_words(filename): """ Count the approximate number of words in a file. """ try: with open(filename, encoding='utf-8') as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: # Count the approximate number of words in the file. words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
true
778b825dd6d9fc525030292508023898238c5fb1
Ryan-Walsh-6/ICS3U-Unit5-05-Python
/mailing_address.py
2,459
4.25
4
#!/usr/bin/env python3 # created by: Ryan Walsh # created on: January 2021 # this program formats a mailing address def format_address(addressee_from_user, street_number_from_user, street_name_from_user, city_from_user, province_from_user, postal_code_from_user, apt_number_from_user=None): # formates mailing address # process if apt_number_from_user is not None: mailing_address = (addressee_from_user + "\n" + apt_number_from_user + "-" + street_number_from_user + " " + street_name_from_user + "\n" + city_from_user + " " + province_from_user + " " + postal_code_from_user) else: mailing_address = (addressee_from_user + "\n" + street_number_from_user + " " + street_name_from_user + "\n" + city_from_user + " " + province_from_user + " " + postal_code_from_user) return mailing_address def main(): # this program formats a mailing address apt_number_from_user = None addressee_from_user = input("Enter your name:") street_number_from_user = input("Enter a street number:") street_name_from_user = input("Enter a street name:") city_from_user = input("Enter a city:") province_from_user = input("Enter a province:") postal_code_from_user = input("Enter a postal code:") live_apt_from_user = input("Do you live in a apartment? (Y/N):") if (live_apt_from_user.upper() == "Y" or live_apt_from_user.upper() == "YES"): apt_number_from_user = input("Enter an apartment number:") print("\n", end="") # call function if apt_number_from_user is not None: address = format_address(addressee_from_user, street_number_from_user, street_name_from_user, city_from_user, province_from_user, postal_code_from_user, apt_number_from_user) else: address = format_address(addressee_from_user, street_number_from_user, street_name_from_user, city_from_user, province_from_user, postal_code_from_user) print(address) if __name__ == "__main__": main()
false
a8fa29813cb4291a39db8d93c46ff0c9c8d5bded
acpfog/python
/6.00.1x_scripts/Week 8/Final Exam/problem3.py
966
4.46875
4
# # dict_invert takes in a dictionary with immutable values and returns the inverse of the dictionary. # The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. # The value for a key in the inverse dictionary is a sorted list of all keys in d that have the same value in d. # # Here are some examples: # If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]} # If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]} # If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]} # def dict_invert ( d ): r = {} for key in d.keys(): if d[key] in r.keys(): t = r[d[key]] t.append( key ) r[d[key]] = sorted(t) else: r.update({ d[key] : [ key, ] }) return r #d = {1:10, 2:20, 3:30} #d = {1:10, 2:20, 3:30, 4:30} d = {4:True, 2:True, 0:True} print dict_invert ( d )
true
ccb58e3365e0bbfc25781cee9c118715a0493513
acpfog/python
/6.00.1x_scripts/Week 2/do_polysum.py
979
4.3125
4
# A regular polygon has 'n' number of sides. Each side has length 's'. # * The area of regular polygon is: (0.25*n*s^2)/tan(pi/n) # * The perimeter of a polygon is: length of the boundary of the polygon # Write a function called 'polysum' that takes 2 arguments, 'n' and 's'. # This function should sum the area and square of the perimeter of the regular polygon. # The function returns the sum, rounded to 4 decimal places. import math def polysum( n, s ): area = ( 0.25 * n * s ** 2 ) / math.tan ( math.pi / n ) perimeter = n * s result = area + perimeter ** 2 result = round( result, 4 ) return result print("A regular polygon has 'n' number of sides. Each side has length 's'.") sides = int(raw_input("Enter number of sides: ")) length = float(raw_input("Enter length of a side: ")) if ( sides < 3 ): print ("A regular polygon cannot have less than 3 sides") else: sides = float(sides) print "The result is %s" % polysum ( sides , length )
true
a7699c41987cbf101e478a6a1623e5bf83221997
paw39/Python---coding-problems
/Problem13.py
1,257
4.34375
4
# This problem was asked by Amazon. # # Run-length encoding is a fast and simple method of encoding strings. # The basic idea is to represent repeated successive characters as a single count and character. # For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". # # Implement run-length encoding and decoding. You can assume the string to be encoded have # no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid. from collections import OrderedDict def encoding(message): count = 1 results = [] for i in range(1, len(message)): if message[i] == message[i-1]: count += 1 else: results.append((count, message[i-1])) count = 1 if i == len(message) - 1: results.append((count, message[i])) for result in results: print(result[0], result[1], sep="", end="") def decoding(message): results = [] for i in range(len(message) - 1): if message[i].isdigit(): results.append(int(message[i]) * str(message[i+1])) else: i += 1 print(*results, sep="") if encoding("AAAABBBCCDAA") == decoding("4A3B2C1D2A"): print("Decoding and encoding works!")
true
261e8bdcd26d998737654e21ddfbc3c5285743d7
zzzzz1797/design_pattern_python
/structural/adapter.py
1,752
4.46875
4
""" 适配器模式(Adapter pattern)是一种结构型设计模式,帮助我们实现两个不兼容接口之间 的兼容。 详细: 如果我们希望把一个老组件用于一个新系统中, 或者把一个新组件用于一个老系统中,不对代码进行任何修改两者就能够通信的情况很少见。 但又并非总是能修改代码,或因为我们无法访问这些代码(例如,组件以外部库的方式提供),或因为修改代码本身就不切实际。 在这些情况下,我们可以编写一个额外的代码层,该代码层包含 让两个接口之间能够通信需要进行的所有修改。这个代码层就叫适配器。 """ from typing import Dict class Computer: def __init__(self, name: str): self.name = name def __str__(self): return self.name def execute(self): return "execute a program" class Human: def __init__(self, name: str): self.name = name def __str__(self): return self.name def speak(self): return "Hello" class Bird: def __init__(self, name: str): self.name = name def __str__(self): return self.name def fly(self): return "fly" class Adapter: def __init__(self, obj: object, adapter_methods: Dict): self.obj = obj self.__dict__.update(adapter_methods) def __str__(self): return str(self.obj) if __name__ == '__main__': objects = [Computer("联想")] bird = Bird("乌鸦") objects.append(Adapter(bird, dict(execute=bird.fly))) human = Human("小明") objects.append(Adapter(human, dict(execute=human.speak))) for o in objects: print(str(o), o.execute())
false
f40e03b6e5812149476681db8ddc24fd22e2063b
HS4MORVEL/Lintcode-solution-in-Python
/004_ugly_number_II.py
1,009
4.25
4
''' Ugly number is a number that only have factors 2, 3 and 5. Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12... Notice Note that 1 is typically treated as an ugly number. Example If n=9, return 10. Challenge O(n log n) or O(n) time. ''' from heapq import heappush, heappop class Solution: """ @param: n: An integer @return: the nth prime number as description. """ def nthUglyNumber(self, n): if n <= 1: return n primes = [2, 3, 5] min_heap = [1] visited = set() for i in range(n): result = heappop(min_heap) for j in range(len(primes)): if result * primes[j] not in visited: heappush(min_heap, result * primes[j]) visited.add(result * primes[j]) return result # def main(): # s = Solution() # print(s.nthUglyNumber(9)) # # # if __name__ == '__main__': # main()
true
4cf2e4c7ad4bdd2a9f80a0aa3de54c4c4f0e4270
fe-sts/curso_em_video
/Python 3 - Mundo 2/4. Repetições em Python (while)/Exercicio 71.py
1,030
4.15625
4
''' Crie um programa que simule o funcionamento de um caixa eletrônico. No inicio, pergunte ao usuario qual será o Valor a ser sacado (numero inteiro) eo programa vai informar quantas cédulas de cada valor serão entregues. Considere que o caixa possui cédulas de 50, 20, 10 e 1 real. ''' print("=======Sistemas Caixa Eletrônico========") valor = int(input('Qual valor deseja sacar? R$').strip()) total = valor cedula = 50 total_cedula = 0 while True: if total >=cedula: total -= cedula total_cedula += 1 else: if total_cedula > 0: print(f'Total de {total_cedula} de {cedula}') if cedula == 50: cedula == 20 elif cedula == 20: cedula == 10 elif cedula == 10: cedula == 1 total_cedula = 0 if total_cedula == 0: break ''' valor = int(input('Qual valor deseja sacar? R$').strip()) if valor // 50 > 1: nota50 = valor // 50 print(f'Notas de 50: {nota50}') '''
false
161200af3074fd3ca367af21f7099b73cef4ebbd
fe-sts/curso_em_video
/Python 3 - Mundo 3/2. Listas/Exercicio 079.py
662
4.15625
4
''' Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente. ''' lista = [] num = 0 continua = '' while True: num = int(input('Digite um valor: ')) if num in lista: print('Você já digitou este valor. Não será adicionado!') else: lista.append(num) continua = input('Quer inserir outro numero? (S/N): ') if continua in "Nn": break print("Os valores em ordem crecente são: {}".format(sorted(lista)))
false
9bc6e1883219e65b6d956f3b624a2d818679d502
fe-sts/curso_em_video
/Python 3 - Mundo 1/1. Tratando dados e fazendo contas/Exercicio 014.py
347
4.15625
4
#Converter graus celsius em farenheit e kelvin celsius = float(input('Entre com a temperatura em graus Celsius (ºC): ')) farenheit = (((9 * celsius) / 5) + 32) print('A temperatura de {0}ºC corresponde a {1} ºF'.format(celsius, farenheit)) kelvin = celsius + 273 print('A temperatura de {0}ºC corresponde a {1} ºK'.format(celsius, kelvin))
false
33fab8dd21256c3f107d68652af5e6cc9216809a
athina-rm/extra_labs
/extralabs_basic/extralabs_basic.py
343
4.15625
4
#Write a Python program display a list of the dates for the 2nd Saturday of every month for a #given year. from datetime import datetime year=int(input("enter the year:")) for j in range(1,13): for i in range (8,15): dates =datetime(year,j,i) if dates.strftime("%w")=="6": print(dates.strftime("%Y-%m-%d"))
true
a6737f8bc4d71bb4d48b3b62c8145626a578007e
athina-rm/extra_labs
/extralabs_basic/module5.py
273
4.375
4
# Find #Find all occurrences of “USA” in given string ignoring the case string=input("Enter the string : ") count=0 count=string.lower().count('usa') if count==0: print('"USA" is not found in the entered string') else: print(f'"USA" is found {count} times')
true
b1020a0e36baa29b31dd14c9f476c80fe095ef95
rob0ak/Hang_Man_Game
/app.py
2,728
4.125
4
import random def set_up_game(word, list_of_letters, blank_list): for letter in word: list_of_letters += letter blank_list += "-" def find_letters(word_list, blank_list, guess, list_of_guesses): count = 0 # Checks the users guess to see if its within the word_list for letter in word_list: if letter == guess: print("correct") blank_list[count] = guess count += 1 if guess not in list_of_guesses: list_of_guesses += guess # Compares list_of_guesses and blank_list to remove letters that don't belong in the list_of_guesses for letter in list_of_guesses: if letter in blank_list: list_of_guesses.remove(user_guess) def check_for_win(word_list, blank_list): if word_list == blank_list: return True else: return False def get_char(): user_input = input("Guess a letter from A-Z: ").upper() allowed_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' while len(user_input) != 1 or user_input not in allowed_chars: user_input = input("Guess a letter from A-Z: ").upper() return user_input def text_animation(wrong_count): animation = ( """ |----- | | | | | |------------ """, """ |----- | | | O | | |------------ """, """ |----- | | | O | | | |------------ """, """ |----- | | | O | |\ | |------------ """, """ |----- | | | O | /|\ | |------------ """, """ |----- | | | O | /|\ | / |------------ """, """ |----- | | | O | /|\ | / \ |------------ """ ) return animation[wrong_count] list_of_words = ["strengthen","Hello","therapeutic","vegetable","chemical"] word_choice = random.choice(list_of_words).upper() letters_in_word = [] blank_word_list = [] wrong_guesses = [] set_up_game(word_choice, letters_in_word, blank_word_list) hang_man = True while hang_man: print(text_animation(len(wrong_guesses))) print(blank_word_list) print(f'Guesses: {wrong_guesses}') user_guess = get_char() find_letters(letters_in_word, blank_word_list, user_guess, wrong_guesses) if check_for_win(letters_in_word, blank_word_list): print("Congratulations you won!!! :)") break if len(wrong_guesses) > 5: print('Sorry you lose! :(') print(text_animation(len(wrong_guesses))) break
true
5c708d99765f36579409eca6fa9d389b0f83b16e
Albertpython/pythonhome
/home14.py
328
4.375
4
'''Write a Python program to find the length of a tuple''' # tup = ("black", "bmw", "red", "ferrary") # res = 0 # for x in tup: # res += 1 # continue # print(res) '''Write a Python program to convert a tuple to a string''' # name = ('A', 'L', 'B', 'E', 'R', 'T') # print(name[0]+name[1]+name[2]+name[3]+name[4]+name[5])
true
db53054877bc9e03ad2feba2efba6c0792857c32
panovitch/code-101
/1_shapes _and_color.py
1,510
4.15625
4
""" Here we introduce the concepts of statements and basic types: strings and integers. WE talk about how a program is a list of senteses exuted from top to bottom, and that some commands can result in a change of state, and some commands are just actions to execute. We also explain what comments are :D """ # here we talk about how all programming languages are made of modules - and we are going to be using a turtle module! # but we also say they shouldnt worry about it for now. import turtle tina=turtle.Turtle() tina.shape("turtle") # this is a statement that makes turtle go forward! tina.forward(90) # this is a statement that makes turtle turn! tina.right(50) # this is a statement that doesnt seem to do anything. # notice how the argument to this command is different - we provide the color name instead of a numerical value # in programming, we usually call text values "strings" tina.color("blue") # however, now see what happens when we draw! tina.forward(20) tina.reset() # lets draw a square! tina.forward(20) tina.right(90) tina.forward(20) tina.right(90) tina.forward(20) tina.right(90) tina.forward(20) tina.reset() # ====== task! ====== # draw a green triangle! # advanced! draw a black circle surrounding the triangle (doesnt have to be centred, unless you are big on geometry) # ====== expected result ====== import turtle tina=turtle.Turtle() tina.shape("turtle") tina.color("green") tina.forward(50) tina.left(120) tina.forward(50) tina.left(120) tina.forward(50)
true
2b4f5355db301ea1a0c2892d384a48dec3c3ecae
Ratheshprabakar/Python-Programs
/maxmin.py
260
4.15625
4
print("Enter the three numbers") a=int(input("Enter the 1st Number")) b=int(input("Enter the 2nd Number\n")) c=int(input("Enter the 3rd Number")) print("The maximum among three numbers",max(a,b,c)) print("The Minimum among three numbers",min(a,b,c))
true
2efe25d4a1589a8ad24e0f9307b616bd419201b0
Ratheshprabakar/Python-Programs
/palindrome.py
258
4.3125
4
#Python program to check whether the number is a palindrome or not def palindrome(a): if(a[::-1]==a): print(a,"is palindrome") else: print(a,"is not a palindrome") def main(): a=input("Enter a number") palindrome(a) if __name__=='__main__': main()
false
4879b0be7e47945416bfe1764495968ae896726c
Ratheshprabakar/Python-Programs
/concatenate and count the no. of characters in a string.py
318
4.3125
4
#Concatnation of two strings #To find the number of characters in the concatenated string first_string=input("Enter the 1st string") second_string=input("Enter the 2nd string") two_string=first_string+second_string print(two_string) c=0 for k in two_string: c+=1 print("No. of charcters in string is",c)
true
e54a34636c36321cb03605dfc39b69f1fab40f89
Ratheshprabakar/Python-Programs
/Multiplication table.py
241
4.28125
4
#To display the multiplication table x=int(input("Enter the table no. you want to get")) y=int(input("Enter the table limit of table")) print("The Multiplication table of",x,"is:") i=1 while i<=y: print(i,"*",x,"=",x*i) i+=1
true
7cfa1c977434c386eb3738bb15c0510c2a587563
adityaapi444/beginner_game
/chocwrap.py
1,004
4.1875
4
#chocolate wrapper puzzle game # price of one chocolate=2 #you will get 1 chocolate by exchanging 3 wrapper #write a program to count how many chocolates can you eat in 'n' money # n is input value for money #ex. #input: money=20 #output: chocolate=14 wrapper remains: 2 money=int(input("ente your money")) c=w=0 if money>0: #chocolate count by exchange with money c+=money//2 w+=c #wrapper count based on chocolate got print('Chocolates:',c,'Wrapper :',w) while(w>=3): #check at least 3 wrapper remaining d=w//3 #chocolate got by xchng with wrapper c+=d #update chocolate count by ading (d) w=w%3+d #update the wrapper count print('Chocolates:',c,'Wrapper :',w) if(w<3): #break if wrapper less than 3 break
true
cc23ecea36f0ad822e62742354427e8e1a9e4495
esterwalf/python-basics
/meh.py
806
4.1875
4
>>> grade = eval(input("Enter your number grade (0-100):")) >>> if grade >= 90: print("You got an A! :)") elif grade >= 80: print("You got a B!") elif grade >= 70: ("You got a C. ") elif grade >= 60: ("You got a D... ") else: print("You got an F :(") >>> rainy = input("How's the weather? Is it raining? (y/n)" ).lower() How's the weather? Is it raining? (y/n)n >>> cold = input("is ti cold outside? (y/n)").lower() is ti cold outside? (y/n)y >>> if(rainy == 'y' and cold == 'y'): print("you'd better wear a raincoat.") elif (rainy == 'y' and cold != 'y'): print("carry an umbrella with you.") elif (rainy != 'y' and cold == 'y'): print("put on a jacket it's cold out") elif (rainy != 'y' and cold != 'y'): print("wear whatever you want, it's beautiful outside!")
false
681b785e3f09a24c8ab87c58aa759a588ce30e51
esterwalf/python-basics
/rosette or polygon.py
1,005
4.5625
5
>>> import turtle >>> t = turtle.Pen() >>> number = int(turtle.numinput("Number of sides or circles", "How many sides or circles in your shape?", 6)) >>> shape = turtle.textinput("which shape do you want?", "Enter 'p' for polygon or 'r' for rosette:") >>> for x in range(number): if shape == 'r': t.circle(100) t.left(95) else: t.forward (150) t.left(360/number) >>> import turtle >>> t = turtle.Pen() >>> sides = int(turtle.numinput("Number of sides", "How many sides in your spiral?")) >>> for m in range(5,75): #our outer spiral loop for polygons and rosettes, from size 5-75 t.left(360/sides + 5) t.width(m//25+1) t.penup() #don't draw lines on spiral t.forward(m*4) #move to next corner t.pendown() #get ready to draw if (m % 2 == 0): for n in range(sides): t.circle(m/3) t.right(360/sides) else: #or, draw a little polygon at each ODD corner of the spiral for m in range(sides): t.forward(m) t.right(360/sides)
true
989eeaea35c3342c9476735031a4ea1ae496c878
elaguerta/Xiangqi
/ElephantPiece.py
1,777
4.21875
4
from Piece import Piece class ElephantPiece(Piece): """Creates ElephantPieces elephant_positions is a class variable, a dictionary of initial positions keyed by player color Two ElephantPieces are created by a call to Player.__init__().""" elephant_positions = { 'red': ['c1', 'g1'], 'black': ['c10', 'g10'] } # legal_ranks is a class variable, a set of ranks that elephants may occupy keyed by player side # Elephants cannot cross the river. legal_ranks = { 'red': {'1','2','3','4','5'}, 'black': {'10','9','8','7','6'} } def __init__(self, side, board, id_num): """ Initializes an Elephant Piece. The side ('red' or 'black'), the Board, and the id_num of this piece are passed as arguments. """ super().__init__(side, board) self._movement = 'diagonal' # Elephants move diagonal self._path_length = 2 # Elephants move 2 points # assign a position from ElephantPiece self._id = id_num # id_num is passed as argument, by Player, and will be 1 or 2 self._pos = ElephantPiece.elephant_positions[side][id_num - 1] # keep track of positions used based on id number def __repr__(self): """Return an informative label for this Piece: ["r" or "b"] + "El" + [id_num for this specific piece]. This is intended to be unique for every piece in a Game """ return self._side[0] + "El" + str(self._id) def is_legal(self, to_pos): """ call Piece.is_legal() with additional restriction that Elephants stay within their legal ranks, i.e. they don't cross the river.""" return super().is_legal(to_pos) and to_pos[1:] in ElephantPiece.legal_ranks[self._side]
true
fef6a53d7ac9e0a73aaf7f8a6168c6b2761c2e90
rambabu519/AlgorithmsNSolutions
/Valid_paranthesis.py
1,533
4.125
4
''' 20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true ''' class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] dt = {'(':')','{':'}','[':']'} # Taken another local storage to avoid iterating through keys for each character in string dtk = dt.keys() for c in s: #If it is open paranthesis then PUSH to stack if c in dt.keys): stack.append(c) #If it is closed paranthesis then pop from stack and compare with current closed paranthesis elif stack: if dt[stack.pop()] != c: return False # This case is when a single open closed paranthesis is present else: return False # if no characters remaining in string and still stack is not empty then given string is not valid if stack: return False else: return True
true
9420188d2d74173dc3b779fe0e6e6a19244712f7
jakovlev-fedor/tms_python_fedor_jakovlev
/02_lesson/10_or_condition.py
681
4.34375
4
"""""" """ Используя or и 2 функции из > < <= >= == != """ """ ------------------------------------ 1. Создайте 3 условия которые будут истинными (True) Пример истинного условия: 7 > 2 or 8 == 3 """ print('#01---------------') print('b' > 'a' or 'one' != 'two') print(3 <= 3 or 8 < 80) print('abc' == 'abc' or 100 >= 99) print() """ ------------------------------------ 2. Создайте 3 условия которые будут ложными (False) """ print('#02---------------') print('b' < 'a' or 'one' == 'two') print(30 <= 3 or 8 > 80) print('abc' != 'abc' or 1 >= 99) print()
false
4c775b35a1f0a0b9ff4484564abcdfadc8273e01
kemar1997/Python_Tutorials
/range_and_while.py
1,213
4.5
4
# creates a for loop that iterates through nine times starting with 0 # the range function is equivalent to creating a list but within the for loop only # Remember: Computers always start counting from 0 # the range function also accepts a range of numbers so the iteration doesn't necessarily, # have to start from exactly 0 # when we have two numbers we have a beginning and an end """ when you use three numbers inside of the range function you have the beginning number then where you want it to end at and lastly the increment value of the range, an example would be range(10, 40, 5) = this is saying that the range starts at 10 and ends at 40 but goes up by 5 for each number so it would give an output of 10, 15, 20, 25, 30, 35 """ # for x in range(10, 40, 5): # print(x) """ A while loop is a special loop that loops as long as the condition is true. So you don't explicitly give a list or a range of numbers. Keeps looping until a condition becomes false. """ x = 2 # keeps outputting the number 5 cause the condition is always true # creating a way to change the variable so that the while knows when to stop is ideal # you never really want an infinite loop while x < 10: print(x) x += 2
true
20781199bff842884181faa97ec7af6d40b239dd
kemar1997/Python_Tutorials
/keyword_arguments.py
991
4.4375
4
# name, action, and item are keywords that hold values either strings or numbers # these keywords can have a default value which can be set in the parentheses below def dumb_sentence(name='Kemar', action='ate', item='tuna.'): print(name, action, item) dumb_sentence() # keyword arguments are taken in the function in the order you first put them in as dumb_sentence('Sally', 'made', 'a banana and strawberry smoothie for breakfast.') # there are gonna be certain times when you just want to pass in the second argument # or maybe pass in the third one and so on. whenever you want to pass in a limited # amount of arguments or pass them in a different order this example shows you how # First off you need to utilize the keywords of the arguments and equal it to something # in the parentheses below, so for instance.. i changed the item argument and set it equal # to "awesome" so when I run it, it returns the sentence "Kemar ate awesome". dumb_sentence(item='awesome', action='is')
true
3835ef1d609ddcff8f545fd8fb3df017d7584923
yuzongjian/pythonLearning
/demo.py
505
4.25
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2018/6/25 23:41 #@Author: yuzongjian #@File : demo.py name = input("Please input your name:") # 打印输出有下面三种方法,最常用的是第一种 print("hello {0}".format(name)) print("hello" + name) print("hello %s" %name) print("1213"+"100") classmates = ['123','1123'] print(classmates.__len__()) for name in classmates: print(name) d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(d['Michael']) print(d.get('Thomas'))
false
076c7e2aa32dcc8aef746adb9c52fd64a742106d
halamsk/checkio
/checkio_solutions/O'Reilly/cipher_crossword.py
2,329
4.3125
4
#!/usr/bin/env checkio --domain=py run cipher-crossword # Everyone has tried solving a crossword puzzle at some point in their lives. We're going to mix things up by adding a cipher to the classic puzzle. A cipher crossword replaces the clues for each entry with clues for each white cell of the grid. These clues are integers ranging from 1 to 26, inclusive. The objective, as any other crossword, is to determine the proper letter for each cell. In a cipher crossword, the 26 numbers serve as a cipher for those letters: cells that share matching numbers are filled with matching letters, and no two numbers stand for the same letter. All resulting entries must be valid words. # # For this task you should solve the cipher crossword. You are given a crossword template as a list of lists (2D array) with numbers (from 0 to 26), where0is a blank cell and other numbers are encrypted letters. You will be given a list of words for the crossword puzzle. You should fill that template with a given word and return the solved crossword as a list of lists with letters. Blank cells are replaced with whitespaces (0 => " "). # # The words are placed in rows and columns with NO diagonals. The crossword contains six words with 5 letters each. These words are placed in a grid. # # # # Input:The Cipher Crossword as a list of lists with integers. Words as a list of strings. # # Output:The solution to the Crossword as a list of lists with letters. # # Precondition: # |crossword| = 5x5 # ∀ x ∈ crossword : 1 ≤ x ≤ 26 # # # END_DESC def checkio(crossword, words): return None if __name__ == '__main__': assert checkio( [ [21, 6, 25, 25, 17], [14, 0, 6, 0, 2], [1, 11, 16, 1, 17], [11, 0, 16, 0, 5], [26, 3, 14, 20, 6] ], ['hello', 'habit', 'lemma', 'ozone', 'bimbo', 'trace']) == [['h', 'e', 'l', 'l', 'o'], ['a', ' ', 'e', ' ', 'z'], ['b', 'i', 'm', 'b', 'o'], ['i', ' ', 'm', ' ', 'n'], ['t', 'r', 'a', 'c', 'e']]
true
70573b9422a6e9b4122522882bf71f6dc902d9a8
No-Life-King/school_stuff
/CSC 131 - Intro to CS/philip_smith.py
1,280
4.21875
4
def mult_tables_one(num): """ Prints a row of the multiplication table of the number 'num' from num*1 to num*10. """ print(num, end="\t") for x in range(1, 11): print(x*num, end='\t') print('\n') def mult_tables_two(start, end): """ Prints the rows of the multiplication table from the specified starting point to the specified ending point. The columns go from 1 to 10. """ print("\t", end='') for x in range(1, 11): print(x, end='\t') print('\n') for y in range(start, end+1): mult_tables_one(y) def is_prime(x): """ Returns true if 'x' is prime, otherwise false. """ if (x == 2): return True for a in range(2, x//2+2): if (x%a==0): return False return True def prime_split(num): """ Accepts an integer input and returns the integer as the sum of two primes. """ if (num <= 2 or num%2==1): return "Improper Number" for x in range(2, num): if (is_prime(x) and is_prime(num-x)): return str(x) + "+" + str(num-x) #mult_tables_one(8) #mult_tables_two(1, 10) #print(is_prime(34)) #print(prime_split(8490))
true
65c80a1aa0437f30ac3b1d8fadffad335da8deb3
zhengyscn/go-slides
/reboot/lesson6/scripts/oop3.py
1,018
4.21875
4
'''程序猿 ''' class Programmer(object): # 局部变量, 所有方法均可以直接访问,无需实例化. monkey = 'Play Computer' # 构造函数 def __init__(self, name, age, height): self.name = name # 可以公开访问 self._age = age # 类的私有属性,是编程规范的约束而非Python语法的越苏 self.__height = height # 对外伪私有属性 # 方法 def get_height(self): return self.__height @classmethod def get_monkey(cls): return cls.monkey @property def get_age(self): return self._age def get_introduction(self): return "My name is {}, I am {} year olds".format(self.name, self._age) # 对象 = 类的实例化 programmer = Programmer('monkey', 12, 180) for i in dir(programmer): print(i) print("--------------") print(Programmer.get_monkey()) print("--------------") print(programmer.get_age) print("--------------") print(programmer.get_introduction())
false
259f11820d403abfd022a319693f15bf0e17156f
nandhinipandurangan11/CIS40_Chapter3_Assignment
/CIS40_Nandhini_Pandurangan_P3_3.py
1,478
4.1875
4
# CIS40: Chapter 3 Assignment: P3.3: Nandhini Pandurangan # This program uses a function to solve problem 3.3 # P3.3: Write a program that reads an integer and prints how many digits # the number has, by checking whether the number >= 10, >= 100 and so on. # (Assume that all integers are less than 10 billion) >> 10 billion >> 10,000, 000, 000 # if the number is negative, multiply it by -1 first # in this context, 0 has 1 digit import math def output_digits(): flag = True num = 0 # input validation while flag: try: num = abs(int(input("Please enter an integer: "))) flag = False except: print("\n ----- Please enter a valid integer ----- \n") # evaluating the input using by checking it against incrementing powers of 10 for i in range (1, 11): digit_counter = math.pow(10, i) if num < digit_counter: print("The number has {0} digit(s)".format(i)) break # calling the function to solve the problem output_digits() ''' Output: Please enter an integer: 1000000 The number has 7 digit(s) ------------------------------------------------- Please enter an integer: hi ----- Please enter a valid integer ----- Please enter an integer: 2jehr3u ----- Please enter a valid integer ----- Please enter an integer: 0 The number has 1 digit(s) ------------------------------------------------- Please enter an integer: 321333980 The number has 9 digit(s) '''
true
c6f2dd94451ab8a2877335b133e1a4b8b0e5c838
betyonfire/gwcexamples
/python/scramble.py
475
4.21875
4
import random print "Welcome to Word Scramble!\n\n" print "Try unscrambling these letters to make an english word.\n" words = ["apple", "banana", "peach", "apricot"] while True: word = random.choice(words) letters = list(word) random.shuffle(letters) scramble = ''.join(letters) print "Scrambled: %s" % scramble guess = raw_input("What word is this? ") if guess == word: print "\nThat's right!\n" else: print "\nNo, the word was %s\n" % word
true
f5be1bc6340012b3b3052e8f6a45df116a1c2d5c
Zahidsqldba07/CodeSignal-solutions-2
/Arcade/Intro/growingPlant.py
1,072
4.53125
5
def growingPlant(upSpeed, downSpeed, desiredHeight): import itertools for i in itertools.count(): if upSpeed >= desiredHeight: return 1 elif i*upSpeed - (i-1)*downSpeed >= desiredHeight: return i '''Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed. Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, your task is to find how many days it'll take for the plant to reach this height. Example For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be growingPlant(upSpeed, downSpeed, desiredHeight) = 10. # Day Night 1 100 90 2 190 180 3 280 270 4 370 360 5 460 450 6 550 540 7 640 630 8 730 720 9 820 810 10 910 900 The plant first reaches a height of 910 on day 10.'''
true
17b85a690befcc87379b5dd3d1f99bf42f77099b
John-Moisha/Hillel_ITP_Python_16_09
/Lesson - 1.py
367
4.28125
4
# num = 5 hi = "Hello, World!" # print (num, type(num)) # print (hi, type (hi)) # print (hi, num) # f_number = 0.6 # print(f_number, type(f_number)) print(2 + 3 * 4) print(2 ** 3) #степень print('2' + '3') print(hi * 3) print(10 / 2) #флоат print(10 // 2) #целое print(11 // 2) print(-11 // 2) print(11 % 2) #остаток от деления
false
a288cdf0c28d593175e59f2e8fdff0a2c26cd98f
OmkarD7/Python-Basics
/22_assignment.py
766
4.28125
4
from functools import reduce #find the sum of squares of all numbers less than 10 numbers = [5, 6, 11, 12] sum = reduce(lambda a,b:a+b, map(lambda a:a*a, filter(lambda n: n <= 10, numbers))) print("sum of squares of all numbers which are less than 10: ",sum) #other way without using lambda def fun1(a, b): return a+b def fun2(c): return c*c def fun3(d): if d<10: return True else: return False sum = reduce(fun1, map(fun2,filter(fun3, numbers))) print("sum of squares of all numbers \ which are less than 10 \ without using lambda function: ", sum) #find the sum of square of all even numbers sum = reduce(lambda n1,n2:n1+n2, map(lambda n:n*n, filter(lambda n: n%2 ==0, numbers))) print("sum of squares of all even numbers: ",sum)
true
709a63ba721c447fad84ff309e45adc0774d29f5
egosk/codewars
/ML - Iris flower - Scikit/Iris flower - ML - basic exercises.py
1,849
4.125
4
# ML exercises from https://www.w3resource.com/machine-learning/scikit-learn/iris/index.php import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import sparse # 1. Write a Python program to load the iris data from a given csv file into a dataframe and print the shape of the # data, type of the data and first 3 rows. data = pd.read_csv("iris.csv", delimiter='\t') print('Data shape: ', data.shape) print('Data type: ', type(data)) print('First 3 rows:\n', data[:3]) #data.head(3) # 2. Write a Python program using Scikit-learn to print the keys, number of rows-columns, feature names and the # description of the Iris data. print('Keys: ', data.keys()) print('Number rows-columns: ', len(data), '-', len(data.columns)) # 3. Write a Python program to get the number of observations, missing values and nan values. print('Number of observations, missing values, Nan values:') print(data.info()) # data.isnull().values.any() # data.isnull().sum() # 4. Write a Python program to create a 2-D array with ones on the diagonal and zeros elsewhere. Now convert the # NumPy array to a SciPy sparse matrix in CSR format. eye = np.eye(5) print(eye) new_eye = sparse.csr_matrix(eye) print('CSR:\n', new_eye) # 5. Write a Python program to get observations of each species (setosa, versicolor, virginica) from iris data. print('Number of samples per specie:') print(data['Species'].value_counts()) # 6. Write a Python program to view basic statistical details like percentile, mean, std etc. of iris data. print('Statistical details:') print(data.describe()) # 7. Write a Python program to access first four columns from a given Dataframe using the index and column labels. new_df = data[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']] print(new_df) new_df_2 = data.iloc[:, :4] print(new_df_2)
true
da877bb35d8f3728d2bf91305c8b30e46819b30c
egosk/codewars
/print directory contents.py
606
4.15625
4
""" This function takes the name of a directory and prints out the paths files within that directory as well as any files contained in contained directories. This function is similar to os.walk. Please don't use os.walk in your answer. We are interested in your ability to work with nested structures. """ import os def print_directory_contents(sPath): for direc in os.listdir(sPath): path = os.path.join(sPath, direc) if os.path.isdir(path): print_directory_contents(path) else: print(path) print_directory_contents('/Users/emila/Desktop/codewars')
true
f0c640ec86971fe2d02ff454be5bee15e7433c01
gbalabanov/Hack_BG_101
/Week1/the_real_deal/substrings_in_string.py
275
4.15625
4
def count_substring(main,sub): count=0 iterator=main.find(sub) while(iterator != -1): count+=1 iterator=main.find(sub,iterator+len(sub)) return count a=(input("Enter string: ")) b=(input("Enter substring: ")) print(count_substring(a,b));
false
088f07aec3fa090ff61b70376bf6e2f169f2241a
Bhumi248/finding_Squareroot_in_python
/squareroot.py
351
4.1875
4
#importing pakage import math print "enter the number u want to squreroot" a=int(input("a:")) #for finding square root there is defuslt function sqrt() which can be accessible by math module print" square_root=",math.sqrt(a) #finding square root without use of math module like:x**.5 print "squareroot using second method" print a**.5
true
ddcec50206d9d5489168c68d234d31cde528742c
abhilash97sharma/python_codes
/Cond_stat.py
359
4.15625
4
is_male = True is_tall = False if is_male: print("You are a male") else: print('You are a female') if is_male and is_tall: print("you are 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 male and tall') else: print("you are not male or not tall")
false
ebdd28443a4eb602e246e5284e300344ce5cd9bf
nihagopala/PythonAssignments
/day3/MaxInThreeNos.py
700
4.5
4
#-----------------------------------------------------------# #Define a function max_of_three() that takes three numbers as # arguments and returns the largest of them. #-----------------------------------------------------------# def Max_Three(a,y,z): max_3 = 0 if a > y: if a > z: max_3 = a else: max_3 = z else: if y > z: max_3 = y else: max_3 = z return max_3 num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) num3 = int(input("Enter the third number:")) print("The largest number of three numbers is", Max_Three(num1, num2, num3))
true
b369116c665c70df576807c8cd7f2a1f7545aae3
nihagopala/PythonAssignments
/day1/10. TranposeOfMatrix.py
374
4.40625
4
#----------------------------------------# #Program to display transpose of a matrix #----------------------------------------# matrix = [[1, 2], [3, 4], [5, 6]] rmatrix = [[0, 0, 0], [0, 0, 0]] for i in range(len(matrix)): for j in range(len(matrix[0])): rmatrix[j][i] = matrix[i][j] for r in rmatrix: print(r)
false
6bcc913eed3ed4d99c607fb12c0400017b247a9e
nihagopala/PythonAssignments
/day1/15. SetOfOperations.py
545
4.53125
5
#----------------------------------------------------------# #Program to print the result of different set of operations #----------------------------------------------------------# set1 = {0, 2, 4, 6, 8}; set2 = {1, 2, 3, 4, 5}; # set union print("Union of set1 and set2 is",set1 | set2) # set intersection print("Intersection of set1 and set2 is",set1 & set2) # set difference print("Difference of set1 and set2 is",set1 - set2) # set symmetric difference print("Symmetric difference of set1 and set2 is",set1 ^ set2)
true
3b52c1a2d001dcaf357f3fc4a6bdfa1745b75ef8
coding5211/python_learning
/learn2.23/ds_seq.py
663
4.125
4
""" shoplist=["apple","banana","mango","sai"] str="jackrose" print("itme 0 is",shoplist[0]) print("item 1 is",shoplist[1]) print("item 2 is",shoplist[2]) print("str 0 is",str[0]) print("itme 1 to 3 is",shoplist[1:2]) print("item 1 end is",shoplist[1:] ) print("item 1 to -1 is",shoplist[1:-1]) print("item start to end is",shoplist[:]) print("str 1 to 3 is",str[1:3]) print("str 1 to end is",str[1:]) print("str 1 to -1 is",str[1:-1]) print("str stard to end is",str[:]) """ bri = set(["rose","jack","tome"]) if "rose" in bri: print("True!") bric = bri.copy() bric.add("china") if bric.issuperset(bri): print("True!") bri.remove("rose") print(bri&bric)
false
8ba142c74997a10c79bf39bcfca62307c8f3eb89
bs4/LearnPythontheHardWay
/ex32drill.py
2,263
4.625
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in items for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range (0, 6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Element was: %d" % i # RANGE PRACTICE # range(start, stop[, step]) # below line is just the stop part of above range() # leaves out the stop integer # oh, also starts at zero, that must be default # below line prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print range(10) # below line prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print range(1, 11) # below line prints: [0, 5, 10, 15, 20, 25] # counts up to 30 by fives, 5 is step print range (0, 30, 5) # below line prints:[0, 6, 12, 18, 24] print range (0, 30, 6) # below line prints: [0, 5, 10, 15, 20, 25, 30] # even tho not a step of 5, still counts all steps of 5 up to stop point 31 print range (0, 31, 5) # below line prints: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] print range (0, -10, -1) # below line prints: TypeError expected integer step, got float #print range (0, 10, .5) # lol, i had to put a # in front of above line or python won't print # after it, haha # STUDY DRILL 2 elementP = [range(0, 6)] for x in elementP: print "This is practice number: %s" % x #...hmm, i think i did this wrong, i think i should be using .append elementG = #...hmm, i don't quite get Study Drill 2, gonna have to come back... # COMMON QUESTION 3 # This took me a sec typing into Python. good practive tho, i created a list # test = [] # then created 2 different variables that were equal to lists of words # then i separately appended (added) each variables list to test # cool
true
5958d7e44c80a44c98a28c64c9451631525f27c5
bs4/LearnPythontheHardWay
/ex06drill.py
2,124
4.125
4
# The below line gives a value for variable x, the value is a string that has a formatter in it x = "There are %d types of people." % 10 # The below line gives a value for the variable "binary", I think doing this is a joke of sorts binary = "binary" # The below line gives a value for the variable "do_not", the value is a contraction of the variable do_not = "don't" # The below line gives variable "y" a value of a string with formatters, there are variables in the string for variable "y" y = "Those who know %s and those who %s." % (binary, do_not) # The below line says to print variable "x" print x # The below line says to print variable "y" print y #The below line inserts variable "x" using %r formatter. %r formatter prints exactly as it is written. ie-(') single quotes are included. #Zed does this to quote the above string, basically "I said "variable x" print "I said: %r." % x # The below line inserts variable y using %s formatter. In this instance, Zed puts (') singles quotes around %s so that the value put into the string looks quoted. # Zed had to use single quote for the below line since he used %s instead of %r. It could read - print "I also said: %r." % y # *Note* using %r in the line above, *POSSIBLY* since there are already (") double quotes, when it pulls "y" using %r, it changes the (") double quotes in "y" to single quotes print "I also said: %r." % y # The below line gives variable "hilarious" a value of "False" hilarious = False # The below line gives variable joke_evaluation a value of a string with a formatter joke_evaluation = "Isn't that joke so funny?! %r" # The below line uses variable "joke_evaluation" as short hand for the string which is it's value...SO instead of writing out the string everytime, you could just use "joke_evaluation", aha! # Notice the % after joke evaluation is just as if you typed -- print "Isn't that joke so fully?! %r" % then added variable "hilarious", aha! print joke_evaluation % hilarious # The below lines are just a play on words or a joke...I think :) w = "This is the left side of..." e = "a string with a right side." print w + e
true
ada0873f48aba1239e05d845c2bb457cda744af4
bs4/LearnPythontheHardWay
/ex18drill.py
1,643
4.5
4
# this one is like your scripts with argv. The below line has a *, it tells python to take all arguments to the function and put them in args as a list def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." # this one is putting a lot of words in a row, just for function def in_a_row(a, b, c, d, e, f, g, h, i, j, k): print "a: %r, b: %r, c: %r, d: %r, e: %r, f: %r, g: %r, h: %r, i: %r, j: %r, k: %r" % (a, b, c, d, e, f, g, h, i, j, k) # this one is...going to attempt raw_input...lol, don't know if this will work. it did, that took some maneuvering tho LOL! def user_def(var1): print "Now we attempt the old raw_input." girl = raw_input("What is your daughters name?") print "Your girl is %r and your son is %r." % (girl, var1) # this one will attempt to read some text in a file. There it is. When I call/run/use the function "filetext" below it will print whatever is in the .txt file...i think lol def filetext(text1): print "Now we attempt to open and read some text from a file." wife = open(text1).read() print wife print_two("Brandon","Smith") print_two_again("Brandon","Smith") print_one("First!") print_none() in_a_row('apple', "bee", "cat", "dog", "eel", "fan", "git", "hat", "ick", "jack", "kick") user_def("Noah") filetext("ex18_sample.txt")
true
83cf84a173ac21a7801299887f5dc1b22cbb6b7e
kavinandha/kavipriya
/prg3.py
274
4.28125
4
ch = input("please enter your own character:") if(ch =='a' or ch =='e' or ch =='i' or ch =='o' or ch =='u' or ch =='A' or ch =='E' or ch =='I' or ch =='O' or ch =='U'): print("the given character",ch,"is a vowel") else: print("the given character",ch,"is a consonant")
false
f30c80da1a3ca8b3c3b34359cc1f7ecb6f0004bc
alinabalgradean/algos
/insertion_sort.py
413
4.25
4
def InsertionSort(lst): """Basic Insertion sort. Args: lst [list]: The list to be sorted. Returns: lst [list]: Sorted list. """ for index in range(1, len(lst)): position = index temp_value = array[lst] while position > 0 and lst[position - 1] > temp_value: lst[position] = lst[position - 1] position -= 1 lst[position] = temp_value return lst
true
8dd255cbd492106fcfde67c9221698df5a85045f
andrewlidong/PythonSyntax
/Top18Questions/11_determineValidNum.py
2,176
4.125
4
''' 11. Determine if the number is valid Given an input string, determine if it makes a valid number or not. For simplicity, assume that white spaces are not present in the input. 4.325 is a valid number. 1.1.1 is NOT a valid number. 222 is a valid number. is NOT a valid number. 0.1 is a valid number. 22.22. is NOT a valid number. Solution: To check if a number is valid, we’ll use the state machine below. The initial state is start, and we’ll process each character to identify the next state. If the state ever ends up at unknown or in a decimal, the number is not valid. Time: O(N) Space: O(1) ''' class STATE: START, INTEGER, DECIMAL, UNKNOWN, AFTER_DECIMAL = range(5) def get_next_state(current_state, ch): if (current_state is STATE.START or current_state is STATE.INTEGER): if ch is '.': return STATE.DECIMAL elif ch >= '0' and ch <= '9': return STATE.INTEGER else: return STATE.UNKNOWN if current_state is STATE.DECIMAL: if ch >= '0' and ch <= '9': return STATE.AFTER_DECIMAL else: return STATE.UNKNOWN if current_state is STATE.AFTER_DECIMAL: if ch >= '0' and ch <= '9': return STATE.AFTER_DECIMAL else: return STATE.UNKNOWN return STATE.UNKNOWN def is_number_valid(s): if not s: return True i = 0 if s[i] is '+' or s[i] is '-': i = i + 1 current_state = STATE.START for c in s[i:]: current_state = get_next_state(current_state, c) if current_state is STATE.UNKNOWN: return False i = i + 1 if current_state is STATE.DECIMAL: return False return True print("Is the number valid 4.325? ", is_number_valid("4.325")) print("Is the number valid 1.1.1? ", is_number_valid("1.1.1")) print("Is the number valid 222? ", is_number_valid("222")) print("Is the number valid 22.? ", is_number_valid("22.")) print("Is the number valid 0.1? ", is_number_valid("0.1")) print("Is the number valid 22.22.? ", is_number_valid("22.22.")) print("Is the number valid 1.? ", is_number_valid("1."))
true
fd8ea6ece01e686a8beef54bc5af3b8dfab593bf
andrewlidong/PythonSyntax
/Top18Questions/3_sumOfTwoValues.py
1,277
4.21875
4
''' 3. Sum of two values Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists and return false if it does not. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. SOLUTION In this solution, you can use the following algorithm to find a pair that add up to the target (say val). Scan the whole array once and store visited elements in a hash set. During scan, for every element e in the array, we check if val - e is present in the hash set i.e. val - e is already visited. If val - e is found in the hash set, it means there is a pair (e, val - e) in array whose sum is equal to the given val. If we have exhausted all elements in the array and didn’t find any such pair, the function will return false. # Time: O(N) # Space: O(N) ''' def find_sum_of_two(A, val): found_values = set() for a in A: if val - a in found_values: return True found_values.add(a) return False v = [5, 7, 1, 2, 8, 4, 3] test = [3, 20, 1, 2, 7] for i in range(len(test)): output = find_sum_of_two(v, test[i]) print("find_sum_of_two(v, " + str(test[i]) + ") =" + str(output))
true
bbcc866382ac2ab1642b31334ee7b53b0d85bac7
mariajosegaete/Python_Projects
/Property_scraper/menu.py
1,020
4.15625
4
from app import houses USER_CHOICE = ''' Please enter one of the following: - 'b' to view all houses - 'n' to view next book in catalogue - 'c' to view 10 cheapest houses - 'q' to quit ----> ''' def print_houses(): '''house_prices = sorted(books, key=lambda x: (x.rating * -1, x.price))[:10]''' for house in houses: print(f'Vivienda de {house.bedrooms}, {house.bathrooms} y {house.surface} por un precio de {house.price}') def print_cheapest_houses(): cheapest_houses = sorted(houses, key=lambda x: x.price)[:10] for house in cheapest_houses: print(house) houses_generator = (x for x in houses) def next_house(): print(next(houses_generator)) choices = { "b": print_houses, "n": next_house, "c": print_cheapest_houses } def menu(): choice = input(USER_CHOICE) while choice != 'q': if choice in choices: choices[choice]() else: print("Please enter a valid option") choice = input(USER_CHOICE) menu()
false
e93d0ce781eb3ff8e8ed1515c3ccc49fb0c47dd9
drewAdorno/Algos
/Python Algos.py
2,200
4.125
4
import math '''Sara is looking to hire an awesome web developer and has received applications from various sources. Her assistant alphabetized them but noticed some duplicates. Given a sorted array, remove duplicate values. Because array elements are already in order, all duplicate values will be grouped together. As with all these array challenges, do this without using any built-in array methods. Second: solve this without using any nested loops.''' def removeDuplicates(arr): newArr=[arr[0]] for i in range(1,len(arr)): if arr[i]!=newArr[len(newArr)-1]: newArr.append(arr[i]) return newArr # Array: Remove Negatives # Implement removeNegatives() that accepts an array, removes negative values, and returns the same array # (not a copy), preserving non-negatives’ order. As always, do not use built-in array functions. # Second: don’t use nested loops. def removeNegatives(arr): x = 0 while x < len(arr): if arr[x] < 0: arr.pop(x) else: x+=1 return arr #1,-2,3,4,5 #  Array: Second-to-Last # Return the second-to-last element of an array. Given [42,true,4,"Kate",7], return "Kate". If array is too short, # return null. def secondToLast(arr): if(len(arr)>=2): return arr[len(arr)-2] else: return None #  Array: Nth-to-Last # Return the element that is N-from-array’s-end. Given ([5,2,3,6,4,9,7],3), return 4. If the array is too short, # return null. #condition_if_true if condition else condition_if_false def nth_to_last(arr, i): return arr[len(arr) - i] if len(arr) >= i else None #  Array: Second-Largest # Return the second-largest element of an array. Given [42,1,4,Math.PI,7], return 7. If the array is too short, # return null. def secondLargest(arr): arr.sort(reverse=True) return arr[1] if len(arr)>=2 else None #  Array: Nth-Largest # Liam has "N" number of Green Belt stickers for excellent Python projects. Given arr and N, return the Nth largest element, where (N-1) elements are larger. Return null if needed. def nth_largest(arr, n): arr.sort(reverse=True) print(arr) return arr[n - 1] if len(arr)>=n else None
true
434a69165a75e71a157fa92cef111911f5b577ec
Erika001/CYPErikaGG
/listas2.py
1,396
4.40625
4
# arreglos # lectura # escritura / Asignacion # actualizacion : inserccion, eliminacion, modificacion # ordenamiento # busqueda # escritura frutas = ["Zapote", "Manzana", "Pera", "Aguacate", "Durazno", "Uva", "Sandia"] # lectura, el selector [indice] print(frutas[2]) # lectura con for # for opcion 1 for indice in range(0,7,1): print(frutas[indice]) print("-----") # for opcion 2 -- por un iterador por each for fr in frutas: print(fr) # asignacion frutas[2]="Melon" print(frutas) # inserccion al final frutas.append("Naranja") print(frutas) print(len(frutas)) frutas.insert(2,"limon") print(frutas) print(len(frutas)) frutas.insert(0,"Mamey") print(frutas) # eliminacion con pop print(frutas.pop()) print(frutas) print(frutas.pop(1)) print(frutas) frutas.append("limon") frutas.append("limon") print(frutas) frutas.remove("limon") print(frutas) #ordenamiento frutas.sort() print(frutas) frutas.reverse() print(frutas) #busqueda print(f"El limon esta e¡n la pos. {frutas.index('limon')}") print(f"El limon esta {frutas.count('limon')} veces en la lista") #concatenar print(frutas) otras_frutas = ["Rambutan", "Mispero", "Liche", "Piraya"] frutas.extend(otras_frutas) print(frutas) #copiar copia = frutas copia.append("Naranja") print(frutas) print(copia) otra_copia = frutas.copy() otra_copia.append("Fresa") otra_copia.append("Fresa") print(frutas) print(otra_copia)
false
3bb64b4540bed752e3f748ce0af80e2657d373e4
carcagi/hpython
/part1/P2_looping.py
1,393
4.25
4
# while loops # Not i++ avaiable i = 0 while i <= 5: # print(i) i += 1 # break and continue i = 0 while i <= 5: i += 1 if i == 2: continue print(i) if i == 4: break # else i = 0 while i <= 5: i += 1 print(i) else: print('Is more than 5') # if you break before else you'll never get there i = 0 while i <= 5: i += 1 if i == 2: continue print(i) if i == 4: break else: print('Is more than 5') """ This is a Docstring, it's ignored, but used for help commands For loops in the traditional form are not encouraged for(i=0; i<5; i++) Instead, Python insists on iterating over items using the for loop """ array = ['h', 'o', 'l', 'b', 'i', 'e'] for element in array: print(element) # run on a string string = "holbie" for char in string: print(char) # range # range generates sequences # range(7) generates 0..6 # range(1, 9) generates 1..8 # range(1, 8, 2) generates 1,3,5,7 for ele in range(3): print(ele) # loop on index of array # len returns len of structure (refer to line 43) for index in range(0, len(array)): print(array[index]) # iterate on dictionaries dict = {'name': 'Pepito perez'} for key, value in dict.items(): print(key + ' is ' + value) # enumerate is used to return a tuple with indexes for index, value in enumerate(array): print(value + ' is in ' + str(index))
true
575617625d8ba29a27eebc80b953330d8e20fb9f
famd92/python
/FizzBuzz.py
565
4.3125
4
###Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz" #### def fizzbuzz(number): if (number%3 ==0 and number%5 ==0): output = 'Fizz Buzz' elif (number%3 ==0): output = 'Fizz' elif (number%5 ==0): output ='Buzz' else: output = number return output if __name__ == '__main__': for i in range(1,101): print(fizzbuzz(i))
true
8857dd572a333f0dd6ea437b128ae88dd03e6d1f
mjanibelli/projetos-iniciantes
/projetos/projeto-gerador-senha/senha_modulo.py
1,208
4.125
4
"""Verifica tamanho da senha e a gera. Atributos: alfabeto (list): Lista que possui as letras do alfabeto. numeros (list): Lista dos números de 0 a 9. chars_especiais (list): Lista de caracteres especiais. """ import random import string alfabeto = list(string.ascii_letters) numeros = list(string.digits) chars_especiais = list(string.punctuation) def verificar_tamanho(tamanho_senha: int) -> bool: if int(tamanho_senha) < 10: return False else: return True def gerar_senha(tamanho_senha: int) -> str: """Gera a senha final. Args: tamanho_senha: tamanho da senha a ser gerada. Retorna: Retorna a senha gerada. """ senha_lista = [] pedaco_senha = tamanho_senha // 3 for _ in range(0, pedaco_senha): letra = random.choice(alfabeto) senha_lista.append(letra) for _ in range(pedaco_senha, (pedaco_senha * 2)): numero = random.choice(numeros) senha_lista.append(numero) for _ in range((pedaco_senha * 2), tamanho_senha): char_espec = random.choice(chars_especiais) senha_lista.append(char_espec) random.shuffle(senha_lista) return "".join(senha_lista)
false
b4ed82079b3ad9ae8e9e2628c7570668215044b3
hamdi3/Python-Practice
/Formatting.py
783
4.53125
5
#Formatting in python str="string" print("this will type a %s" %(str)) # in %() whatever you write will be changed to a string print("this will type a %s , %s" %("hello" ,3)) # you can use %s 2 times and more but you use one %() with a comma for diffrient ones print("this will type a float %1.2f" %(13.4454)) # %1.2f means that the float would have min 1 num before the comma and max 2 after #Recommended Methods: print("this will print {p}".format (p = "something")) #by typing {p} then ending the string with a .format(P=) you can put anything as a value of p in it print("string1 : {p} , string2: {p}, string 3:{p}" .format(p="hi")) #you can p several times print("object1: {a}, object2:{b}, object3:{c}" .format(a="string", b= 4 , c = 2.3)) #you can use more than one variable
true
1693064c8e6f44f9a93e4e15de044f87b1801c16
theCompSciTutor/computerScience
/Algorithms/Sort/MergeSort/merge sort python code.py
968
4.15625
4
# Merge Sort Algorithm def merge_sort(array): print('Separating...', array) if len(array) > 1: mid = len(array) // 2 left_half = array[: mid] right_half = array[mid :] merge_sort(left_half) merge_sort(right_half) i = 0 j = 0 k = 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: array[k] = left_half[i] i += 1 else: array[k] = right_half[j] j += 1 k += 1 while i < len(left_half): array[k] = left_half[i] i += 1 k += 1 while j < len(right_half): array[k] = right_half[j] j += 1 k += 1 print('Merging', array) # testing... test_array = [54, 2, 55, 23, 15, 99, 40, 13, 10, 9] merge_sort(test_array) print(test_array)
false
1be9f869ffea5b124cb98630ed9160ce4680d812
Matheus-Pontes/Curso-Python-3
/aula_11/ex37.py
488
4.1875
4
# CONVERSÃO DE BASE NUMÉRICAS # BINÁRIO, OCTAL E HEXADECIMAL num = int(input("Digite um número inteiro: ")) print('''Escolha a conversão: [0] BINÁRIO [1] OCTAL [2] HEXADECIMAL ''') option = int(input("Faça sua escolha: ")) if option == 0: print("{} em BINÁRIO {}".format(num, bin(num))) elif option == 1: print("{} em OCTAL {}".format(num, oct(num))) elif option == 2: print("{} em HEXADECIMAL {}".format(num, hex(num))) else: print("[ERRROR] TRY AGAIN !!!")
false
8121d98e6b70c5383c066422dc0e6a9cbef9598c
iamSurjya/dailycoding
/Day 21 pandas_add_col.py
769
4.1875
4
import numpy as np import pandas as pd from numpy.random import rand np.random.seed(101) #creating an column pandas DataFrame using an numpy array. print('pandas DataFrame') df=pd.DataFrame(rand(5,4),['A','B','C','D','E'],['W','X','Y','Z']) print(df) #adding new column to an Existing DataFrame df['new']=0.233333 print('\nAdding new column to an Existing DataFrame') print(df) #adding a new column based on 2 existing columns print('\nAdding new column to an Existing DataFrame based on existing columns') df['new']=df['W']+df['Z'] print(df) #droping column from pandas DataFrame print('\nDrop column from DataFrame') df.drop('W',axis=1) print(df) print('\nDrop column from DataFrame with explicitly specify to delete') df.drop('W',axis=1,inplace=True) print(df)
false
1ecebff7cf8703717fc8bc5d19a795161869c53a
iamSurjya/dailycoding
/Day 12_numpy_advance_indexing.py
421
4.1875
4
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) print('Array') print(x) y = x[[0,1,2], [0,1,0]] print('\nFrom each row, a specific element should be selected') #fetching [1 4 5] print(y) print('\nFrom a 4x3 array the corner elements should be selected using advanced indexing') x = np.array( [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) y=x[[0,0,3,3],[0,2,0,2]] #print(y) print(x[[0,3],[1,2]])
true