blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a7ee00fd9f9dac5ec77d96e7b1ab8c1a1dbe1b4f
Rggod/codewars
/is alphanumerical/solution.py
592
4.15625
4
''' In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that. The string has the following conditions to be alphanumeric: At least one character ("" is not valid) Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9 No whitespaces/underscore ''' #Solution def alphanumeric(string): for letter in string: if letter.isalpha(): continue elif letter.isdigit(): continue else: return False return True
true
57813ddd83679b08db0ca6b7d29ad27d25e32252
falondarville/practicePython
/birthday_dictionary/months.py
495
4.5625
5
# In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month. import json from collections import Counter with open("info.json", "r") as f: info = json.load(f) # print the months, which will be added to a list for each in info["birthdays"]: birthday_month = each["month"] print(birthday_month)
true
9b505fd7c9d15fedb84b90c9c8443e791d8a9e61
falondarville/practicePython
/birthday_dictionary/json_bday.py
696
4.46875
4
# In the previous exercise we created a dictionary of famous scientists’ birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program. import json with open("info.json", "r") as f: info = json.load(f) print('Welcome to the birthday dictionary. We know the birthdays of:') for each in info["birthdays"]: print(each["name"]) print('Whose birthday do you want to know?') query = str(input()) print(f'You want to know the birthday of {query}.') for i in info["birthdays"]: if i["name"] == query: birthday = i["birthday"] print(f"{query}'s birthday is on {birthday}")
true
fe8c35b13ecc12fd043023795917be731beda765
alexdistasi/palindrome
/palindrome.py
937
4.375
4
#Author: Alex DiStasi #File: palindrome.py #Purpose: returns True if word is a palindrome and False if it is not def checkPalindrome(inputString): backwardsStr ="" #iterate through inputString backwards for i in range(len(inputString)-1,-1,-1): #create a reversed version of inputString backwardsStr+=(inputString[i]).lower() #iterate through inputString and compare to the reverse string. If an element has a different value, it is not a palindrome for i in range(0, len(inputString)): if inputString[i]!=backwardsStr[i]: return False return True #Ask user for a word to check until user writes 'stop': userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ") while (userWord.lower() != "stop"): print (checkPalindrome(userWord)) userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ")
true
8ebfcdfeba3a5e2a8adc7f70ea6bf85a3e423e68
abrambueno1992/Intro-Python
/src/fileio.py
526
4.40625
4
# Use open to open file "foo.txt" for reading object2 = open('foo.txt', 'r') # Print all the lines in the file # print(object) # Close the file str = object2.read() print(str) object2.close() # Use open to open file "bar.txt" for writing obj_bar = open("bar.txt", 'w') # Use the write() method to write three lines to the file obj_bar.write("Python is a great language.\nYeah its great!!\n New line") # Close the file obj_bar.close() objec_read = open('bar.txt', 'r') str2 = objec_read.read() print(str2) objec_read.close()
true
81cb9114c1fdd16e8b12863531fdaf860080943b
udbhavkanth/Algorithms
/Find closest value in bst.py
1,756
4.21875
4
#in this question we have a bst and #a target value and we have to find # which value in the bst is closest #to our target value. #First we will assign a variable closest #give it some big value like infinity #LOGIC: #we will find the absolute value of (target-closest) And # (target - tree value) # if the absoulte value of target-closest is larger than #absolute value of target - tree value than we will update our #closest and #than compare the tree value to target value if tree value is #greater than target then we only have to traverse left side of #tree if its lower than rigt side of tree #RECURSIVE WAY :- def findClosestValueInBst(tree, target): return findClosestValueInBstHelper(tree,target,float("inf")) def findClosestValueInBstHelper(tree,target,closest): if tree is None: return closest if abs(target-closest) > abs(target-tree.value): closest = tree.value if target < tree.value: return findClosestValueInBstHelper(tree.left,target,closest) elif target > tree.value: return findClosestValueInBstHelper(tree.right, target, closest) else: return closest def findClosestValueInBSt_1(tree, target): return findClosestValueInBstHelper1(tree,target,float("inf")) def findClosestValueInBstHelper1(tree,target,closest): currentNode = tree while currentNode is not None: if abs(target-closest) > abs(target-tree.value): closest = currentNode.value if target < currentNode.value: currentNode = currentNode.left elif target > currentNode.value: currentNode = currentNode.right else: break return closest
true
f132e65fb3e884765ab28eded1b9ededdb09a1b1
artalukd/Data_Mining_Lab
/data-pre-processing/first.py
1,964
4.40625
4
#import statement https://pandas.pydata.org/pandas-docs/stable/dsintro.html import pandas as pd #loading dataset, read more at http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table df = pd.read_csv("iris.data") #by default header is first row #df = pd.read_csv("iris.data", sep=",", names=["petal_length","petal_width","sepal_length", "sepal_width", "category"]) #size of df df.shape() df.head() #df.tail(3) ''' Entire table is a data frame and The basics of indexing are as follows: Operation Syntax Result Select column df[col] Series Select row by label df.loc[label] Series Select row by integer location df.iloc[loc] Series Slice rows df[5:10] DataFrame Select rows by boolean vector df[bool_vec] DataFrame ''' #frame[colname] #df.frame["category"] #Acess particular element :df.loc[row_indexer,column_indexer] #df.loc[123,"petal_length"] #df.loc[123,"petal_length"] = <value of appropriate dtype> #assign always returns a copy of the data, leaving the original DataFrame untouched. #df.assign(sepal_ratio = df['sepal_width'] / df['sepal_length']).head()) ''' Simple python programming constructs: FOR loop: for item in sequence: # commands else: #commands example: word = "Hello" for character in word: print(character) While loop: while (condition): # commands else: # commands example: i = 0 while (i < 3): print("Knock") i += 1 print("Penny!") if-else in python example: option = int(input("")) if (option == 1): result = a + b elif (option == 2): result = a - b elif (option == 3): result = a * b elif (option == 4): result = a / b if option > 0 and option < 5: print("result: %f" % (result)) else: print("Invalid option") print("Thank you for using our calculator.") '''
true
988dab09d39206865788bc0f8d7c3088b551b337
VictoriaEssex/Codio_Assignment_Contact_Book
/part_two.py
2,572
4.46875
4
#Define a main function and introduce the user to the contact book #The function is executed as a statement. def main(): print("Greetings! \nPlease make use of my contact book by completing the following steps: \na) Add three new contacts using the following format: Name : Number \nb) Make sure your contacts have been arranged in alphebetical order.\nc) Delete a contact.\nd) Search for an existing contact.") #Create two variables made up of an array of strings. #The first variable represents the name of an indiviudal and the second is their contact number. Name = ['Victoria', 'Andrew'] print(Name) Number = ['0849993016', '0849879074'] print(Number) #Create a third variable, which is made of an empty array. contacts = [] print(contacts) #Create a loop which will continue to run until it reaches the length of array. #Make use of the append method to add a new contact to the end of the list. for i in range(len(Name)): contacts.append(Name[i] + ' : ' + Number[i]) #concatenation of the two different arrays. #Introduce a while loop to run until the statement is false, where the number of contacts has reached maximum number of 5. while len(contacts) < 5: details = input('Please enter a name and number of an individual to create a new contact.\n') # name : number contacts.append(details) print(contacts) #The sort method is used to arrange all your exisitng contacts into alphabetical order. contacts.sort() print(contacts) #A input is used to inform the user that they can delete a contact by inputting their name. name_to_delete = input('Which contact do you want to delete? ') #Delete a contact based on what it starts with. index_to_delete = 0 for c in range(len(contacts)): contact_name = contacts[c] if contact_name.startswith(name_to_delete): index_to_delete = c #The pop method is used to delete a contact in a specific index position. print('Index to delete: ' + str(index_to_delete)) contacts.pop(index_to_delete) print(contacts) #Search for a contact based on what their name starts with. name_search = input('Search contact: ') for search in range(len(contacts)): contact_name = contacts[search] if contact_name.startswith(name_search): print(contact_name) if __name__ == "__main__": main() #Close main function.
true
757b60fbc021114cc77faa07b7e828a12ea00072
aholyoke/language_experiments
/python/Z_combinator.py
1,285
4.28125
4
# ~*~ encoding: utf-8 ~*~ # Implementation of recursive factorial using only lambdas # There are no recursive calls yet we achieve recursion using fixed point combinators # Y combinator # Unfortunately this will not work with applicative order reduction (Python), so we will use Z combinator # Y := λg.(λx.g (x x)) (λx.g (x x)) Y = (lambda g: (lambda x: g(x(x)))(lambda x: g(x(x)))) # Z combinator # Like the Y combinator except it has an extra "thunking" step to prevent infinite reduction # Z = λf.(λx.f (λv.x x v)) (λx.f (λv.x x v)) Z = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v)))) # The definition of factorial # Takes a continuation r which will be the recursive definition of factorial # λr. λn.(1, if n = 0; else n × (r (n−1))) G = (lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # Z(G) = factorial # The definition of factorial G is passed to Z as argument f # Since Z is a fixed point combinator it satisfies Z(G) = G(Z(G)) # G(Z(G)) tells us that parameter r of G is passed the recursive definition of factorial factorial = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))( lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # demonstration print(factorial(5)) print(factorial(6))
true
40224c5ba455fb7e03e135ff2cb35e94c150e351
lyoness1/Calculator-2
/calculator.py
1,772
4.25
4
""" calculator.py Using our arithmetic.py file from Exercise02, create the calculator program yourself in this file. """ from arithmetic import * def intergerize(str_list): """returns a list of integers from a list of strings""" return map(int, str_list) def read_string(): """reads the input to determine which function in arithmetic.py to use""" token_list = raw_input().split() #original code: # if token_list[0] == "+": # return add(int(token_list[1]), int(token_list[2])) #code for taking multiple inputs - adjusted in arithmetic.py: # if token_list[0] == "+": # return add(map(int, token_list[1:])) if token_list[0] == "+": # code for using reduce() for multiple nums return my_reduce(add, intergerize(token_list[1:])) if token_list[0] == "-": return subtract(int(token_list[1]), int(token_list[2])) if token_list[0] == "*": return multiply(int(token_list[1]), int(token_list[2])) if token_list[0] == "/": return divide(int(token_list[1]), int(token_list[2])) if token_list[0] == "square": return square(int(token_list[1])) if token_list[0] == "cube": return cube(int(token_list[1])) if token_list[0] == "pow": return power(float(token_list[1]), float(token_list[2])) if token_list[0] == "mod": return mod(int(token_list[1]), int(token_list[2])) else: print "invalid operation" #my version of reduce() def my_reduce(func, iterable, initialzer=None): if initialzer is not None: answer = initialzer else: answer = iterable[0] iterable = iterable[1:] for i in iterable: answer = func(answer, i) return answer print "Your answer is {}".format(float(read_string()))
true
1e3e4a200bf8e1db120c6d21463a9186f26b19a5
ashwinimanoj/python-practice
/findSeq.py
805
4.1875
4
'''Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a num- ber, tries to find a sequence of such additions and multiplications that produce that number? For example, the number 13 could be reached by first multiplying by 3 and then adding 5 twice, whereas the number 15 cannot be reached at all.''' def findSeq(start, history, target) -> str: if start == target: return f'({history} = {str(target)})' elif start > target: return 0 else: return findSeq(5 + start, f'({history} + 5)', target)\ or findSeq(3 * start, f'({history} * 3)', target) num = int(input("Enter number: ")) print(findSeq(1, "1", num))
true
1377c3aabb11ba82fd0337b1ef56f0baf0c6de21
yunge008/LintCode
/6.LinkedList/[E]Nth to Last Node in List.py
1,236
4.1875
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null and n = 2, return node whose value is 1. """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: The first node of linked list. @param n: An integer. @return: Nth to last node of a singly linked list. """ def nthToLast(self, head, n): current = head return_node = head for i in xrange(n - 1): current = current.next if current: while current.next: current = current.next return_node = return_node.next return return_node n15 = ListNode(5) n14 = ListNode(6, n15) n13 = ListNode(7, n14) n12 = ListNode(8, n13) n11 = ListNode(9, n12) n19 = ListNode(1) n20 = ListNode(1, n19) n21 = ListNode(1, n20) n22 = ListNode(1, n21) n23 = ListNode(1, n22) s = Solution() head2 = s.nthToLast(n11, 0) while head2: print head2.val, print "->", head2 = head2.next print "None"
true
846b0924cec1a3fd9dfb225af2b22404d1ca5268
yunge008/LintCode
/6.LinkedList/[M]Convert Sorted List to Balanced BST.py
1,053
4.125
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 2 1->2->3 => / \ 1 3 """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class TreeNode(object): def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param head: The first node of linked list. @return: a tree node """ def sortedListToBST(self, head): # write your code here pass n15 = ListNode(5) n14 = ListNode(6, n15) n13 = ListNode(7, n14) n12 = ListNode(8, n13) n11 = ListNode(9, n12) n19 = ListNode(1) n20 = ListNode(1, n19) n21 = ListNode(1, n20) n22 = ListNode(1, n21) n23 = ListNode(1, n22) s = Solution() head2 = s.sortedListToBST(n11) while head2: print head2.val, print "->", head2 = head2.next print "None"
true
896841b93741f2b09cd36c09ff494f1bb6851059
simplifiedlearning/dummy
/function.py
1,739
4.375
4
######################FUNCTIONS#################### #SYNTAX #using def keyword #without parameters def greet(): print("hello") greet() ###add two number #with parameters def add1(x,y): z=x+y print(z) add1(2,3) ####default arguments def add2(b,c,a=12): print(a+b+c) add2(5,5) ####abritriy arguments it is represented by * it is used when the programmer doesnt know how many arguments def read(*n): for x in n: print(x) read(1,2,3) #####RECURSION #Recursion doesnt have loops and do not use loops #takes a lot of space """def fact(n): if(n==1): return 1 else: return n*fact(n-1) r=fact(5) print(r)""" ### #fact(5) n!=1 so else statement is excuted #which gives 5*fact(4) and is not equal to 1 #again 4*fact(3) n!=1 #3*fact(2) n!=1 #2*fact(1) n==1 #soo returns 5*4*3*2*1=120 ##############X RAISED TO Y """x=int(input("enter the value of x")) y=int(input("enter the value of y")) def xtoy():""" ########WAP TO CHECK NUMBER IS PALINDROME OR NOT################# """n=int(input("enter the number")) r=0 m=n while(n>0): d=n%10 r=r*10+d n=n//10 if(m==r): print("its a palindrome") else: print("its not a palindrome")""" ########WAP TO CHECK IF NUMBER IS PRIME OR NOT################### """n=int(int("enter the number to be checked\n")) for i in range(2,n//2): if(n%i)==0: flag=0 break if(flag==0): print("is not prime number") else: print("prime")""" ####REVERSE USING FUNCTIONS """n=int(input("enter the number to be reversed\n")) def rev(n): r=0 while(n>0): d=n%10 r=r*10+d n=n//10 print(r) rev(n)"""
true
c0620531c0aea733e89fda828f42333573c5dcde
naomi-rc/PythonTipsTutorials
/generators.py
638
4.34375
4
# generators are iterators that can only be iterated over once # They are implemented as functions that yield a value (not return) # next(generator) returns the next element in the sequence or StopIteration error # iter(iterable) returns the iterable's iterator def my_generator(x): for i in range(x): yield i print(next(my_generator(10))) print() for i in my_generator(10): print(i) print() try: my_string = "Hi" iterator = iter(my_string) print(next(iterator)) print(next(iterator)) print(next(iterator)) except: print("No more elements left - Threw a StopIteration exception as expected")
true
2f7d869fdcce5a45fd4003d771984b3c871bb921
naomi-rc/PythonTipsTutorials
/enumerate.py
417
4.3125
4
# enumerate : function to loop over something and provide a counter languages = ["java", "javascript", "typescript", "python", "csharp"] for index, language in enumerate(languages): print(index, language) print() starting_index = 1 for index, language in enumerate(languages, starting_index): print(index, language) print() language_tuple = list(enumerate(languages, starting_index)) print(language_tuple)
true
fbc9bbfbb0b4c12eb7af244cdf85a96fb726b2b2
RayGar7/AlgorithmsAndDataStructures
/Python/diagonal_difference.py
581
4.25
4
# Given a square matrix, calculate the absolute difference between the sums of its diagonals. # For example, the square matrix is shown below: # 1 2 3 # 4 5 6 # 9 8 9 # The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is abs(15 - 17) = 2. def diagonalDifference(arr): n = len(arr) left_diagonal_sum = 0 right_diagonal_sum = 0 for i in range(0, n): left_diagonal_sum += arr[i][i] right_diagonal_sum += arr[i][n-1-i] return abs(left_diagonal_sum - right_diagonal_sum)
true
64466b637b49b744d34c0d37cacd212998177a0b
mohitarora3/python003
/sum_of_list.py
376
4.125
4
def sumList(list): ''' objective: to compute sum of list input parameters: list: consist of elemnts of which sum has to be found return value: sum of elements of list ''' #approach: using recursion if list == []: return 0 else: return(list[0]+sumList(list[1:])) print(sumList([1,2,3]))
true
5cecdc3cb4373a598efbe015f6446f84ee950501
lsalgado97/My-Portfolio
/python-learning/basics/guess-a-number.py
2,369
4.34375
4
# This is a code for a game in which the player must guess a random integer between 1 and 100. # It was written in the context of a 2-part python learning course, and is meant to introduce # basic concepts of Python: variables, logic relations, built-in types and functions, if and # for loops, user input, program output (via print()), string formating, importing and random # number generation. import random def run(): print("********************************") print("** Welcome to Guess-a-Number! **") print("********************************") print("") points = 1000 lost_points = 0 total_tries = 0 secret_number = random.randint(1, 100) print("Set the difficulty level") print("(1) Easy (2) Normal (3) Hard") level = int(input("Chosen level: ")) if level == 1: print("You are playing on easy mode") total_tries = 20 elif level == 2: print("You are playing on normal mode") total_tries = 10 else: print("You are playing on hard mode") total_tries = 5 print("") for current_round in range(1, total_tries+1): print("Try {} of {}".format(current_round, total_tries)) # string formatting prior to Python 3.6 guess = int(input("Guess a number between 1 and 100: ")) print("You guessed ", guess) if guess < 1 or guess > 100: print("You must guess between 1 and 100!") continue correct = guess == secret_number higher = guess > secret_number smaller = guess < secret_number if correct: print("You got it right :)") print("You made {} points!".format(points)) break else: if higher: print("You missed! Your guess is higher than the number.") elif smaller: print("You missed! Your guess is smaller than the number.") lost_points = abs(secret_number - guess) points = points - lost_points if current_round == total_tries: print("The secret number was {}, you made {} points".format(secret_number, points)) print("GAME OVER") # This prepares this python file to be executed inside another python program. if __name__ == "__main__": run()
true
4ed6cf981fd362e21ff59c9abbf24035f2e765a3
manovidhi/python-the-hard-way
/ex13.py
650
4.25
4
# we pass the arguments at the runtime here. we import argument to define it here. from sys import argv script, first, second, third = argv #print("this is script", argv.script) print( "The script is called:", script ) # this is what i learnt from hard way print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) age = input("put input your age]") print("your age is", age) # i put it to check input and argv difference #print("this is script", argv[0]) #this is from mihir #print("this is first", argv[1]) #print("this is 2nd", argv[2]) #print("this is third", argv[3])
true
c01b4306131f6fa4bd8a59f7b68ec758e2b16a5c
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter5/wordLength.py
708
4.40625
4
# Average Words Length # wordLength.py # Get a sentence, remove the trailing spaces. # Count the length of a sentence. # Count the number of words. # Calculate the spaces = the number of words - 1 # The average = (the length - the spaces) / the number of words def main(): # Introduction print('The program calculates the average length of words in a sentence.') # Get a sentence sentence = input('Enter a sentence: ').rstrip() # Seperate it into words words = sentence.split() # Calculate the average length of words average = (len(sentence) - (len(words) - 1)) / len(words) # Rule them all print('Your average length of words is {0:.2f}.'.format(average)) main()
true
2afa7c968a716fcca6cdb879880091093f1d22fc
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/sidewalk.py
510
4.125
4
# sidewalk.py from random import randrange def main(): print('This program simulates random walk inside a side walk') n = int(input('How long is the side walk? ')) squares = [0]*n results = doTheWalk(squares) print(squares) def doTheWalk(squares): # Random walk inside the Sidewalk n = len(squares) pos = n // 2 while pos >= 0 and pos < n: squares[pos] += 1 x = randrange(-1,2,2) pos += x return squares if __name__ == '__main__': main()
true
393e027c2e80d8a2ca901ef0104ac59c6887770d
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter3/distance.py
467
4.21875
4
# Distance Calculation # distance.py import math def main(): # Instruction print('The program calculates the distance between two points.') # Get two points x1, y1, x2, y2 = eval(input('Enter two points x1, y1, x2, y2:'\ '(separate by commas) ')) # Calculate the distance distance = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) # Rule them all print('The distance is {0:.2f}.'.format(distance)) main()
true
39c742637396b520ad65097e4a6ac7fc92b16af4
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter8/syracuse.py
447
4.125
4
# syracuse.py # Return a sequence of Syracuse number def main(): # Introduction print('The program returns a sequence of Syracuse number from the first input.') # Get the input x = int(input('Enter your number: ')) # Loop until it comes to 1 while x != 1: if x % 2 == 0: x = x // 2 else: x = 3 * x + 1 print(x, end=', ') if __name__ == '__main__': main()
true
5dd5876363aa431cb73871182406d6da8cef8503
MakeRafa/CS10-poetry_slam
/main.py
1,376
4.25
4
# This is a new python file # random library import random filename = "poem.txt" # gets the filename poem.txt and moves it here def get_file_lines(filename): read_poem = open(filename, 'r') # reads the poem.txt file return read_poem.readlines() def lines_printed_backwards(lines_list): lines_list = lines_list[::-1] #this reverses a line for line in lines_list: #this is used in every function afterwards to pick poem lines print(line) print("*************************************************************************") print("Backwords Poem") lines_printed_backwards(get_file_lines(filename)) # calling the function to be able to print print("*************************************************************************") def lines_printed_random(lines_list): random.shuffle(lines_list) #mixes lines in random order for line in lines_list: print(line) print("Random Line Poem") lines_printed_random(get_file_lines(filename)) print("*************************************************************************") print("Every 5th line Poem") # def lines_printed_custom(): with open('poem.txt') as fifth: for num, line in enumerate(fifth): if num%5 == 0: #chooses every fifth line starting at the first one print(line) print("*************************************************************************")
true
5b4161986fe4af26d3a588ecd8a28347212aecbf
lexboom/Testfinal
/Studentexempt.py
2,121
4.375
4
#Prompt the user to enter the student's average. stu_avg = float(input("Please enter student's average: ")) #Validate the input by using a while loop till the value #entered by the user is out of range 0 and 100. while(stu_avg < 0 or stu_avg > 100): #Display an appropriate message and again, prompt #the user to enter a valid average value. print("Invalid average! Please enter a valid " + "average between 0 - 100:") stu_avg = float(input("Please enter student's " + "average: ")) #Prompt the user to enter the number of days missed. num_days_missed = int(input("Please enter the number " + "of days missed: ")) #Validate the input by using a while loop till the #value entered by the user is less than 0. while(num_days_missed < 0): #Display an appropriate message and again, prompt #the user to enter a valid days value. print("Invalid number of days! Please enter valid " + "number of days greater than 0:") num_days_missed = int(input("Please enter the " + "number of days missed: ")) #If the student's average is at least 96, then the #student is exempt. if(stu_avg >= 96): print("Student is exempt from the final exam. " + "Because, the student's average is at least 96.") #If the student's average is at least 93 and number of #missing days are less than 3, then the student is #exempt. elif(stu_avg >= 93 and num_days_missed < 3): print("Student is exempt from the final exam. " + "Because, the student's average is at least 93 " + "and number of days missed are less than 3.") #If the student's average is at least 90 and there is a #perfect attendence i.e., number of missing days is 0, #then the student is exempt. elif(stu_avg >= 90 and num_days_missed == 0): print("Student is exempt from the final exam. " + "Because, the student's average is at least 90 " + "and student has perfect attendence.") #Otherwise, student is not exempt. else: print("Student is not exempt from the final exam.")
true
3196064e2211728cc382913d1f6c6a0b019364c4
micajank/python_challenges
/exercieses/05factorial.py
365
4.40625
4
# Write a method to compute the `factorial` of a number. # Given a whole number n, a factorial is the product of all # whole numbers from 1 to n. # 5! = 5 * 4 * 3 * 2 * 1 # # Example method call # # factorial(5) # # > 120 # def factorial(num): result = 1 for i in range(result, (num + 1)): result = result * i return result print(factorial(5))
true
2501c35e44be4af82b2d46b48d92125109bb245f
DevYam/Python
/filereading.py
967
4.125
4
f = open("divyam.txt", "rt") # open function will return a file pointer which is stored in f # mode can be rb == read in binary mode, rt == read in text mode # content = f.read(3) # Will read only 3 characters # content = content + "20" # content += "test" # content = f.read(3) # Will read next 3 characters # print(content) # content = f.read() # print(content) # for abc in content: # print(abc) # Will print character by character # For printing line by line we can iterate over the pointer f # for ab in f: # print(ab) # This prints a new line character at the end of each line because that is present in text file # # for ab in f: # print(ab, end=" ") # This prints line by line # print(f.readline(), end=" ") # This space in end=" " makes the second line move a little further # print(f.readline()) # print(f.readline()) content = f.readline() content += f.readline() print(content) # print(f.readlines()) f.close()
true
e7ddc640319e91b422cbee450ecb6ce69c13f534
DevYam/Python
/lec10.py
1,270
4.375
4
# Dictionary is a data structure and is used to store key value pairs as it is done in real life dictionaries d1 = {} print(type(d1)) # class dict ==> Dictionary (key value pair) d2 = {"Divyam": "test", "test2": "testing", "tech": "guru", "dict": {"a": "dicta", "b": "dictb"}} print(d2) print(d2["Divyam"]) # Keys of dictionary are case sensitive # print(d2["0"]) ==> Error print(d2["dict"]["b"]) # queering nested dictionary # The values in the key value pair of dictionary can be a list, tuple, # dictionary etc but the key should be of immutable type . e.g String or numbers # Adding new items to dictionary d2["added"] = "newlyAdded" print(d2) # dictionary keys can be numbers as well d2[420] = "I am 420" print(d2) # deleting key 420 from dictionary del d2[420] print(d2) # Element with key 420 got deleted d3 = d2 # here it will behave as pass by reference del d3["added"] print(d2) # key with element added got deleted from d2 as well # To avoid this we will use copy function d4 = d2.copy() del d4["Divyam"] print(d2) # not deleted from original dictionary print(d4) # Deleted from copy print(d2.get("Divyam")) d2.update({"opem": "sankore"}) print(d2) print(d2.keys()) print(d2.values()) print(d2.items()) # prints full key value pairs
true
69c56249896e306fe80e40ce278505d5be077cc4
minwuh0811/DIT873-DAT346-Techniques-for-Large-Scale-Data
/Programming 1/Solution.py
928
4.25
4
# Scaffold for solution to DIT873 / DAT346, Programming task 1 def fib (limit) : # Given an input limit, calculate the Fibonacci series within [0,limit] # The first two numbers of the series are always equal to 1, # and each consecutive number returned is the sum of the last two numbers. # You should use generators for implementing this function # See https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions # Your code below a,b=0,1 while (a<=limit): yield a a,b=b,a+b def list_fib(limit) : # Construct a list of Fibonacci series list = [] # Your code below num=fib(limit) for nu in num: list.append(nu) return list # The following is called if you execute the script from the commandline # e.g. with python solution.py if __name__ == "__main__": assert list_fib(20) == [0, 1, 1, 2, 3, 5, 8, 13]
true
dd8ec5954a400f30b2af555dc79650c1712437c7
FredC94/MOOC-Python3
/Exercices/20200430 Sudoku Checker.py
1,672
4.15625
4
# Function to check if all the subsquares are valid. It will return: # -1 if a subsquare contains an invalid value # 0 if a subsquare contains repeated values # 1 if the subsquares are valid. def valid_subsquares(grid): for row in range(0, 9, 3): for col in range(0,9,3): temp = [] for r in range(row,row+3): for c in range(col, col+3): if grid[r][c] != 0: temp.append(grid[r][c]) # Checking for invalid values. if any(i < 0 and i > 9 for i in temp): print("Invalid value") return -1 # Checking for repeated values. elif len(temp) != len(set(temp)): return 0 return 1 # Function to check if the board invalid. def valid_board(grid): # Check each row and column. for i in range(9): res1 = valid_row(i, grid) res2 = valid_col(i, grid) # If a row or column is invalid then the board is invalid. if (res1 < 1 or res2 < 1): print("The board is invalid") return # If the rows and columns are valid then check the subsquares. res3 = valid_subsquares(grid) if (res3 < 1): print("The board is invalid") else: print("The board is valid") def print_board(grid): for row in grid: print(row) board = [[1, 4, 7, 0, 0, 0, 0, 0, 3], [2, 5, 0, 0, 0, 1, 0, 0, 0], [3, 0, 9, 0, 0, 0, 0, 0, 0], [0, 8, 0, 0, 2, 0, 0, 0, 4], [0, 0, 0, 4, 1, 0, 0, 2, 0], [9, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 9], [4, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 1, 0, 0, 8, 0, 0, 7]] print_board(board) valid_board(board)
true
b441d9cbcccdfa77932e707e4e9c4490cb0e4c78
Shyonokaze/mysql.py
/mysql.py
2,656
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 12:41:02 2018 @author: pyh """ ''' This class is for creating database and table easier by using pymysql ''' import pymysql class mysql_data: def __init__(self,user_name,password): self.conn=pymysql.connect(host='127.0.0.1', port=3306, user=user_name, passwd=password, charset='utf8') self.cursor=self.conn.cursor() def create_DATABASE(self,db_name): self.cursor.execute('drop database if exists '+db_name) self.cursor.execute('create database '+db_name) self.cursor.execute('use '+db_name) def delete_DATABASE(self,db_name): self.cursor.execute('drop database if exists '+db_name) def use_DATABASE(self,db_name): try: self.cursor.execute('use '+db_name) except: print('use new database failed') def show_DATABASE(self): self.cursor.execute('show databases') return self.cursor.fetchall() def create_TABLE(self,name,content): self.cursor.execute('drop table if exists '+name) self.cursor.execute('create table '+name+'('+content+')') def insert_TABLE(self,table,value): self.cursor.execute('insert into '+table+' values('+value+')') self.conn.commit() def insert_all_TABLE(self,table,value): self.cursor.execute('insert into '+table+' values'+value) self.conn.commit() def delete_TABLE(self,table_name): self.cursor.execute('drop table if exists '+table_name) def show_TABLE(self,table_name): self.cursor.execute('select * from '+table_name) return self.cursor.fetchall() def show_une(self,table_name,require): self.cursor.execute('select U,N,E from '+table_name+' where '+require) U=[] N=[] E=[] data=self.cursor.fetchall() for i in range(len(data)): U.append(data[i][0]) N.append(data[i][1]) E.append(data[i][2]) return U,N,E def close(self): self.cursor.close() self.conn.close() if __name__=='__main__': db=mysql_data('root','622825') db.create_DATABASE('test5') db.use_DATABASE('test1') db.create_TABLE('hh','id int,name varchar(20) charset utf8') db.insert_all_TABLE('hh(id,name)',"(11,'苏打'),(12,'苏打')") db.insert_TABLE('hh(id,name)',"12,'sss'") print(db.show_DATABASE()) print(db.show_TABLE('hh')) db.delete_TABLE('hh') db.close()
true
061b1f29b6c5bc4f2717b07a554e3dd5eac13dab
metehankurucu/data-structures-and-algorithms
/Algorithms/Sorting/BubbleSort/BubbleSort.py
399
4.21875
4
def bubbleSort(arr): n = len(arr) for i in range(n): swapped = False #Every iteration, last i items sorted for j in range(n-i-1): if(arr[j] > arr[j+1]): swapped = True arr[j], arr[j+1] = arr[j+1],arr[j] # One loop without swapping means that array already sorted if(not swapped): break
true
fdc1e38708d2d91acaad06ea6cb73545921f6305
jonathan-pasco-arnone/ICS3U-Unit5-02-Python
/triangle_area.py
1,075
4.15625
4
#!/usr/bin/env python3 # Created by: Jonathan Pasco-Arnone # Created on: December 2020 # This program calculates the area of a triangle def area_of_triangle(base, height): # calculate area area = base * height / 2 print("The area is {}cm²".format(area)) def main(): # This function calls gets inputs, checks them for errors and # calls the specified functions print("") print("This program calculates the area of a triangle") print("") print("Please input the base and height") print("") base_from_user_str = input("Base: ") print("") height_from_user_str = input("Height: ") print("") try: base_from_user = int(base_from_user_str) height_from_user = int(height_from_user_str) except Exception: print("Please enter a real base and height") else: if base_from_user > 0 and height_from_user > 0: area_of_triangle(base_from_user, height_from_user) else: print("Please enter positive values for base and height") if __name__ == "__main__": main()
true
a80210552c4810d0b9d7a1b710934aaddda73b9d
lindagrz/python_course_2021
/day5_classwork.py
2,850
4.46875
4
# 1. Confusion T # he user enters a name. You print user name in reverse (should begin with capital letter) then extra # text: ",a thorough mess is it not ", then the first name of the user name then "?" Example: Enter: Valdis -> # Output: Sidlav, a thorough mess is it not V? # # # 2. Almost Hangman # Write a program to recognize a text symbol The user (first player) enters the text. Only # asterisks instead of letters are output. Assume that there are no numbers, but there may be spaces. The user (i.e. # the other player) enters the symbol. If the letter is found, then the letter is displayed in ALL the appropriate # places, all other letters remain asterisks. # Example: First input: Kartupeļu lauks -> ********* ***** Second input: # a -> *a****** *a*** # # In principle, this is a good start to the game of hangman. # https://en.wikipedia.org/wiki/Hangman_(game) # # # 3. Text conversion # Write a program for text conversion Save user input Print the entered text without changes # Exception: if the words in the input are not .... bad, then the output is not ... bad section must be changed to # is good def confusion(): name = input("Enter a name: ") print(name[::-1].title()) def almost_hangman(): word = input("First player, enter the text: ") # word = "Kartupeļu lauks" guessed = "*" * len(word) letter = " " # to add back the spaces before starting while not letter == "0": for i, c in enumerate(word): if c.lower() in letter.lower(): # guesses are not case sensitive guessed = guessed[:i] + c + guessed[i + 1:] if guessed.find("*") == -1: print("Good job!") break print(guessed) letter = input("Player 2: Guess a letter (or input 0 to give up): ") print(f"The answer was: {word}") def text_conversion(): text = input("Input text: ") # text = "The weather is not bad" # text = "The car is not new" # text = "This cottage cheese is not so bad" # text = "That was pretty bad, was in not my friend?" # text = "This sport is not badminton!" start = "not" tail = "bad" alternative = "good" # # for the Latvian language variation # text = "Laikapstākļi nav slikti" # text = "Mašīna nav jauna" # text = "Kartupeļu biezenis nav nemaz tik slikts" # start = "nav" # tail = "slikt" # alternative = "ir lab" if text.find(start) != -1 and text.find(tail, text.find(start)) != -1 and text.split(tail)[1][0].isspace(): starting_text = text.split(start)[0] ending_text = text.split(tail)[1] print(f"Result: {starting_text}{alternative}{ending_text}") else: print(f"Nothing to convert: {text}") def main(): # confusion() # almost_hangman() text_conversion() if __name__ == "__main__": main()
true
2b7a758e15f6cd2be76e6cf416a07860663da96b
emilybee3/deployed_whiteboarding
/pig_latin.py
1,611
4.3125
4
# Write a function to turn a phrase into Pig Latin. # Your function will be given a phrase (of one or more space-separated words). #There will be no punctuation in it. You should turn this into the same phrase in Pig Latin. # Rules # If the word begins with a consonant (not a, e, i, o, u), #move first letter to end and add "ay" to the end #if word begins with a vowel, add "yay" to the end ########################################################################################### ########################################################################################### #first function will turn words into pig latin #Example input: # "Hello" = "Ellohey" # "Android" = "Androidyay" def pig_latin(word): #create a list of vowels for function to check the first letter #of input word against vowels = ["a", "e", "i", "o", "u"] #first letter = vowel condition if word[0] in vowels: return word + "yay" #first letter = consenent condition else: return word[1:] + word[0] + "ay" #second function will pig latin all the words in a phrase #example input: #"Hello my name is so and so" = "ellohey ymay amenay isyay osay andyay osay" def pig_phrase(phrase): #split phrase into words so that pig_latin can work on each part split_phrase = phrase.split(" ") #create a list to put all the pig latined words: piggied_words = [] #apply pig_latin to each word for word in split_phrase: piggied_words.append(pig_latin(word)) #join list to return full phrase print " ".join(piggied_words) pig_phrase("I am a sentence")
true
55a100f8658a25e2003a382f91c430f993c11a21
findango/Experiments
/linkedlist.py
1,407
4.21875
4
#!/usr/bin/env python import sys class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def __str__(self): return "[Node value=" + str(self.value) + "]" class SortedList: def __init__(self): self.head = None def insert(self, value): prev = None current = self.head while current is not None and current.value <= value: prev = current current = current.next new_node = Node(value, current) if prev is None: self.head = new_node else: prev.next = new_node def find(self, value): node = self.head while (node is not None): if node.value == value: return node node = node.next return None def __str__(self): string = "" node = self.head while (node is not None): string += str(node.value) if node.next is not None: string += ", " node = node.next return string def main(argv=None): list = SortedList() list.insert(5) list.insert(2) list.insert(7) list.insert(9) list.insert(4) list.insert(3) print list print "find 6:", list.find(6) print "find 7:", list.find(7) if __name__ == "__main__": sys.exit(main())
true
cdfbeaf2c417826e26dc3016f9d42916712fb341
luiscarm9/Data-Structures-in-Python
/DataStructures/LinkedList_def/Program.py
627
4.21875
4
from LinkedList_def.LinkedList import LinkedList; LList=LinkedList() #Insert Elements at the start (FATS) LList.insertStart(1) LList.insertStart(2) LList.insertStart(3) LList.insertStart(5) #Insert Elements at the end (SLOW) LList.insertEnd(8) LList.insertEnd(13) LList.insertEnd(21) LList.insertEnd(34) LList.insertEnd(55) LList.insertEnd(89) print("----------------------------------------------------------------------") #Print what is in our list LList.traverseList() print("----------------------------------------------------------------------") #Remove first element (FATS) LList.remove(55) LList.traverseList()
true
d5e2382900b729a2e3392882cf95a006a36e57b9
Priyanshuparihar/make-pull-request
/Python/2021/1stOct_IshaSah.py
835
4.34375
4
'''Take input the value of 'n', upto which you will print. -Print the Fibonacci Series upto n while replacing prime numbers, all multiples of 5 by 0. Sample Input : 12 27 Sample Output : 1 1 0 0 0 8 0 21 34 0 0 144 1 1 0 0 0 8 0 21 34 0 0 144 0 377 0 987 0 2584 4181 0 10946 17711 0 46368 0 121393 196418''' import math n=int(input()) n1=1 n2=1 count=0 def isprime(num): if num<=1: return False if num==2: return True if num>2 and num%2==0: return False x=int(math.sqrt(num)) for i in range(3,x,2): if(num%i==0): return False return True if n==1: print(n1) else: while (count<n): if not isprime(n1) and n1%5!=0: print(n1,end=' ') else: print(0,end=' ') sum=n1+n2 n1=n2 n2=sum count=count+1
true
82a0b63b6b46dbc1b0fb456cf23d1554814c3b04
Priyanshuparihar/make-pull-request
/Python/2021/1stOct_devulapallisai.py
922
4.1875
4
# First take input n # contributed by Sai Prachodhan Devulapalli Thanks for giving me a route # Program to find whether prime or not def primeornot(num): if num<2:return False else: #Just checking from 2,sqrt(n)+1 is enough reduces complexity too for i in range(2,int(pow((num),1/2)+1)): if num%i == 0: return False return True # Program to find multiple of 5 or not def multipleof5(n): if(n % 5 == 0): return True return False n = int(input('Enter the value of n please')) # Check whether n=0 or any invalid if(n <= 0): print('Enter a number greater than 1 because there are no zero terms :(') else: n1 = 0 n2 = 1 count=0 while(count < n): if(multipleof5(n2) or primeornot(n2)): print(0,end=" ") else: print(n2,end=" ") nth = n1 + n2 # update values n1 = n2 n2 = nth count=count+1
true
0319816ef3a65374eaa7dd895288b6eff0f42f4a
Priyanshuparihar/make-pull-request
/Python/2021/2ndOct_RolloCasanova.py
1,276
4.3125
4
# Function to print given string in the zigzag form in `k` rows def printZigZag(s, k): # Creates an len(s) x k matrix arrays = [[' ' for x in range (len(s))] for y in range (k)] # Indicates if we are going downside the zigzag down = True # Initialize the row and column to zero col, row = 0, 0 # Iterate over all word's letters for l in s[:]: arrays[row][col] = l # col always increases col = col + 1 # If going down, increase row if down: row = row + 1 # Already at the bottom? let's go up if row == k: row = k-2 down = False # If going up, decrease row else: row = row - 1 # Already at top, let's go down if row == -1: row = 1 down = True # Iterate over all k arrays in matrix for arr in arrays[:]: # Set str to empty string str = "" # Iterate over each letter in array for l in arr[:]: # Concatenate letters on array str = str + l # Print str print(str) # if __name__ == '__main__': # s = 'THISZIGZAGPROBLEMISAWESOME' # k = 3 # printZigZag(s, k)
true
5a840100907d0fe49012b75d8707ee142ba80738
Priyanshuparihar/make-pull-request
/Python/2021/2ndOct_Candida18.py
703
4.125
4
rows = int(input(" Enter the no. of rows : ")) cols = int(input(" Enter the no. of columns : ")) print("\n") for i in range(1,rows+1): print(" "*(i-1),end=" ") a = i while a<=cols: print(a , end="") b = a % (rows-1) if(b==0): b=(rows-1) a+=(rows-b)*2 print(" "*((rows-b)*2-1),end=" ") print("\n") """ Output: Enter the no. of rows : 7 Enter the no. of columns : 16 1 13 2 12 14 3 11 15 4 10 16 5 9 6 8 7 """
true
d2d56f7fc126004e97d41c53f9b3704d61978473
alexsmartens/algorithms
/stack.py
1,644
4.21875
4
# This stack.py implementation follows idea from CLRS, Chapter 10.2 class Stack: def __init__(self): self.items = [] self.top = 0 self.debug = True def is_empty(self): return self.top == 0 def size(self): return self.top def peek(self): if self.top > 0: return self.items[self.top - 1] else: return None def push(self, new_item): self.items.append(new_item) self.top += 1 if self.debug: self.print() def pop(self): if self.is_empty(): print("Attention: stack underflow") return None else: new_item = self.items[self.top - 1] self.items = self.items[:self.top - 1] # the last list item is not included self.top -= 1 if self.debug: self.print() return new_item def print(self): print(self.items) # Running simple examples myStack = Stack() print("is_empty: " + str(myStack.is_empty())) print("top: " + str(myStack.top)) myStack.push(15) myStack.push(6) myStack.push(2) myStack.push(9) print("is_empty: " + str(myStack.is_empty())) print("top: " + str(myStack.top)) myStack.push(17) myStack.push(3) print("size " + str(myStack.size())) print("peek " + str(myStack.peek())) myStack.pop() print("top: " + str(myStack.top)) myStack.pop() myStack.pop() myStack.pop() myStack.pop() print("top: " + str(myStack.top)) myStack.pop() print("top: " + str(myStack.top)) myStack.pop() myStack.pop()
true
58fa55150c3bc3735f3f63be5193eb2433eddd28
Catboi347/python_homework
/fridayhomework/homework78.py
211
4.1875
4
import re string = input("Type in a string ") if re.search("[a-z]", string): print ("This is a string ") elif re.search("[A-Z]", string): print ("This is a string") else: print ("This is an integer")
true
5e0bf04f50e383157a0f4d476373353342f3385e
karngyan/Data-Structures-Algorithms
/Tree/BinaryTree/Bottom_View.py
1,305
4.125
4
# Print Nodes in Bottom View of Binary Tree from collections import deque class Node: def __init__(self, data): self.data = data self.left = None self.right = None def bottom_view(root): if root is None: return # make an empty queue for BFS q = deque() # dict to store bottom view keys bottomview = {} # append root in the queue with horizontal distance as 0 q.append((root, 0)) while q: # get the element and horizontal distance elem, hd = q.popleft() # update the last seen hd element bottomview[hd] = elem.data # add left and right child in the queue with hd - 1 and hd + 1 if elem.left is not None: q.append((elem.left, hd - 1)) if elem.right is not None: q.append((elem.right, hd + 1)) # return the bottomview return bottomview if __name__ == '__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) bottomview = bottom_view(root) for i in sorted(bottomview): print(bottomview[i], end=' ')
true
487d70507adea1986e7c35271ced0d4f702f1897
karngyan/Data-Structures-Algorithms
/String_or_Array/Searching/Linear_Search.py
480
4.125
4
# Function for linear search # inputs: array of elements 'arr', key to be searched 'x' # returns: index of first occurrence of x in arr def linear_search(arr, x): # traverse the array for i in range(0, len(arr)): # if element at current index is same as x # return the index value if arr[i] == x: return i # if the element is not found in the array return -1 return -1 arr = [3, 2, 1, 5, 6, 4] print(linear_search(arr, 1))
true
d87e3ccfe1dcebc2ba0e3d030b0704c68b52d684
dominiquecuevas/dominiquecuevas
/05-trees-and-graphs/second-largest.py
1,720
4.21875
4
class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right ''' go right if has a right attr, copy value of previous Node if current has a left, reassign value and return it else go left and reassign value to current and return ''' def find_largest(node): if node.right: return find_largest(node.right) return node.value def second_largest(node): ''' >>> root = BinaryTreeNode(5) >>> ten = root.insert_right(10) >>> seven = ten.insert_left(7) >>> eight = seven.insert_right(8) >>> six = seven.insert_left(6) >>> find_largest(root) 10 >>> second_largest(root) 8 5 10 7 6 8 >>> root = BinaryTreeNode(5) >>> three = root.insert_left(3) >>> two = three.insert_left(2) >>> four = three.insert_right(4) >>> find_largest(root) 5 >>> second_largest(root) 4 5 3 2 4 ''' if node.left and not node.right: return find_largest(node.left) if node.right and not node.right.left and not node.right.right: return node.value return second_largest(node.right) # time complexity is O(h) and space is O(h) # cut down to O(n) space if didn't use recursion if __name__ == '__main__': import doctest if doctest.testmod(verbose=True).failed == 0: print('ALL TESTS PASSED')
true
ad6fc102c4ad03ca32dc29b84cdffb1d6108147e
VitaliiUr/wiki
/wiki
2,978
4.15625
4
#!/usr/bin/env python3 import wikipedia as wiki import re import sys import argparse def get_random_title(): """ Find a random article on the Wikipadia and suggests it to user. Returns ------- str title of article """ title = wiki.random() print("Random article's title:") print(title) ans = input( "Do you want to read it?\n (Press any key if yes or \"n\" if you want to see next suggestion)\n\ Press \"q\" to quit") if ans in ("n", "next"): return get_random_title() elif ans == "q": print("sorry for that") sys.exit(0) else: return title def search_title(search): """ Looks for the article by title Parameters ---------- search : str query for the search Returns ------- str title of the article """ titles = wiki.search(search) print(">>> We found such articles:\n") print(*[f"\"{t}\","for t in titles[:5]], "\n") for title in titles: print(">>> Did you mean \"{}\"?\n Press any key if yes or \"n\"".format(title), "if you want to see next suggestion") ans = input("Press \"q\" to quit") if ans in ("n", "next"): continue elif ans == "q": print(">>> Sorry for that. Bye") sys.exit(0) else: return title def split_paragraphs(text): # Remove bad symbols text = re.sub(r"\s{2,}", " ", text.strip()) text = re.sub(r"\n{2,}", "\n", text) # Split article to the paragraphs pat = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s*?)(?:[^=]+)(?:\s*?)(?:={2,}))") paragraphs = pat.split(text) # Get titles of the paragraphs pat2 = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s?)([^=]+)(?:\s?)(?:={2,}))") titles = list(map(lambda x: x.strip(), ["Summary"] + pat2.findall(text))) # Create a dictionary of the paragraphs and return it result = dict(zip(titles, paragraphs)) if "References" in result: del result["References"] return result if __name__ == "__main__": # Get arguments parser = argparse.ArgumentParser() parser.add_argument("search", type=str, nargs='?', help="search wiki article by title") args = parser.parse_args() if args.search: name = search_title(args.search) # search article by title else: name = get_random_title() # get random article if name: print(">>> Article is loading. Please, wait...") page = wiki.page(name) else: print(">>> Please, try again") sys.exit(0) paragraphs = split_paragraphs(page.content) print("\n===== ", name, " =====") for title in paragraphs: print("\n") print("=== ", title, " ===") print(paragraphs[title]) ans = input( "Press any key to proceed, \"q\" to quit") if ans == "q": sys.exit(0)
true
80d0e021194a67ff06851523210bc9f7ca635833
jimboowens/python-practice
/dictionaries.py
1,131
4.25
4
# this is a thing about dictionaries; they seem very useful for lists and changing values. # Dictionaries are just like lists, but instead of numbered indices they have english indices. # it's like a key greg = [ "Greg", "Male", "Tall", "Developer", ] # This is not intuitive, and the placeholders give no indication as to what they represent # Key:value pair greg = { "name": "Greg", "gender": "Male", "height": "Tall", "job": "Developer", } # make a new dictionary zombie = {}#dictionary zombies = []#list zombie['weapon'] = "fist" zombie['health'] = 100 zombie['speed'] = 10 print zombie # zombie stores the items it comprises in random order. print zombie ['weapon'] for key, value in zombie.items():#key is basically an i, and I don't get how it iterated because both change...? print "zombie has a key of %s with a value of %s" % (key, value) zombies.append({ 'name': "Hank", 'weapon': "baseball bat", 'speed': 10 }) zombies.append({ 'name': "Willy", 'weapon': "axe", 'speed': 3, 'victims': ['squirrel', 'rabbit', 'Hank'] }) print zombies[1]['victims'][1]
true
735222b563750bceca379969e5cff58224ddf83e
nlin24/python_algorithms
/BinaryTrees.py
1,982
4.375
4
class BinaryTree: """ A simple binary tree node """ def __init__(self,nodeName =""): self.key = nodeName self.rightChild = None self.leftChild = None def insertLeft(self,newNode): """ Insert a left child to the current node object Append the left child of the current node to the new node's left child """ if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): """ Insert a right child to the current node object Append the right child of the current node to the new node's right child """ if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): """ Return the right child of the root node """ return self.rightChild def getLeftChild(self): """ Return the left child of the root node """ return self.leftChild def setRootValue(self,newValue): """ Set the value of the root node """ self.key = newValue def getRootValue(self): """ Return the key value of the root node """ return self.key if __name__ == "__main__": r = BinaryTree('a') print(r.getRootValue()) #a print(r.getLeftChild()) #None r.insertLeft('b') print(r.getLeftChild()) #binary tree object print(r.getLeftChild().getRootValue()) #b r.insertRight('c') print(r.getRightChild()) #binary tree object print(r.getRightChild().getRootValue()) #c r.getRightChild().setRootValue('hello') print(r.getRightChild().getRootValue()) #hello
true
d22dd3d84f34487598c716f13af578c3d2752bc4
aduV24/python_tasks
/Task 19/example.py
1,720
4.53125
5
#************* HELP ***************** #REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LEAVE A #COMMENT FOR YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL. #************************************ # =========== Write Method =========== # You can use the write() method in order to write to a file. # The syntax for this method is as follows: # file.write("string") - writes "string" to the file # ************ Example 1 ************ # Before you can write to a file you need to open it. # You open a file using Python's built-in open() function which creates a file called output.txt (it doesn't exist yet) in write mode. # Python will create this file in the directory/folder that our program is automatically. ofile = open('output.txt', 'w') # We ask the user for their name. When they enter it, it is stored as a String in the variable name. name = input("Enter your name: ") # We use the write method to write the contents of the variable name to the text file, which is represented by the object ofile. # Remember, you will learn more about objects later but for now, think of an object as similar to a real-world object # such as a book, apple or car that can be distinctly identified. ofile.write(name+"\n") # You must run this Python file for the file 'output.txt' to be created with the output from this program in it. ofile.write("My name is on the line above in this text file.") # When we write to the file again, the current contents of the file will not be overwritten. # The new string will be written on the second line of the text file. ofile.close() # Don't forget to close the file! # ****************** END OF EXAMPLE CODE ********************* #
true
473237b007ea679c7b55f3c4c7b5895bdf150ae5
aduV24/python_tasks
/Task 11/task2.py
880
4.34375
4
shape = input("Enter the shape of the builing(square,rectangular or round):\n") if shape == "square": length = float(input("Enter the length of one side:\n")) area = round(length**2,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "rectangle": length = float(input("Enter the length of one side:\n")) width =float(input("Enter the width:\n")) area = round(length*width,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "round": import math radius = float(input("Enter the radius:\n")) area = round((math.pi)*(radius**2),2) print(f"The area that will be taken up by the building is {area}sqm")
true
3427a7d78131b4d26b633aa5f70e2dc7a7dab748
aduV24/python_tasks
/Task 17/disappear.py
564
4.78125
5
# This program asks the user to input a string, and characters they wish to # strip, It then displays the string without those characters. string = input("Enter a string:\n") char = input("Enter characters you'd like to make disappear separated by a +\ comma:\n") # Split the characters given into a list and loop through them for x in char.split(","): # Check if character is in string and replace it if x in string: string = string.replace(x, "") else: print(f"'{x}' is not in the string given") print("\n" + string)
true
55d2392b17d505045d5d80d209dc5635c47657f6
aduV24/python_tasks
/Task 17/separation.py
298
4.4375
4
# This program asks the user for a sentence and then displays # each character of that senetence on a new line string = input("Enter a sentence:\n") # split string into a list of words words = string.split(" ") # Iterate thorugh the string and print each word for word in words: print(word)
true
40df8c8aa7efb4fc8707f712b94971bae08dacea
aduV24/python_tasks
/Task 21/john.py
344
4.34375
4
# This program continues to ask the user to enter a name until they enter "John" # The program then displays all the incorrect names that was put in wrong_inputs = [] name = input("Please input a name:\n") while name != "John": wrong_inputs.append(name) name = input("Please input a name:\n") print(f"Incorrect names:{wrong_inputs}")
true
aa382979b4f5bc4a8b7e461725f59a802ffe3a4e
aduV24/python_tasks
/Task 14/task1.py
340
4.59375
5
# This python program asks the user to input a number and then displays the # times table for that number using a for loop num = int(input("Please Enter a number: ")) print(f"The {num} times table is:") # Initialise a loop and print out a times table pattern using the variable for x in range(1,13): print(f"{num} x {x} = {num * x}")
true
ab8491166133deadd98d2bbbbb40775f95c7091b
aduV24/python_tasks
/Task 24/Example Programs/code_word.py
876
4.28125
4
# Imagine we have a long list of codewords and each codeword triggers a specific function to be called. # For example, we have the codewords 'go' which when seen calls the function handleGo, and another codeword 'ok' which when seen calls the function handleOk. # We can use a dictionary to encode this. def handleGo(x): return "Handling a go! " + x def handleOk(x): return "Handling an ok!" + x # This is dictionary: codewords = { 'go': handleGo, # The KEY here is 'go' and the VALUE it maps to is handleGo (Which is a function!). 'ok': handleOk, } # This dictionary pairs STRINGS (codewords) to FUNCTIONS. # Now, we see a codeword given to us: codeword = "go" # We can handle it as follows: if codeword in codewords: answer = codewords[codeword]("Argument") print(answer) else: print("I don't know that codeword.")
true
ee04a317415c9a0c9481f712e8219c92fb719ce0
hackettccp/CIS106
/SourceCode/Module2/formatting_numbers.py
1,640
4.65625
5
""" Demonstrates how numbers can be displayed with formatting. The format function always returns a string-type, regardless of if the value to be formatted is a float or int. """ #Example 1 - Formatting floats amount_due = 15000.0 monthly_payment = amount_due / 12 print("The monthly payment is $", monthly_payment) #Formatted to two decimal places print("The monthly payment is $", format(monthly_payment, ".2f")) #Formatted to two decimal places and includes commas print("The monthly payment is $", format(monthly_payment, ",.2f")) print("The monthly payment is $", format(monthly_payment, ',.2f'), sep="") #********************************# print() #Example 2 - Formatting ints """ weekly_pay = 1300 annual_salary = weekly_pay * 52 print("The annual salary is $", annual_salary) print("The annual salary is $", format(annual_salary, ",d")) print("The annual salary is $", format(annual_salary, ",d"), sep="") """ #********************************# print() #Example 3 - Scientific Notation """ distance = 567.465234 print("The distance is", distance) print("The distance is", format(distance, ".5e")) """ #********************************# print() #Example 4 - Formatting floats # This example displays the following # floating-point numbers in a column # with their decimal points aligned. """ num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 # Display each number in a field of 7 spaces # with 2 decimal places. print(format(num1, '7.2f')) print(format(num2, '7.2f')) print(format(num3, '7.2f')) print(format(num4, '7.2f')) print(format(num5, '7.2f')) print(format(num6, '7.2f')) """
true
3d2c8b1c05332e245a7d3965762b2a746d6e5c3d
hackettccp/CIS106
/SourceCode/Module4/loopandahalf.py
899
4.21875
4
""" Demonstrates a Loop and a Half """ #Creates an infinite while loop while True : #Declares a variable named entry and prompts the user to #enter the value z. Assigns the user's input to the entry variable. entry = input("Enter the value z: ") #If the value of the entry variable is "z", break from the loop if entry == "z" : break #Prints the text "Thank you!" print("Thank you!") #********************************# print() """ #Creates an infinite while loop while True: #Declares a variable named userNum and prompt the user #to enter a number between 1 and 10. #Assigns the user's input to the user_number variable. user_number = int(input("Enter a number between 1 and 10: ")) #If the value of the userNumber variable is correct, break from the loop if user_number >= 1 and user_number <= 10 : break #Prints the text "Thank you!" print("Thank you!") """
true
824f4f86eaef9c87c082c0f471cb7a68cc72a44f
hackettccp/CIS106
/SourceCode/Module2/converting_floats_and_ints.py
1,055
4.71875
5
""" Demonstrates converting ints and floats. Uncomment the other section to demonstrate the conversion of float data to int data. """ #Example 1 - Converting int data to float data #Declares a variable named int_value1 and assigns it the value 35 int_value1 = 35 #Declares a variable named float_value1 and assigns it #int_value1 returned as a float float_value1 = float(int_value1) #Prints the value of int_value1. The float function did not change #the variable, its value, or its type. print(int_value1) #Prints the value of float_value1. print(float_value1) #********************************# print() #Example 2 - Converting float data to int data """ #Declares a variable named float_value2 and assigns it the value 23.8 float_value2 = 23.8 #Declares a variable named int_value2 and assigns it #float_value2 returned as an int int_value2 = int(float_value2) #Prints the value of float_value2. The int function did not change #the variable, its value, or its type. print(float_value2) #Prints the value of int_value2 print(int_value2) """
true
98868a37e12fc16d5a1e0d49cb8e076a5ffb107d
hackettccp/CIS106
/SourceCode/Module10/button_demo.py
866
4.15625
4
#Imports the tkinter module import tkinter #Imports the tkinter.messagebox module import tkinter.messagebox #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates button that belongs to test_window that #calls the showdialog function when clicked. test_button = tkinter.Button(test_window, text="Click Me!", command=showdialog) #Packs the button onto the window test_button.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Function that displays a dialog box when it is called. def showdialog() : tkinter.messagebox.showinfo("Great Job!", "You pressed the button.") #Calls the main function/starts the program main()
true
1af15c312f75e507b4acb77abc76b25ff8022318
hackettccp/CIS106
/SourceCode/Module5/returning_data1.py
815
4.15625
4
""" Demonstrates returning values from functions """ def main() : #Prompts the user to enter a number. Assigns the user's #input (as an int) to a variable named num1 num1 = int(input("Enter a number: ")) #Prompts the user to enter another number. Assigns the user's #input (as an int) to a variable named num2 num2 = int(input("Enter another number: ")) #Passes the num1 and num2 variables as arguments to the printsum #function. Assign the value returned to a variable called total total = printsum(num1, num2) #Prints the value of total print("The total is", total) #A function called printsum that accepts two arguments. #The function adds the arguments together and returns the result. def printsum(x, y) : #Returns the sum of x and y return x + y #Calls main function main()
true
c359aae7e1cd194eedb023b580f34e42b7663c27
hackettccp/CIS106
/SourceCode/Module2/mixed_number_operations.py
1,699
4.46875
4
""" Demonstrates arithmetic with mixed ints and floats. Uncomment each section to demonstrate different mixed number operations. """ #Example 1 - Adding ints together. #Declares a variable named value1 and assigns it the value 10 value1 = 10 #Declares a variable named value2 and assigns it the value 20 value2 = 20 #Declares a variable named total1 #Assigns the sum of value1 and value2 to total1 #total1's data type will be int total1 = value1 + value2 #Prints the value of total1 print(total1) #********************************# print() #Example 2 - Adding a float and int together """ #Declares a variable named value3 and assigns it the value 90.5 value3 = 90.5 #Declares a variable named value4 and assigns it the value 40 value4 = 20 #Declares a variable named total2 #Assigns the sum of value3 and value3 to total2 #total2's data type will be float total2 = value3 + value4 #Prints the value of total2 print(total2) """ #********************************# print() #Example 3 - Adding floats together """ #Declares a variable named value5 and assigns it the value 15.6 value5 = 15.6 #Declares a variable named value6 and assigns it the value 7.5 value6 = 7.5 #Declares a variable named total3 #Assigns the sum of value5 and value6 to total3 #total3's data type will be float total3 = value5 + value6 #Prints the value of total3 print(total3) """ #********************************# print() #Example 4 - Multiple operands """ #Declares a variable named result #Assigns the sum of total1, total2, and total3 to result #result's data type will be float (int + float + float = float) result = total1 + total2 + total3 #Prints the value of result print(result) """
true
188486bfabc4f36413579d6d1af0aaae3da63681
hackettccp/CIS106
/SourceCode/Module10/entry_demo.py
504
4.125
4
#Imports the tkinter module import tkinter #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates an entry field that belongs to test_window test_entry = tkinter.Entry(test_window, width=10) #Packs the entry field onto the window test_entry.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Calls the main function/starts the program main()
true
6e470e6f8219a39ebdb2b862ea9bf85c7710c576
alexbehrens/Bioinformatics
/rosalind-problems-master/alg_heights/FibonacciNumbers .py
372
4.21875
4
def Fibonacci_Loop(number): old = 1 new = 1 for itr in range(number - 1): tmpVal = new new = old old = old + tmpVal return new def Fibonacci_Loop_Pythonic(number): old, new = 1, 1 for itr in range(number - 1): new, old = old, old + new return new print(Fibonacci_Loop(13)) print(Fibonacci_Loop_Pythonic(13))
true
5af688c66904d3d6b0ad57fbb008c93d2797ddd8
alexeahn/UNC-comp110
/exercises/ex06/dictionaries.py
1,276
4.25
4
"""Practice with dictionaries.""" __author__ = "730389910" # Define your functions below # Invert function: by giving values, returns a flip of the values def invert(first: dict[str, str]) -> dict[str, str]: """Inverts a dictionary.""" switch: dict[str, str] = {} for key in first: value: str = first[key] switch[value] = key return switch # Favorite color: sort different colors based on what people like the most def favorite_color(colors: dict[str, str]) -> str: """Gives the most frequently listed color.""" favorite: str = "" for key in colors: value: str = colors[key] favorite = value return favorite # Count: shows how many times a certain key was given def count(find: list[str]) -> dict[str, int]: """Counts how many times a string is presented.""" i: int = 0 final: dict[str, int] = {} while i < len(find): key = find[i] if key in final: final[key] += 1 else: final[key] = 1 i += 1 return final f: str = "blue" g: str = "silver" h: str = "gold" link: list[str] = ["fish", "bird", "dog", "fish"] print(invert({g: f})) print(favorite_color({"Alex": f, "Jeff": f, "Joe": g})) print(count(link))
true
43fff8b5123088e2fa7416157b729b0ddb3542a8
cassjs/practice_python
/practice_mini_scripts/math_quiz_addition.py
1,687
4.25
4
# Program: Math Quiz (Addition) # Description: Program randomly produces a sum of two integers. User can input the answer # and recieve a congrats message or an incorrect message with the correct answer. # Input: # Random Integer + Random Integer = ____ # Enter your answer: # Output: # Correct = Congratulations! # Incorrect = The correct answer is ____ # Program Output Example: # Correct # 22 + 46 = ___ # Enter your answer: 68 # Congratulations! # Incorrect # 75 + 16 = ___ # Enter your answer: 2 # The correct answer is 91. # Pseudocode: # Main Module # from numpy import random # Set num1 = random.randint(100) # Set num2 = random.randint(100) # Display num1, '+', num2, '= ___ ' # Set correctAnswer = num1 + num2 # Set userAnswer = getUserAnswer() # Call checkAnswer(userAnswer, correctAnswer) # End Main # Module getUserAnswer(): # Set userAnswer = int(input('Enter your answer: ')) # Return userAnswer # Module checkAnswer(userAnswer, correctAnswer): # If userAnswer == correctAnswer: # Display 'Congratulations!' # Else: # Display 'The correct answer is ', correctAnswer, '.', sep='' # End checkAnswer # Call Main def main(): from numpy import random num1 = random.randint(100) num2 = random.randint(100) print(num1, '+', num2, '= ___ ') correctAnswer = num1 + num2 userAnswer = getUserAnswer() checkAnswer(userAnswer, correctAnswer) def getUserAnswer(): userAnswer = int(input('Enter your answer: ')) return userAnswer def checkAnswer(userAnswer, correctAnswer): if userAnswer == correctAnswer: print('Congratulations!') else: print('The correct answer is ', correctAnswer, '.', sep='') main()
true
0970f57aa338249ee6466c1dadadeee769acf7c6
MurphyStudebaker/intro-to-python
/1-Basics.py
2,086
4.34375
4
""" PYTHON BASICS PRACTICE Author: Murphy Studebaker Week of 09/02/2019 --- Non-Code Content --- WRITING & RUNNING PROGRAMS Python programs are simply text files The .py extension tells the computer to interperet it as Python code Programs are run from the terminal, which is a low level interaction with the computer You must be in the directory of your program in order to run the file correctly Switch directories by typing: cd <PATH/TO/YOUR/FILE> (path can be found by right clicking your file and copying the full path) Once in the right directory, type python (or python3 for Macs) and then the name of your file EXAMPLE: python MyProgram.py NAMING CONVENTIONS Variable names should be lower_case, cannot contain any python keywords, and must be descriptive of what the variable represents OPERATORS + Addition - Subtraction * Multiplication / Division // Rounded Division ** Exponent (ex 2**2 is 2 to the power of 2) % Modulo aka Integer Remainder < Less than == Equal to > Greater than <= less than or equal to >= greater than or equal to != not equal to = assignment (setting a value to a variable) TYPES int Integer 8, 0, -1700 float Decimal 8.0, .05, -42.5 str String "A character", "30", "@#$!!adgHHJ" bool Boolean True, False """ """ NOW FOR THE CODE """ # GETTING INPUT AND OUTPUTTING TO CONSOLE # input is always a string # saving what the user types in to the variable "name" name = input("Enter your name: ") print("Hello, " + name) """ MODULES Modules are libraries of code written by other developers that make performing certain functions easier. Commonly used modules are the math module (has constants for pi and e and sqrt() functions) and the random module (randomly generate numbers) """ import random user_id = random.randint(100, 1000) print("Hello, " + name + "! Your ID is " + str(user_id)) # MATHEMATICAL OPERATIONS import math radius = float(input("Radius: ")) circ = 2 * math.pi * radius print("The circumference is " + str(circ))
true
a3c3790812f74749f601c0075b115fbe2a296ca1
sudoabhinav/competitive
/hackerrank/algorithms/strings/pangrams.py
232
4.125
4
# https://www.hackerrank.com/challenges/pangrams from string import ascii_lowercase s = raw_input().strip().lower() if len([item for item in ascii_lowercase if item in s]) == 26: print "pangram" else: print "not pangram"
true
e8cff56a53e29a80d047e999918b43deff019c3e
sauravsapkota/HackerRank
/Practice/Algorithms/Implementation/Beautiful Days at the Movies.py
713
4.15625
4
#!/bin/python3 import os # Python Program to Reverse a Number using While loop def reverse(num): rev = 0 while (num > 0): rem = num % 10 rev = (rev * 10) + rem num = num // 10 return rev # Complete the beautifulDays function below. def beautifulDays(i, j, k): count = 0 for num in range(i, j + 1): rev = reverse(num) if (abs(num - rev) % k) == 0: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) result = beautifulDays(i, j, k) fptr.write(str(result) + '\n') fptr.close()
true
f2cacc2f354655e601273d4a2946a2b27258624d
YayraVorsah/PythonWork
/conditions.py
1,769
4.1875
4
#Define variable is_hot = False is_cold = True if is_hot: #if true for the first statement then print print("It's a hot day") print("drink plenty of water") elif is_cold: # if the above is false and this is true then print this print("It's a cold day") print("Wear warm clothes") else: # else you print this if both statements are false print("It's a good day") print("Enjoy your day") print("EXERCISE") house_price = 1000000 good_credit = True bad_credit = False if good_credit: downpay = house_price//10 print("your downpayment : $" + str(downpay)) else : downpay = house_price//20 print("Your downpay is bad ") # if good_credit: # print("Your down payment is " + good_credit) print("LOGICAL OPERATORS") hasHighIncome = True hasGoodCredit = True if hasHighIncome and hasGoodCredit: #Both Conditions need to be true to execute print("Eligible for Loan") #even if one statement is false(It all becomes false due to the AND operator) else: print("Not eligible for Loan") hasHighIncome = True hasGoodCredit = False if hasHighIncome or hasGoodCredit: #At least One condition needs to be true to execute print("Eligible for Loan and other goods") #even if one statement is false it will execute because of the OR operator) else: print("Not eligible for Loan") print("NOT OPERATOR") #has good credit and not a criminal record good_credit = True criminalRecord = False # the not operator would turn this to True if good_credit and not criminalRecord: # and not (criminalRecord = False) === True print("you are good to go")
true
881a8e4b1aa1eaed9228782eef2440097c2cb301
siyangli32/World-City-Sorting
/quicksort.py
1,439
4.125
4
#Siyang Li #2.25.2013 #Lab Assignment 4: Quicksort #partition function that takes a list and partitions the list w/ the last item #in list as pivot def partition(the_list, p, r, compare_func): pivot = the_list[r] #sets the last item as pivot i = p-1 #initializes the two indexes i and j to partition with j = p while not j == r: #function runs as long as j has not reached last object in list if compare_func(the_list[j], pivot): #takes in compare function to return Boolean i += 1 #increments i before j temp = the_list[i] #switches i value with j value the_list[i] = the_list[j] the_list[j] = temp j += 1 #increments j temp = the_list[r] #switches pivot with the first object larger than pivot the_list[r] = the_list[i+1] the_list[i+1] = temp return i+1 #returns q = i+1 (or pivot position) #quicksort function takes in the partition function and recursively sorts list def quicksort(the_list, p, r, compare_func): if p < r: #recursive q = partition(the_list, p, r, compare_func) quicksort(the_list, p, q-1, compare_func) quicksort(the_list, q+1, r, compare_func) return the_list #sort function sorts the entire list using quicksort def sort(the_list, compare_func): return quicksort(the_list, 0, len(the_list)-1, compare_func)
true
150810f760c409533200b7252912130cc72e792b
aiman88/python
/Introduction/case_study1.py
315
4.1875
4
""" Author - Aiman Date : 6/Dec/2019 Write a program which will find factors of given number and find whether the factor is even or odd. """ given_number=9 sum=1 while given_number>0: sum=sum*given_number given_number-=1 print(sum) if sum%10!=0: print("odd number") else: print("Even number")
true
764b1f8af7fee5c6d0d1707ab6462fc1d279be36
dadheech-vartika/Leetcode-June-challenge
/Solutions/ReverseString.py
863
4.28125
4
# Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # You may assume all the characters consist of printable ascii characters. # Example 1: # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Example 2: # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"] # Hide Hint #1 # The entire logic for reversing a string is based on using the opposite directional two-pointer approach! # SOLUTION: class Solution(object): def reverseString(self, s): def helper(left,right): if left < right: s[left], s[right] = s[right], s[left] helper(left + 1, right - 1) helper(0, len(s) - 1)
true
ca042af11712f32c4b089da67c4a9dcfecd6000d
darkblaro/Python-code-samples
/strangeRoot.py
1,133
4.25
4
import math ''' getRoot gets a number; calculate a square root of the number; separates 3 digits after decimal point and converts them to list of numbers ''' def getRoot(nb): lsr=[] nb=math.floor(((math.sqrt(nb))%1)*1000) #To get 3 digits after decimal point ar=str(nb) for i in ar: lsr.append(int(i)) return lsr ''' getPower gets a number; calculate a power of the number; and converts the result to list of numbers ''' def getPower(num): lsp=[] num=int(math.pow(num,2)) ar=str(num) for i in ar: lsp.append(int(i)) return lsp ''' isStrange gets a number; calls to two functions above and gets from them two lists of numbers; after that compares two lists ''' def isStrange(nb): ls1=getRoot(nb) ls2=getPower(nb) for i1 in ls1: for i2 in ls2: if i1==i2: return True return False if __name__ == '__main__': number=int(input("Enter a number")) if isStrange(number): print(f'{number} has strange root') else: print(f'{number} doesn\'t have strange root')
true
01b8496d29a0a14957447204d655e441254aeb75
worasit/python-learning
/mastering/generators/__init__.py
1,836
4.375
4
""" `A generator` is a specific type of iterator taht generates values through a function. While traditional methods build and return a `list` of iterms, ad generator will simply `yield` every value separately at the moment when they are requested by the caller. Pros: - Generators pause execution completely until the next value is yielded, which make them completely lazy. - Generators have no need to save values. Whereas a traditional function would require creating a `list` and storing all results until they are returned, a generator only need to store a single value - Generators have infinite size. There is no requirement to stop at a certain point These preceding benefits come at a price, however. The immediate results of these benefits are a few disadvantage Cons: - Until you are done processing, you never know how many values are left; it could even be infinite. This make usage dangerous in some cases; executing `list(some_infinite_generator)` will run out of memory - You cannot slice generators - You cannot get specific items without yielding all values before that index - You cannot restart a generator. All values are yielded exactly one ================= Coroutines =============== Coroutiens are functions that allow for multitasking without requiring multiple threads or processes. Whereas generators can only yield values from the caller while it is still running. While this technique has a few limiations, if it suits your purpose, it can result in great performance at a very little cost. The topics covered in this chapter are: - The characteristics and uses of generators - Generator comprehensions - Generator functions - Generator classes - Buldled generators - Coroutines """
true
c03dd868f24eec310e537c5c224b9627b469a811
rileyworstell/PythonAlgoExpert
/twoNumSum.py
900
4.21875
4
""" Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If not two numbers sum up to the target sum, the function should return an empty array. Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum. You can assume there will be at most one pair of numbers summing up to the target sum. """ class Car: def __init__(self, year): self.color = "Red" self.year = year Mustang = Car(1997) print(Mustang.color) print(Mustang.year) dict1 = { "brand": "Nike", "color": "Red" } mydict = dict1 print(mydict["brand"]) arr = [[x for x in range(10)] for _ in range(10)] print(arr)
true
c79ba3a6834fbb5a0f8d5c2ebabe0d4f6f790452
mwongeraE/python
/spellcheck-with-inputfile.py
904
4.15625
4
def spellcheck(inputfile): filebeingchecked=open(inputfile,'r') spellcheckfile=open("words.txt",'r') dictionary=spellcheckfile.read().split() checkedwords=filebeingchecked.read().split() for word in checkedwords: low = 0; high=len(dictionary)-1 while low <= high: mid=(low+high)//2 item=dictionary[mid] if word == item: break elif word < item: high=mid-1 else: low=mid+1 else: yield word def main(): print("This program accepts a file as an input file and uses a spell check function to \nidentify any problematic words that are not found in a common dictionary.") inputfile=input("Enter the name of the desired .txt file you wish to spellcheck:") for word in spellcheck(inputfile): print(word) main()
true
89038721966e0c3974e91a3c58db4c6245ffa354
robwalker2106/100-Days
/day-18-start/main.py
1,677
4.1875
4
from turtle import Turtle, Screen from random import randint, choice don = Turtle() #don.shape('turtle') don.color('purple3') #don.width(10) don.speed('fastest') screen = Screen() screen.colormode(255) def random_color(): """ Returns a random R, G, B color. :return: Three integers. """ r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return r, g, b def spirograph(circles, radius): """ Creates a spirograph with the inputted amount of circles, each with random line colors and equal radius size. :param circles: int :param radius: int :return: """ angles = 360 / circles for _ in range(circles): don.setheading(don.heading() + angles) don.pencolor(random_color()) don.circle(radius) spirograph(120, 150) # def short_walk(): # """ # Creates a short walk with a random color and direction. There are three choices for the direction. # (Left, Straight, or Right). # :return: None # """ # not_backwards = [-90, 0, 90] # current = int(don.heading()) # don.setheading(current + choice(not_backwards)) # don.pencolor(random_color()) # don.forward(15) # # # for _ in range(200): # short_walk() # def draw_shape(sides): # """ # Draws a shape with equal N sides. # :param sides: int # :return: None # """ # r = randint(1, 255) # b = randint(1, 255) # g = randint(1, 255) # # for _ in range(sides): # don.pencolor((r, g, b)) # don.forward(100) # don.right(360 / sides) # for i in range(3, 11): # draw_shape(i) screen.screensize(600, 600) screen.exitonclick()
true
a3337bde5cf7d0b0712a15f23d2ab63fed289c2f
nickdurbin/iterative-sorting
/src/searching/searching.py
1,860
4.3125
4
def linear_search(arr, target): # Your code here # We simply loop over an array # from 0 to the end or len(arr) for item in range(0, len(arr)): # We simply check if the item is equal # to our target value # If so, then simply return the item if arr[item] == target: return item # If the target does not exist in our array # Return -1 which equates to not found return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here # We need the beginning of the array # So we create a variable and start at zero start = 0 # Next we need to find the end of the array # Create a variable use the length - 1 end = len(arr) - 1 # Next we create a loop that runs as long as the start # and the end are NOT the same and start is LESS THAN # the value of end while start <= end: # Here we create the middle value # We simply add the start + end and then divide # By two to find the median value or middle middle = (start + end) // 2 # If our middle value is the target we are searching for # simply return the middle value if arr[middle] == target: return middle # Else if the middle value is less than our target value # We do not need any of the array values before our middle # So we make the start our middle value + 1 elif arr[middle] < target: start = middle + 1 # Else if the middle is greater than the target # we work backwards and make our mid value # equal to our end value and subtract one else: end = middle - 1 # If the target value is not in the array # return -1, which is not found return -1 # not found
true
c346a76f33f96248e4782304636a32c12238c6aa
adilawt/Tutorial_2
/1_simpsons_rule.py
672
4.15625
4
# ## Tutorial2 Question3 ## a) Write a python function to integrate the vector(in question #2) using ## Simpson's Rule # import numpy as np def simpsonsrule(f, x0, xf, n): if n & 1: print ("Error: n is not a even number.") return 0.0 h = float(xf - x0) / n integral = 0.0 x = float(x0) for i in range(0, n / 2): integral += f(x) + (2.0 * f(x + h)) x += 2 * h integral = (2.0 * integral) - f(x0)+f(x0) integral = h * integral / 3.0 return integral def f(x): #f(x) = np.cos(x) return np.cos(x) x0=0.0; xf=np.pi/2 N = (10,30,100,300,1000) for n in N: print(simpsonsrule(f, x0, xf, n))
true
ab1a0c5e0f29e91a4d2c49a662e3176f4aa158f5
salihbaltali/nht
/check_if_power_of_two.py
930
4.1875
4
""" Write a Python program to check if a given positive integer is a power of two """ def isInt(x): x = abs(x) if x > int(x): return False else: return True def check_if_power_of_two(value): if value >= 1: if value == 1 or value == 2: return True else: while value != 2: value /= 2 if isInt(value) == False : return False return True else: if value == 0: return False while value < 1: value *= 2 if value == 1: return True else: return False while True: number = float(input("Please Enter the Number: ")) print(number) if check_if_power_of_two(number): print("{} is the power of 2".format(number)) else: print("{} is not the power of 2".format(number))
true
89994b56da945167c927ad2617a5b9cbfc2d4a6b
rkovrigin/crypto
/week2.py
2,872
4.25
4
""" In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in the lecture (14:04). While we ask that you implement both encryption and decryption, we will only test the decryption function. In the following questions you are given an AES key and a ciphertext (both are hex encoded ) and your goal is to recover the plaintext and enter it in the input boxes provided below. For an implementation of AES you may use an existing crypto library such as PyCrypto (Python), Crypto++ (C++), or any other. While it is fine to use the built-in AES functions, we ask that as a learning experience you implement CBC and CTR modes yourself. Question 1 CBC key: 140b41b22a29beb4061bda66b6747e14 CBC Ciphertext 1: 4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81 """ from Cryptodome.Cipher import AES from Cryptodome import Random from Cryptodome.Util import Counter import codecs keys = [] ciphers = [] keys.append(codecs.decode("140b41b22a29beb4061bda66b6747e14", 'hex')) keys.append(codecs.decode("140b41b22a29beb4061bda66b6747e14", 'hex')) keys.append(codecs.decode("36f18357be4dbd77f050515c73fcf9f2", 'hex')) keys.append(codecs.decode("36f18357be4dbd77f050515c73fcf9f2", 'hex')) ciphers.append(codecs.decode("4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81", "hex")) ciphers.append(codecs.decode("5b68629feb8606f9a6667670b75b38a5b4832d0f26e1ab7da33249de7d4afc48e713ac646ace36e872ad5fb8a512428a6e21364b0c374df45503473c5242a253", "hex")) ciphers.append(codecs.decode("69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc388d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329", "hex")) ciphers.append(codecs.decode("770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa0e311bde9d4e01726d3184c34451", "hex")) block_size = 16 def decrypt_cbc(key, cypherText): iv = cypherText[:block_size] ct1 = cypherText[block_size:] obj = AES.new(key, AES.MODE_CBC,iv) padded_str = obj.decrypt(ct1) padding_amount = ord(padded_str[len(padded_str)-1:]) return padded_str[:-padding_amount] def decrypt_ctr(key, cypherText): iv = cypherText[:block_size] ct1 = cypherText[block_size:] ctr = Counter.new(block_size * 8, initial_value=int(codecs.encode(iv, 'hex'), 16)) obj = AES.new(key, AES.MODE_CTR, counter=ctr) padded_str = obj.decrypt(ct1) return padded_str for key, cipher in zip(keys[:2], ciphers[:2]): out = decrypt_cbc(key, cipher) print(out) for key, cipher in zip(keys[2:], ciphers[2:]): out = decrypt_ctr(key, cipher) print(out)
true
1350fcd3baa866a02f5db2c066420eaa77e00892
BrasilP/PythonOop
/CreatingFunctions.py
1,404
4.65625
5
# Creating Functions # In this exercise, we will review functions, as they are key building blocks of object-oriented programs. # Create a function average_numbers(), which takes a list num_list as input and then returns avg as output. # Inside the function, create a variable, avg, that takes the average of all the numbers in the list. # Call the average_numbers function on the list [1, 2, 3, 4, 5, 6] and assign the output to the variable my_avg. # Print out my_avg. # Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1, 2, 3, 4, 5, 6]) # Print out my_avg print(my_avg) # 3.5 # Creating a complex data type # In this exercise, we'll take a closer look at the flexibility of the list data type, by creating a list of lists. # In Python, lists usually look like our list example below, and can be made up of either simple strings, integers, # or a combination of both. list = [1, 2] # In creating a list of lists, we're building up to the concept of a NumPy array. # Create a variable called matrix, and assign it the value of a list. # Within the matrix list, include two additional lists: [1,2,3,4] and [5,6,7,8]. # Print the matrix list. matrix = [[1, 2, 3, 4], [5, 6, 7, 8]] print(matrix)
true
566ff9db1680e613ef013e6918d274b1382c2934
codethat-vivek/NPTEL-Programming-Data-Structures-And-Algorithms-Using-Python-2021
/week2/RotateList.py
646
4.28125
4
# Third Problem: ''' A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2]. Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotations. If k is not positive, your function should return l unchanged. Note that your function should not change l itself, and should return the rotated list. ''' # SOLUTION - def rotatelist(l,k): if k <= 0: return l ans = [0]*len(l) for i in range(len(l)): ans[i] = l[(i+k)%len(l)] return ans
true
1ff1fadb88d860e4d2b97c5c38668bcc880c607c
morzen/Greenwhich1
/COMP1753/week7/L05 Debugging/02Calculator_ifElifElse.py
1,241
4.40625
4
# this program asks the user for 2 numbers and an operation +, -, *, / # it applies the operation to the numbers and outputs the result def input_and_convert(prompt, conversion_fn): """ this function prompts the user for some input then it converts the input to whatever data-type the programmer has requested and returns the value """ string = input(prompt) number = conversion_fn(string) return number def output(parameter1, parameter2): """ this function prints its parameters as strings """ parameter1_str = str(parameter1) parameter2_str = str(parameter2) print(parameter1_str + parameter2_str) number1 = input_and_convert(" First number: ", int) number2 = input_and_convert("Second number: ", int) operation = input_and_convert("Operation [+, -, *, /]: ", str) if operation == "+": combination = number1 + number2 elif operation == "-": combination = number1 - number2 elif operation == "*": combination = number1 * number2 elif operation == "/": combination = number1 / number2 else: # the user has made a mistake :( combination = "ERROR ... '" + operation + "' unrecognised" output("Answer: ", combination) print() input("Press return to continue ...")
true
36e7cd8cc96264f50e49f9cd2b778fc642434312
GaryZhang15/a_byte_of_python
/002_var.py
227
4.15625
4
print('\n******Start Line******\n') i =5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) a = 'hello'; print(a) b = \ 5 print(b) print('\n*******End Line*******\n')
true
a09f9fe6aa0663cf8143ca71d01553918d6d35a1
Sana-mohd/fileQuestions
/S_s_4.py
298
4.34375
4
#Write a Python function that takes a list of strings as an argument and displays the strings which # starts with “S” or “s”. Also write a program to invoke this function. def s_S(list): for i in list: if i[0]=="S" or i[0]=="s": print(i) s_S(["sana","ali","Sara"])
true
ddc89b17a98a81a0e4b2141e487c0c2948d0621a
lfr4704/python_practice_problems
/algorithms.py
1,579
4.375
4
import sys; import timeit; # Big-O notation describes how quickly runtime will grow relative to the input as the input gets arbitrarily large. def sum1(n): #take an input of n and return the sume of the numbers from 0 to n final_sum = 0; for x in range(n+1): # this is a O(n) final_sum += x return final_sum def sum2(n): return (n*(n+1))/2 # this is a O(n**2) # using setitem t = timeit.Timer() print 'TIMEIT:' print "sum1 is " + str(sum1(100)) + " and the time for sum1 " + str(t.timeit(sum1(100))) print "sum2 is " + str(sum2(100)) + " and time for sum2 " + str(t.timeit(sum2(100))) #O(1) constant def func_constant (values): ''' print first item in a list of value ''' print values[0] func_constant([1,2,3,4,5,6,7]) # no matter how big the list gets the output will always be constant (1) #O(n) Linear is going to be a little more computational than a constant (will take longer) def func_lin (lst): ''' takes in list and prints out all values ''' for val in lst: print val func_lin([1,2,3,4,5,6,7]) #O(n^2) Quadratic def func_quadratic(lst): #prints pairs for every item in list for item_1 in lst: for item_2 in lst: print (item_1, item_2) lst = [1,2,3] print func_quadratic(lst) #this will always have to do an n * n so it will be Quadratic as n grows # time complexity vs. space complexity def memory(n): for x in range(n): # time complexity O(n) print ('memory') # space complexity O(1) - becuase memory is a constant, never changes memory(4)
true
01d9030aa89da902667a6ea05a45bbd9761162ef
DerekHunterIcon/CoffeeAndCode
/Week_1/if_statements.py
239
4.1875
4
x = 5 y = 2 if x < y: print "x is less than y" else print "x is greater than or equal to y" isTrue = True if isTrue: print "It's True" else: print "It's False" isTrue = False if isTrue: print "It's True" else: print "It's False"
true
f2ed037552b3a8fdd37b776d5b9df5709b0e494e
SamWaggoner/125_HW6
/Waggoner_hw6a.py
2,742
4.1875
4
# This is the updated version that I made on 7/2/21 # This program will ask input for a list then determine the mode. def determinemode(): numlist = [] freqlist = [] print("Hello! I will calculate the longest sequence of numbers in a list.") print("Type your list of numbers and then type \"end\".") num = (input("Please enter a number: ")) def CheckNum(num): try: num = int(num) return True except ValueError: return False while CheckNum(num) != False: numlist.append(int(num)) num = ((input("Please enter a number: "))) print(numlist) currFreq = 1 modeNum = -1 maxNumOccurrences = 1 for i in range(len(numlist)-2): if numlist[i] == numlist[i+1]: currFreq += 1 if currFreq > maxNumOccurrences: maxNumOccurrences = currFreq modeNum = numlist[i] else: currFreq = 1 if len(numlist) == 0: print("There is no mode, the list provided is empty.") elif modeNum == -1: print("There is no mode, all of the numbers occur an equal number of times.") else: print("The mode is " + str(modeNum) + " which occurred " + str(maxNumOccurrences) + " times.") determinemode() while input("Would you like to find another mode from a new list? (Type \"yes\"): ") == "yes": determinemode() print("Okay, glad I could help!") # This is the original program that I made while in school as homework. # File: hw6a.py # Author: Sam Waggoner # Date: 10/25/2020 # Section: 1006 # E-mail samuel.waggoner@maine.edu # Description: # Create a count for the largest number of subsequent numbers entered by the user. # Collaboration: # I did not discuss this assignment with anyone other than the course staff. (I # got help from Matt.) # def main(): # numlist = [] # freqlist = [] # print("Hello! I will calculate the longest sequence of numbers in a list.") # print("Type your list of numbers and then type end.") # num = (input("Please enter a number: ")) # while num!= "end": # numlist.append(int(num)) # num = ((input("Please enter a number: "))) # print(numlist) # freq = 1 # currfreq = 1 # numfreq = 0 # for i in range(len(numlist)-1): # if numlist[i] == numlist[i+1]: # currfreq += 1 # if currfreq > freq: # freq = currfreq # currfreq = 1 # numfreq = numlist[i] # print("The most frequent number was "+str(numfreq)+" which was printed "+str(freq)+" times.") # main()
true
35f1a4243a2a56315eee8070401ee4f8dc38bf9c
JordanJLopez/cs373-tkinter
/hello_world_bigger.py
888
4.3125
4
#!/usr/bin/python3 from tkinter import * # Create the main tkinter window window = Tk() ### NEW ### # Set window size with X px by Y px window.geometry("500x500") ### NEW ### # Create a var that will contain the display text text = StringVar() # Create a Message object within our Window window_message = Message(window, textvariable = text) # Set the display text text.set("HELLO WORLD") # Compile the message with the display text ### NEW ### ## Notable .config Attributes: # anchor: Orientation of text # bg: Background color # font: Font of text # width: Width of text frame # padx: Padding on left and right # pady: Padding on top and bottom # and more! window_message.config(width=500, pady=250, font=("Consolas", 60), bg = 'light blue') ### NEW ### window_message.pack() # Start the window loop window.mainloop() exit()
true
4df8eadf0fe84ff3b194ac562f24a94b778a2588
Zioq/Algorithms-and-Data-Structures-With-Python
/7.Classes and objects/lecture_3.py
2,395
4.46875
4
# Special methods and what they are # Diffrence between __str__ & __repr__ """ str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__. This means, in simple terms: almost every object you implement should have a functional __repr__ that’s usable for understanding the object. Implementing __str__ is optional """ class Student: def __init__(self, first, last, courses=None ): self.first_name = first self.last_name = last if courses == None: self.courses = [] else: self.courses = courses def add_course(self, new_course): if new_course not in self.courses: self.courses.append(new_course) else: print(f"{self.first_name} is already enrolled in the {new_course} course") def remove_course(self, remove_course): if remove_course in self.courses: self.courses.remove(remove_course) else: print(f"{remove_course} not found") def __len__(self): return len(self.courses) def __repr__(self): return f"Sturdent('{self.first_name}', '{self.last_name}', '{self.courses}')" def __str__(self): return f"First name: {self.first_name.capitalize()}\nLast name: {self.last_name.capitalize()}\nCourses: {', '.join(map(str.capitalize, self.courses))}" courses_1 = ['python', 'go', 'javascript'] courses_2 = ['java', 'go', 'c'] # Create new object of class robert = Student("Robert", "Han") john = Student("John", "Smith",courses_2) print(robert.first_name, robert.last_name, robert.courses) print(john.first_name, john.last_name, john.courses) # Add new course using a method john.add_course("java") robert.add_course("PHP") print(robert.first_name, robert.last_name, robert.courses) # Remove course using a method john.remove_course("c") john.remove_course("c") john.remove_course("python") print(john.first_name, john.last_name, john.courses) # use __str__ method print(robert) print(john) # use __dict__ method print(robert.__dict__) # use repre method print(repr(robert)) print(repr(john)) # use len functionality print(len(robert)) # return how many courses robert enrolled.
true
835fff2341216766489b87ac7682ef49a47fb713
Zioq/Algorithms-and-Data-Structures-With-Python
/1.Strings,variables/lecture_2.py
702
4.125
4
# concatenation, indexing, slicing, python console # concatenation: Add strings each other message = "The price of the stock is:" price = "$1110" print(id(message)) #print(message + " " +price) message = message + " " +price print(id(message)) # Indexing name = "interstella" print(name[0]) #print i # Slicing # [0:5] first num is start point, second num is stop point +1, so it means 0~4 characters print(name[0:5]) # print `inter` #[A:B:C] -> A: Start point, B: Stop +1, C: Step size nums ="0123456789" print(nums[2:6]) # output: 2345 print(nums[0:6:2]) # output: 024 print(nums[::2]) # output : 02468 print(nums[::-1]) # -1 mena backward step so, it will reverse the array. output: 9876543210
true
9123640f03d71649f31c4a6740ba9d1d3eca5caf
Zioq/Algorithms-and-Data-Structures-With-Python
/17.Hashmap/Mini Project/project_script_generator.py
1,946
4.3125
4
# Application usage ''' - In application you will have to load data from persistent memory to working memory as objects. - Once loaded, you can work with data in these objects and perform operations as necessary Exmaple) 1. In Database or other data source 2. Load data 3. Save it in data structure like `Dictionary` 4. Get the data from the data structure and work with process data as necessary 5. Produce output like presentation or update data and upload to the Database etc In this project we follow those steps like this 1. Text file - email address and quotes 2. Load data 3. Populate the AlgoHashTable 4. Search for quotes from specific users 5. Present the data to the console output ''' # Eamil address and quotes key-value data generator from random import choice from string import ascii_lowercase as letters list_of_domains = ['yaexample.com','goexample.com','example.com'] quotes = [ 'Luck is what happens when preparation meets opportunity', 'All cruelty springs from weakness', 'Begin at once to live, and count each separate day as a separate life', 'Throw me to the wolves and I will return leading the pack'] def generate_name(lenght_of_name): return ''.join(choice(letters) for i in range(lenght_of_name)) def get_domain(list_of_domains): return choice(list_of_domains) def get_quotes(list_of_quotes): return choice(list_of_quotes) def generate_records(length_of_name, list_of_domains, total_records, list_of_quotes): with open("data.txt", "w") as to_write: for num in range(total_records): key = generate_name(length_of_name)+"@"+get_domain(list_of_domains) value = get_quotes(quotes) to_write.write(key + ":" + value + "\n") to_write.write("mashrur@example.com:Don't let me leave Murph\n") to_write.write("evgeny@example.com:All I do is win win win no matter what!\n") generate_records(10, list_of_domains, 100000, quotes)
true
517611d9663ae87acdf5fed32099ec8dcf26ee76
Zioq/Algorithms-and-Data-Structures-With-Python
/20.Stacks and Queues/stack.py
2,544
4.25
4
import time class Node: def __init__(self, data = None): ''' Initialize node with data and next pointer ''' self.data = data self.next = None class Stack: def __init__(self): ''' Initialize stack with stack pointer ''' print("Stack created") # Only add stack pointer which is Head self.stack_pointer = None # Push - can only push (add) an item on top of the stack (aka head or stack pointer) def push(self,x): ''' Add x to the top of stack ''' if not isinstance(x, Node): x = Node(x) print (f"Adding {x.data} to the top of stack") # If the Stack is empty, set the stack point as x, which is just added. if self.is_empty(): self.stack_pointer = x # If the Stack has some Node else: x.next = self.stack_pointer self.stack_pointer = x # Pop - can only remove an item on top of the stack (aka head or stack pointer) def pop(self): if not self.is_empty(): print("Removing node on top of stack") curr = self.stack_pointer self.stack_pointer = self.stack_pointer.next curr.next = None return curr.data else: return "Stack is empty" def is_empty(self): '''return True if stack is empty, else return false''' return self.stack_pointer == None # peek - view value on top of the stack (aka head or stack pointer) def peek(self): '''look at the node on top of the stack''' if not self.is_empty(): return self.stack_pointer.data def __str__(self): print("Printing Stack state...") to_print = "" curr = self.stack_pointer while curr is not None: to_print += str(curr.data) + "->" curr = curr.next if to_print: print("Stack Pointer") print(" |") print(" V") return "[" + to_print[:-2] + "]" return "[]" my_stack = Stack() print("Checking if stack is empty:", my_stack.is_empty()) my_stack.push(1) time.sleep(2) my_stack.push(2) print(my_stack) time.sleep(2) my_stack.push(3) time.sleep(2) my_stack.push(4) time.sleep(2) print("Checking item on top of stack:", my_stack.peek()) time.sleep(2) my_stack.push(5) print(my_stack) time.sleep(2) print(my_stack.pop()) time.sleep(2) print(my_stack.pop()) print(my_stack) time.sleep(2) my_stack.push(4) print(my_stack) time.sleep(2)
true
002c584b14e9af36fe9db5858c64711ec0421533
PaulSayantan/problem-solving
/CODEWARS/sum_of_digits.py
889
4.25
4
''' Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. ''' import unittest def digitalRoot(n:int): if n < 10 and n > 0: return n add = 0 while n != 0: add += n % 10 n = n // 10 if add > 9: return digitalRoot(int(add)) else: return int(add) class digitRootTest(unittest.TestCase): def test1(self): self.assertEqual(digitalRoot(16), 7) def test2(self): self.assertEqual(digitalRoot(942), 6) def test3(self): self.assertEqual(digitalRoot(132189), 6) def test4(self): self.assertEqual(digitalRoot(493193), 2) if __name__ == "__main__": unittest.main()
true
f99bcedd6bed96991fb8fdf06eba27708ef867b1
dks1018/CoffeeShopCoding
/2021/Code/Python/DataStructures/dictionary_practice1.py
1,148
4.25
4
myList = ["a", "b", "c", "d"] letters = "abcdefghijklmnopqrstuvwxyz" numbers = "123456789" newString = " Mississippi ".join(numbers) print(newString) fruit = { "Orange":"Orange juicy citrus fruit", "Apple":"Red juicy friend", "Lemon":"Sour citrus fruit", "Lime":"Green sour fruit" } veggies = { "Spinach":"Katia does not like it", "Brussel Sprouts":"No one likes them", "Brocolli":"Makes people gassy" } veggies.update(fruit) print(veggies) superDictionary = fruit.copy() superDictionary.update(veggies) print(superDictionary) while True: user_input = str(input("Enter Fruit or Veggie: ")) if user_input == "quit": break if user_input in superDictionary or fruit or veggies: print(superDictionary.get(user_input)) if user_input not in superDictionary and fruit and veggies: print("Hey that item is not in the list, but let me add it for you!!") fruit_veggie = str(input("Enter your Fruit or Veggie: ")) desc = str(input("Enter the taste: ")) superDictionary[fruit_veggie] = desc print(superDictionary[fruit_veggie])
true
1c4e7bf09af67655c22846ecfc1312db04c3bfe1
dks1018/CoffeeShopCoding
/2021/Code/Python/Tutoring/Challenge/main.py
967
4.125
4
import time # You can edit this code and run it right here in the browser! # First we'll import some turtles and shapes: from turtle import * from shapes import * # Create a turtle named Tommy: tommy = Turtle() tommy.shape("turtle") tommy.speed(10) # Draw three circles: draw_circle(tommy, "green", 50, 0, 100) draw_circle(tommy, "green", 50, 0, 200) draw_circle(tommy, "blue", 50, 75, 25) draw_circle(tommy, "red", 50, -75, 25) # Draw three Squares draw_square(tommy, "green", 50, -50, -200) draw_square(tommy, "green", 50, -50, -300) draw_square(tommy, "blue", 50, 50, -200) draw_square(tommy, "red", 50, -150, -200) # Write a little message: tommy.penup() tommy.goto(0,-50) tommy.color("black") tommy.write("Darius's New Python Challenge", None, "center", "16pt 20") tommy.goto(0,-80) # Try changing draw_circle to draw_square, draw_triangle, or draw_star #The turtle program is finished turtle.done() #Dont close out GUI for (x) seconds #time.sleep(10)
true
760537b38c1899088736d0f4a3ba3d27fe3a29c5
dks1018/CoffeeShopCoding
/2021/Code/Python/Searches/BinarySearch/BinarySearch.py
1,779
4.15625
4
low = 1 high = 1000 print("Please think of a number between {} and {}".format(low, high)) input("Press ENTER to start") guesses = 1 while low != high: print("\tGuessing in the range of {} and {}".format(low, high)) # Calculate midpoint between low adn high values guess = low + (high - low) // 2 high_low = input("My guess is {}. Should I guess Higher or Lower?" "Enter h or l or c if my guess was correct " .format(guess)).casefold() if high_low == "h": # Guess higher.The low end of the range becomes 1 greater than the guess. low = guess + 1 elif high_low == "l": # Guess lower.The high end of the range becomes one less than the guess high = guess - 1 elif high_low == "c": print("I got it in {} guesses!".format(guesses)) break else: print("Please enter h,l, or c") guesses += 1 else: print("You thought of the number {}".format(low)) print("I got it in {} guesses".format(guesses)) #I am choosing 129 # with 1000 number what I want to do is be able to guess the users number within 10 guesses # to do this i need to continue to devide in half the high form the low # then establish a new high and low # if the number is 22 and the high is 100 and low is 0 first computer says # 1 is you number 50? higher or lower # lower, so high is 100-1 / 2 equals 49.5 rounded down high now equals 49 low now equals 0 # 2 is the number 25 or higher or lower # lower so high is 49-1 / 2 is 24 # 3 is you number 12, # it is higher so lower = guess + 1 # lower is 13 high is 24 # 4 is you number 18, # no high # 5 lower is 19, is your number 21 # no high lower equals 22 high equals 24 # 6 is your number 23, no lower # 7 your number is 22
true