blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
00404a17c4abb680cc7424d8e968d4b5bce4de82
bsakers/Introduction_to_Python
/classes_three.py
1,976
4.3125
4
class Computer(object): condition = "new" def __init__(self, model, color, ram, storage): self.model = model self.color = color self.ram = ram self.storage = storage def display_computer(self): return "This is a %s %s with %s gb of RAM and %s gb SSD." %(self.color, self.model, str(self.ram), str(self.storage)) def use_computer(self): self.condition = "used" my_computer = Computer("Macbook Pro", "space grey", 16, 512) print my_computer.display_computer() print my_computer.condition my_computer.use_computer() print my_computer.condition #note that in the above we modified condition variable from new to used, via the use_computer method #if we were to create a new computer variable, it would have the "new" condition class CellPhone(Computer): def __init__(self, model, color, ram, storage, carrier): self.model = model self.color = color self.ram = ram self.storage = storage self.carrier = carrier def use_computer(self): self.condition = "almost new" def __repr__(self): return "(%s, %s, %i, %i, %s)" %(self.model, self.color, self.ram, self.storage, self.carrier) my_cell = CellPhone("iPhone", "black", 8, 64, "Verizon") print my_cell.carrier print my_cell.condition my_cell.use_computer() print my_cell.condition #in the above, we overrode the "use computer" method, to change the condition from new to "almost new" #OVERRIDING __repr__(): #there is a built in function, __repr__ which stands for representation #representation is how python will represent an object #normally, this is returned in a format similar to <__ object at 0x012202> #however, we can tell python to show us the object however we want #note the difference between printing my_computer and my_cell below print my_computer print my_cell #since we overwrote the repr method for the CellPhone class, we see the object differently than for the computer class
true
c4f1a54798667c53eb6952afc1d0fe923c052803
bsakers/Introduction_to_Python
/classes.py
1,977
4.34375
4
#general sytax for a class: class NewClassName(object): # code pass #in the above, we simply state the keyword 'class' and whatever we want to name it #then we state what the class will inherit from (here we inherit from python's object) #the 'pass' keyword doesnt do anything, but can act as a placeholder to not break our placeholder #similar to ruby, each class requires an initialize function to actually create class objects class Hero(object): def __init__(self, name, role): self.name = name self.role = role is_from_dota2 = True def description(self): print self.name print self.role #in the above, the initialize function follows the syntax '__init__(x, y, z)' #the first argument is almost always 'self', which just refers to that specific object being created #technically, you dont have to use 'self', as the first argument will always refer to calling upon that specific object, but this is common practice #under initialize we define each of the subsequent arguments passed in #this is very similar to ruby, where we used @name = name #since we've made a class, we can now instantiate objects: jugg = Hero("Juggernaut", "carry") print jugg.name, jugg.role #scope # global variables/functions, variables that are available everywhere # member variables/functions, variables that are only available to members of a certain class # instance variables/functions, variables that are only available to particular instances of a class #in our hero class, we created a member variable, is_from_dota2, meaning all objects of that class have access (and will return the same) print jugg.is_from_dota2 #no matter how many heros I create, they will all have true for is_from_dota2 #we also created a member function, description, which also required a self statement jugg.description() #note in the above, I can call .description() on ANY of my class objects since it's a member function
true
027342a1e6c8fa72fc03ea820f4770209fa04f77
bsakers/Introduction_to_Python
/enumerate.py
463
4.6875
5
#enumerate supplies a corresponding index as we loop options = ["pizza", "sushi", "gyro"] #normal for loop: for option in options: print option #enumerator (note that "index" could be replaced by anything; it's just a placeholder) for index, option in enumerate(options): print index, option #we can even alter the index count if needed (example, for a list to not start at 1) for index, option in enumerate(options): print index +1, option
true
325ab3f4d26130fd386bbdb3473ae5c7dbe9ca63
bsakers/Introduction_to_Python
/pig_latin_translator.py
376
4.125
4
print 'Welcome to the Pig Latin Translator!' original_word = raw_input("Enter a word you would like translated: ").lower() ending = "ay" if len(original_word) > 0 and original_word.isalpha(): translated_word = original_word[1:len(original_word)] + original_word[0] + ending print translated_word else: print "Your imput is either empty or contains a non-letter"
true
3aae270f26e6a22bf805081abfee3ed682002282
ayecoo-103/Python_Code_Drills
/03_Inst_ATM_Application_Logic/Unsolved/atm.py
656
4.15625
4
"""This is a basic ATM Application. This is a command line application that mimics the actions of an ATM. Example: $ python app.py """ accounts = [ { "pin": 123456, "balance" : 1436.19}, { "pin" : 246802, "balance": 3571.87}, { "pin": 135791, "balance" : 543.79}, { "pin" : 123987, "balance": 25.89}, { "pin" : 269731, "balance": 3258.42} ] def login(user_pin): for account in accounts: if account ["pin"] == user_pin: print ("") return account["balance"] print("Wrong PIN") return False # Create the `login` function for the ATM application.
true
ba4c6bb212ce1374b4bf1779ae7b2fc415d6017b
ignis05/informatyka-python
/!KLASA_4/2.3.py
949
4.3125
4
# Napisz program, który sprawdzi położenie punktu względem odcinka. # Użytkownik podaje współrzędne początkowe i końcowe odcinka oraz współrzędne punktu. # Program należy zabezpieczyć przed podaniem współrzędnych określających długość odcinka równą 0. import math def distance(a,b): return math.sqrt((a.x - b.x)**2 + (a.y - b.y)**2) def is_between(a,c,b): return distance(a,c) + distance(c,b) == distance(a,b) class Point: def __init__(self, x, y): self.x = x self.y = y print('Podaj wspolrzedne odcinka:') a = Point(float(input('x1:')), float(input('y1:'))) b = Point(float(input('x2:')), float(input('y2:'))) print('Podaj wspolrzedne punktu:') c = Point(float(input('x1:')), float(input('y1:'))) if distance(a,b) == 0: print('Dlugosc odcinka wynosi 0') else: if is_between(a,c,b): print('Punkt nalezy do odcinka') else : print('Punkt nie nalezy do odcinka')
false
ac51a04b6213e9a8b96e8b1b5d8e4310b56a945a
sarahdepalo/python-classes
/pokemon.py
2,834
4.125
4
#Below is the beginnings of a very basic pokemon game. Still needs a main menu built in. Someday I'd like to add the ability to maybe find new pokemon and battle random ones! class Pokemon: def __init__(self, name, health, attack, defense): self.name = name self.health = health self.attack = attack self.defense = defense self.potions = 3 def attack_opponent(self, other_pokemon): # While loop that starts the battle while self.health > 0 or other_pokemon.health == 0: desire_to_attack = input("Do you want to attack? Yes or No? ") lower_desire_to_attack = desire_to_attack.lower() #If the user wants to attack do: if lower_desire_to_attack == "yes": other_pokemon.health = other_pokemon.health - (self.attack * 0.1) self.attack -= 5 self.health = self.health - (other_pokemon.attack * 0.1) print("%s's health has decreased to %d" % (other_pokemon.name, other_pokemon.health)) print("-----------") print("%s's attack has decreased to %d" % (self.name, self.attack)) print("%s attacked your pokemon. Your health fell to: %d" % (other_pokemon.name, self.health)) elif lower_desire_to_attack == "no": print(""" 1. Flee 2. Take Potion """) flee_or_potion = int(input("What do you want to do? Type 1 or 2." )) # Option for taking potions if flee_or_potion == 2: if self.potions > 0: self.health += 20 self.potions -= 1 print("Your pokemon's health is now at %d. You have %d potions left" % (self.health, self.potions)) else: print("You don't have any more potions.") # Option for fleeing the battle else: print("You have fled the battle.") self.health = 0 else: print("Please enter a valid option.") def list_stats(self): print("""%s's stats: Health: %d Attack: %d Defense: %d """ % (self.name, self.health, self.attack, self.defense)) running = True charizard = Pokemon("Charizard", 100, 120, 80) blastoise = Pokemon("Blastoise",100, 100, 110) charizard.attack_opponent(blastoise) # print("Welcome to Pokemon!") # while running: # print(""" # 1. View Pokemon's stats # 2. Fight another pokemon # 3. Exit # """) # user_input = int(input("What would you like to do? Select a number 1-3"))
true
7c744188e7d75ac5ecf083c29b5449c43928e11d
pasanchamikara/ec-pythontraining-s03
/numpy-tutorial/basics.py
1,205
4.46875
4
import numpy as np # Basics # a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # Create a rank 1 array # print(type(a)) # Prints "<class 'numpy.ndarray'>" # print(a.shape) # Prints "(3,)" # print(a) # | 1 2 3 4 | # | 5 6 7 8 | # print(a[0], a[1], a[2]) # Prints "1 2 3" # a[0] = 5 # Change an element of the array # print(a) # Prints "[5, 2, 3]" # print(a[0][1]) # a[0][2] = 7 # print(a) # print(a.shape) # b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array # print(b.shape) # Prints "(2, 3)" # print(b[0, 0], b[0, 1], b[1, 0]) # Important Cases # Create the following rank 2 array with shape (3, 4) # [[ 1 2 3 4] # [ 5 6 7 8] # [ 9 10 11 12]] a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print(a[1:3, 1:3]) # Use slicing to pull out the subarray consisting of the first 2 rows # and columns 1 and 2; b is the following array of shape (2, 2): # [[2 3] # [6 7]] # b = a[:2, 1:3] # A slice of an array is a view into the same data, so modifying it # will modify the original array. # print(a[0, 1]) # Prints "2" # b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1] # print(a[0, 1])
false
b2478988fed601e0c3b2bbcba70605d0940622b4
seshu141/20-Projects
/19th Program.py
715
4.125
4
# 19th program Find second biggest number of a list print(" enter the range of no. and stop") def Range(list1): largest = list1[0] largest2 = None for item in list1[1:]: if item > largest: largest2 = largest largest = item elif largest2 == None or largest2 < item: largest2 = item print("Largest element is:", largest) print("Second Largest element is:", largest2) # Driver Code # try block to handle the exception try: my_list = [] while True: my_list.append(int(input())) # if the input is not-integer, just print the list except: print(" The Range of no u enter are : ", my_list) Range(my_list)
true
40f42faa9ff184914e9725e845f69113d73634a2
stevenckwong/learnpython
/ex06.py
590
4.3125
4
#String formatting hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print (joke_evaluation.format(hilarious)) a = "Adam" b = "Bob" c = "Cathryn" friends = "There were once 3 friends named {}, {} and {}" print (friends.format(a,b,c)) # positioning of the variables corresponds to the location of the {} in the string bfgf = "{} and {} were in love and {} was jealous" print (bfgf.format(a,c,b)) bfgf2 = f"Because of this {b} left the group, and {a} and {c} broke up" print (bfgf2) w = "This is eh left side of .... " e = "a string with a right side." print (w + e)
true
9b67263e7c33c532840bd950c7fc055053e70cd7
stevenckwong/learnpython
/ex32.py
676
4.53125
5
#Loops and Lists the_count = [1,2,3,4,5] fruits = ['apples','oranges','pears','apricots'] change = [1,'pennies',2,'dimes',3,'quarters'] #the first kind of for loop that goes through a list for number in the_count: print(f"This is count {number}") for fruit in fruits: print(f"A fruit of type: {fruit}") # notice we have to use {} since we don't know what type of data is in the list for i in change: print(f"I got {i}") # we can also build lists, first starting with an empty one. elements = [] for i in range(0,6): print(f"Adding {i} to the list") elements.append(i) #now we can print them out too for i in elements: print (f"Element was: {i}")
true
66fa6d629d9ddfe80b4255e1ba72f95bff31ad4a
kwikl3arn/python-tutorial
/Python-Palindrome-Number.py
290
4.25
4
# Python Program for Palindrome Number num = int(input("Enter a number: ")) temp = num rev = 0 while num>0: remain = num % 10 rev = (rev * 10) + remain num = num // 10 if temp == rev: print("Number is palindrome") else: print("Number is not palindrome")
true
4a369bff7a8797951f2ab3c7af2fef2b4ae75ba3
CraGL/Hyperspectral-Inverse-Skinning
/PerVertex/util.py
2,478
4.21875
4
import re import numpy as np def veclen(vectors): """ return L2 norm (vector length) along the last axis, for example to compute the length of an array of vectors """ return np.sqrt(np.sum(vectors**2, axis=-1)) def normalized(vectors): """ normalize array of vectors along the last axis """ return vectors / veclen(vectors)[..., np.newaxis] def homogenize(v, value=1): """ returns v as homogeneous vectors by inserting one more element into the last axis the parameter value defines which value to insert (meaningful values would be 0 and 1) >>> homogenize([1, 2, 3]).tolist() [1, 2, 3, 1] >>> homogenize([1, 2, 3], 9).tolist() [1, 2, 3, 9] >>> homogenize([[1, 2], [3, 4]]).tolist() [[1, 2, 1], [3, 4, 1]] """ v = np.asanyarray(v) return np.insert(v, v.shape[-1], value, axis=-1) def dehomogenize(a): """ makes homogeneous vectors inhomogenious by dividing by the last element in the last axis >>> dehomogenize([1, 2, 4, 2]).tolist() [0.5, 1.0, 2.0] >>> dehomogenize([[1, 2], [4, 4]]).tolist() [[0.5], [1.0]] """ a = np.asfarray(a) return a[...,:-1] / a[...,np.newaxis,-1] def transform(v, M, w=1): """ transforms vectors in v with the matrix M if matrix M has one more dimension then the vectors this will be done by homogenizing the vectors (with the last dimension filled with w) and then applying the transformation """ if M.shape[0] == M.shape[1] == v.shape[-1] + 1: v1 = homogenize(v, value=w) return dehomogenize(np.dot(v1.reshape((-1,v1.shape[-1])), M.T)).reshape(v.shape) else: return np.dot(v.reshape((-1,v.shape[-1])), M.T).reshape(v.shape) def filter_reindex(condition, target): """ >>> indices = np.array([1, 4, 1, 4]) >>> condition = np.array([False, True, False, False, True]) >>> filter_reindex(condition, indices).tolist() [0, 1, 0, 1] """ if condition.dtype != np.bool: raise ValueError, "condition must be a binary array" reindex = np.cumsum(condition) - 1 return reindex[target] def tryint(s): try: return int(s) except: return s def alphanum_key(s): """ Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [ tryint(c) for c in re.split('([0-9]+)', s) ] def sort_nicely(l): """ Sort the given list in the way that humans expect. """ l.sort(key=alphanum_key)
true
3667fe3935484f27411ba2d9522f282b98cd9d26
adsr652/Python
/fact2.py
534
4.1875
4
def recu_fact(num): if num==1: return num else: return num * recu_fact(num-1) num= int(input("Enter any no. : ")) if num < 0: print("Factorial cannot be found for negative integer") print("Reenter the value again ") num= int(input("Enter any no. : ")) if num==0: print("Factorial of 0 is 1") else: print("Factorial of", num, "is: ", recu_fact(num)) elif num==0: print("Factorial of 0 is 1") else: print("Factorial of", num, "is: ", recu_fact(num))
true
6c8cb118721a066d8d31a7df10d030c5371a36f4
Phyopyosan/Exercises
/If_Else_Statements.py
2,063
4.15625
4
#Boolean Expression print(20 > 10) print(20 == 10) print(20 < 10) print(bool("Hello World")) print(bool(20)) Python Condition Equals -> x == y Not Equals -> x != y Less Than -> x < y Less Than or Equals to -> x <= y Greater than -> x > y Grater than or equal to -> x >= y Boolean OR -> x or y , x | y Boolean AND -> x and y , x & y Boolean NOT -> not x #if statement x = 70 y = 60 if x > y: print("x is grater than y") if x < y: print(" x is not grater than y") elif x == y: print("x is equal to y") elif x > y: print("x is grater than y") elif x != y: print("x is not equal to y") elif y < x: print("y is smaller than x") else: print("x is grater than y") #short hand if if x > y: print("x is grater than y") x= 50 y = 150 if x > y: print("x is grater than y") elif x ==y : print("x is equal to y") else: print("xis less than y") print(x) if x > y else print(y) #And is logical operator x = 50 y = 40 z = 100 if x > y and z > x: print("All Condition are True") #Or logical operator x = 50 y = 40 x = 100 if x > y or z > y: print("one of the Condition is true") elif x > y and z > y: print ("All Condition are true") else: print("nothing else") if x > y and z < y or x < y: print("Line No1 is True") elif x < x or y < x or z == y: print("Line No2 is true") elif z > y and x > y and x!= y : print("Line No 3 is true") else: print("Nothing else") #Nested If is if statement in if statement x = 50 if x > 10: print("x is ten") if x > 20: print("x is grater than 20") else: print("No, x is not grater than 20") elif x < 10: print("x is small") if x < 5: print("x is small than 5") else: print("No, x is nothing") else: print("x is biggest") #Pass Statement x = 100 y = 50 if x > y : Pass if x > y : print("x is grater than 10 and 20") pass print("x is not grater than 10 & 20 ")
false
ef7bf55fa66a02245c45f2d263a69ee811ffbb7f
PatrickWMoore88/htx-immersive-08-2019
/02-week/1-tuesday/labs/patrick-moore/patrickwmoore88-phonebook.py
2,509
4.3125
4
#Phone Book App #Phonebook phonebook = { 'A':{'Alex': '123-456-7890', 'Amy': '234-567-8901'}, 'B':{'Brian': '345-678-9012', 'Bobby': '456-789-0123'}, 'C':{'Chelsea': '567-890-1234', 'Candy': '678-901-2345'}, 'D':{'Derrick': '789-012-3456', 'Donnie': '890-123-4567'}, 'E':{'Erik': '901-234-5678', 'Erin': '012-345-6789'} } #Opening interface print("\n========================== \n Electronic Phone Book \n========================== \n 1. Look up an entry \n 2. Set an entry \n 3. Delete an entry \n 4. List all entries \n 5. Quit") print("==========================") #Make your selection selection = "" while selection != 5: selection = int(input("Please select an option #: ")) #Selection Option 1: Search if selection == 1: search_name = str(input("Please input name: ")) print("====================") print(f"Name: {search_name}") for letter in search_name[0]: print(f"Phone Number: {phonebook[letter][search_name]}") print("====================") #Selection Option 2: Add elif selection == 2: add_name = str(input("What name would you like to add?: ")) add_number = str(input("Please enter phone number: ")) print("====================") print(f"Name: {add_name}") for letter in add_name[0]: if letter not in phonebook.keys(): phonebook[letter]= {add_name: add_number} phonebook[letter][add_name] = add_number print(f"Phone Number: {phonebook[letter][add_name]}") print(f"Entry stored for {add_name}.") print("====================") #Selection Option 3: Remove elif selection == 3: remove_name= str(input("What name would you like to remove?: ")) print("====================") print(f"Name: {remove_name}") for letter in remove_name[0]: del phonebook[letter][remove_name] print(f"Entry for {remove_name} has been removed.") print("====================") #Selection Option 4: List All Entries elif selection == 4: for key, value in phonebook.items(): print(f"{key}: ") print("--") for key, value in phonebook[key].items(): phonebook_list = f"{str(key)}: {value}" print(phonebook_list) print("------------------") print("====================") #Selection Option 5: Quit else: print("Thanks! Come back soon!")
false
7bf3ded502ca212e55ebdb24b40b27cdf9c020df
shillwil/cs-module-project-iterative-sorting
/src/searching/searching.py
908
4.125
4
def linear_search(arr, target): # Your code here if len(arr) is not 0: for i in range(len(arr)): if arr[i] == target: return i return -1 return -1 # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here if len(arr) is not 0: lowest = 0 highest = len(arr) - 1 return binary_search_helper(arr, target, highest, lowest) else: return -1 def binary_search_helper(arr, target, highest, lowest): mid_range = ((lowest + highest) / 2).__round__() if arr[mid_range] < target: return binary_search_helper(arr, target, highest, mid_range) elif arr[mid_range] > target: return binary_search_helper(arr, target, mid_range, lowest) else: if arr[mid_range] == target: return mid_range else: return -1
true
3feb8418eda00072433c911fc79984ff78cb77ba
799898961/python-learn-note
/python学习笔记/第6章-循环控制/6.1遍历循环.py
1,029
4.21875
4
# 6.1遍历循环.py # 字符串遍历: for c in "python123": print(c, end=",") print() # 列表遍历: for item in [123, "python", 456]: print(item, end=",") print() # 遍历某个结构形成的循环运行方式 # for <循环变量> in <遍历结构>: # <语句块> # 每次循环,能从遍历结构中逐一提取元素,放在循环变量里 # 并执行一次语句块 # 计数循环n次 # for i in range(n): # <语句块> # 遍历由range()函数产生的数字序列,产生循环 # 计数循环 特定次 # for i in range(m,n,k): # <语句块> # m —— 起始数字 n —— 终止数字 k —— 步长 # 循环次数:(n-m)次 # 字符串遍历循环 # for c in s: # <语句块> # 列表遍历循环 # for item in ls: # <语句块> # ls是一个列表,遍历其每一个元素,产生循环 # 文件遍历循环 # for line in fi: # <语句块> # fi是一个文件标识符,遍历其每行,产生循环
false
ec747b85a18d2962577e2e24547981b3d70be38b
kemar1997/TSTP_Programs
/Chapter13_TheFourPillarsOfObjectOrientedProgramming/Inheritance.py
2,766
4.90625
5
""" Inheritance in programming is similar to genetic inheritance. In genetic inheritance, you inherit attributes like eye color from your parents. Similarly, when you create a class, it can inherit methods and variables from another class. The class that is inherited from is the parent class, and the class that inherits is the child class. In this section, you will model shapes using inheritance. Here is a class that models a shape: """ class Shape: def __init__(self, w, l): self.width = w self.len = l def print_size(self): print("""{} by {} """.format(self.width, self.len)) my_shape = Shape(20, 25) my_shape.print_size() """ With this class, you can create Shape objects with width and len. In addition, Shape objects have the method print_size, which prints their width and len. You can define a child class that inherits from a parent class by passing the name of the parent class as a parameter to the child class when you create it. The following example creates a Square class that inherits from the Shape class: """ # class Square(Shape): # pass # # # a_square = Square(20,20) # a_square.print_size() # >> 20 by 20 """ Because you passed the Shape class to the Square class as a parameter; the Square class inherits the Shape class's variables and methods. The only suite you defined in the Square class was the keyword pss, which tells Python not to do anything. Because of inheritance, you can create a Square object, pass it a width and length, and call the method print_size on it without writing any code (aside from pass) in the Square class. This reduction in code is important because avoiding repeating code makes your program smaller and more manageable. A child class is like any other class; you can define methods and variables in it without affecting the parent class: """ # class Square(Shape): # def area(self): # return self.width * self.len # # # a_square = Square(20, 20) # print(a_square.area()) """ When a child class inherits a method from a parent class, you can override it by defining a new method with the same name as the inherited method. A child class's ability to change the implementation of a method inherited from its parent class is called method overriding. """ class Square(Shape): def area(self): return self.width * self.len def print_size(self): print("""I am {} by {} """.format(self.width, self.len)) a_square = Square(20, 20) a_square.print_size() """ In this case, because you defined a method named print_size, the newly defined method overrides the parent method of the same name, and it prints a new message when you call it. """
true
ced65aca9c260388d36e6d84939b29e3d60660c2
kemar1997/TSTP_Programs
/Loops/range.py
750
4.90625
5
""" You can use the built-in range function to create a sequence of integers, and use a for-loop to iterate through them. The range function takes two parameters: a number where the sequence starts and a number where the sequence stops. The sequence of integers returned by the range function includes the first parameter (the number to start at), but not the second parameter (the number to stop at). Here is an example of using the range function to create a sequence of numbers, and iterate through them: """ for i in range(1, 11): print(i) """ In this example, you used a for-loop to print each number in the iterable returned by the range function. Programmers often name the variable used to iterate through a list of integers i. """
true
52c6816d339f1140d7da3fd7c97c9df468084f7f
kemar1997/TSTP_Programs
/String_Manipulation/Concatenation.py
321
4.25
4
""" You can add two (or more) strings together using the addition operator. HTe result is a string made up of the characters from the first string, followed by the characters from the next string(s). Adding strings together is called concatenation: """ print("cat" + "in" + "hat") print("cat" + " in" + " the" + " hat")
true
56329c35e37e044922969f696523bd39b76281fb
kemar1997/TSTP_Programs
/Challenges/Ch12_Challenges/Triangle.py
565
4.1875
4
# Create a Triangle class with a method called area that calculates and returns # its area. Then create a Triangle object, call area on it, and print the result. # a,b,c are the sides of the triangle class Triangle(): def __init__(self, a, b, c): self.s1 = a self.s2 = b self.s3 = c def area(self): # calculcate the semi-perimeter s = (self.s1 + self.s2 + self.s3) / 2 # calculate the area return (s*(s-self.s1)*(s-self.s2)*(s-self.s3)) ** 0.5 triangle = Triangle(5, 6, 7) print(triangle.area())
true
17601476e7b674a9900d695a47a4cecc327ae2cf
kemar1997/TSTP_Programs
/Challenges/Ch13_Challenges/Challenge4.py
415
4.34375
4
""" Create a class called Horse and a class called Rider. Use composition to model a horse that has a rider """ class Horse: def __init__(self, name, owner): self.name = name self.owner = owner class Rider: def __init__(self, name): self.name = name john = Rider("John Whitaker") jaguar = Horse("Jaguar", john) print(jaguar.owner.name)
true
25da8767ef0a8ec27bfc216ca40c4cdf9967adf9
kemar1997/TSTP_Programs
/Challenges/Ch4_Challenges/ch4_challenge1.py
236
4.25
4
""" 1. Writing a function that takes a number as an input and returns that number squared. """ def square_a_number(): num = input("Enter a number: ") num = int(num) return num*num result = square_a_number() print(result)
true
9b7c6e30ca621c5796db893acbb3eab3a7b7d1f5
paskwal/python-hackerrank
/Basic_Data_Types/04_finding_the_percentage.py
1,169
4.21875
4
# -*- coding: utf-8 -*- # # (c) @paskwal, 2019 # Problem # You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. # The marks can be floating values. The user enters some integer N followed by the names and marks for N students. # You are required to save the record in a dictionary data type. The user then enters a student's name. # Output the average percentage marks obtained by that student, correct to two decimal places. # Input Format # The first line contains the integer N, the number of students. The next N lines contains the name and marks obtained by that student # separated by a space. The final line contains the name of a particular student previously listed. def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() if query_name in student_marks.keys(): print("%.2f" % mean(student_marks[query_name]))
true
3c530015d9a9088feb6ce024b49fc3cd51717ba9
shobha-bhagwat/Python
/games/RockPaperScissors.py
1,554
4.15625
4
import random rock = 1 paper = 2 scissors = 3 names = {rock: "Rock", paper: "Paper", scissors: "Scissors"} rules = {rock: scissors, paper: rock, scissors: paper} player_score = 0 computer_score = 0 def start(): print("Lets play Rock, Paper, Scissors!!") while game(): pass scores() def game(): player = move() computer = random.randint(1, 3) result(player, computer) return play_again() def move(): while True: player = input("1: Rock\n2: Paper\n3: Scissors\nMake your move: ") try: player = int(player) if player in (1, 2, 3): return player except ValueError: print("Please enter 1, 2 or 3") def result(player, computer): global player_score, computer_score print("Computer's move: {}".format(names[computer])) if player == computer: print("Tie!!") else: if rules[player] == computer: print("You win!! :)") player_score += 1 else: print("Sorry, you lost! :(") computer_score += 1 def play_again(): answer = input("Would you like to play again (y/n): ") if answer in ('y', 'Y', 'yes', 'YES', 'Yes'): return answer else: print("Thanks for playing the game!") def scores(): global player_score, computer_score print("---------- FINAL SCORES ----------------") print("Computer: {}".format(computer_score)) print("You: {}".format(player_score)) if __name__ == '__main__': start()
true
3eed1469ae90561bb9a21487579d822b21d09f8b
shobha-bhagwat/Python
/algorithms/binarySearch.py
440
4.125
4
def binarySearch(arr, start, end, x): while start <= end: mid = (start + end)//2 if arr[mid] == x: return mid elif arr[mid] < x: start = mid + 1 else: end = mid -1 return -1 arr = [-5, 3.0, 10, 20, 50, 80] x = 3 result = binarySearch(arr, 0, len(arr), x) print(result) arr = [0, 1, 0] #### doesn't work correctly if multiple instances of a number present
true
5d321e674e79ec3037a4831fa1be766fe26a8aab
celusta/Python
/mookwl_P2Q4.py
312
4.125
4
# Filename: mookwl_P2Q4.py # Name: Marcus Mook Wei Lun # Description: Determine whether the input year is a leap year # Prompt user for year year = int(input("Enter year:")) # Display result if year%4 == 0 and year%100 != 0 or year%400 == 0 : print(year, "is a leap year.") else : print(year, "is not a leap year.")
false
1a257fddb2c63d53423544a9737d3dca62e85968
xperrylinn/whiteboard
/algo/easy/branch_sums.py
1,328
4.1875
4
# Write a function that takes in a Binary tree and retuns a list of # its branch sums ordered from leftmost branch to rightmost branch # # A branch is the sum of all values in a Binary Tree branch. A # binary tree branch is a path of nodes in a tree that starts at the # root and ends at any leaf # This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def branchSums(root): return branchSumsHelper(root, 0, []) def branchSumsHelper(root, s=0, output=[]): if root == None: return else: if root.left == None and root.right == None: output.append(s + root.value) else: branchSumsHelper(root.left, s + root.value, output) branchSumsHelper(root.right, s + root.value, output) return output # Notes: # - O(n) Time | O(n) Space # -- time: we need to touch each of the n node. At every node constant time # operations. # -- space: aside from the recusrive calls on the stack, we are returning # a list sums and there are roughly 1/2 leaf nodes as there are nodes # - The question is asking you determine the sum of node values from # root to each left, orderd left to right. # -- Left to right is achieved by choosing pre-order traversal of tree
true
9ae2ccf4e88e93d0c47565cd6b0b9d18825faa2f
supercp3/code_leetcode
/basedatestructure/stack_run_class.py
822
4.15625
4
class Node: def __init__(self,value): self.value=value self.next=None class Stack: def __init__(self): self.top=None def push(self,value): node=Node(value) node.next=self.top self.top=node def pop(self): node=self.top if node is None: raise Exception("this is an empty stack") self.top=node.next return node.value def peek(self): node=self.top if node is None: raise Exception("this is an empty stack") return node.value def is_empty(self): return not self.top def size(self): node=self.top count=0 if node is None: raise Exception("this is an empty stack") while node is not None: count+=1 node=node.next return count if __name__=="__main__": stack=Stack() stack.push(2) stack.push(3) print(stack.peek()) print(stack.is_empty()) print(stack.size())
true
877ee9220c82d773f6b8e7e83b281e1be3b455dc
vedashri15/new1
/Basic1.6.py
717
4.84375
5
#Write a Python program to accept a filename from the user and print the extension of that. filename = input("Input the Filename: ") f_extns = filename.split(".") print ("The extension of the file is : " + f_extns[-1]) #The function returns a list of the words of a given string using a separator as the delimiter string. #If maxsplit is given, the list will have at most maxsplit+1 elements. #If maxsplit is not specified or -1, then there is no limit on the number of splits. #If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings. #The sep argument may consist of multiple characters. #Splitting an empty string with a specified separator returns [''].
true
85c53dbee3db530435a9f69c43fac32606b6b476
tonylattke/python_helpers
/5_functions_methods.py
1,154
4.34375
4
######################## Example 1 - Create a function and using ######################## # Even or not # @number : Number to decide # @return : True if the number is even, otherwise Flase def even(number): return number % 2 == 0 # Testing Function for aux in xrange(0,10): if even(aux): print "%d - Even" % aux else: print "%d - Odd" % aux ################################# Example 2 - Recursion ################################# # Factorial of number # @number : Number # @return : Factorial value of number def factorial(value): if (value <= 1): return 1 return value * factorial(value -1) # Fibonacci # @value : Number # @return : Fibonacci value def fibonacci(value): if value == 0: return 0 elif value == 1: return 1 else: return fibonacci(value-1)+fibonacci(value-2) # Testing Function number = 7 print 'Factorial of %d is %d' % (number,factorial(number)) print 'Fibonacci of %d is %d' % (number,fibonacci(number)) #################################### Example of main #################################### import sys def main(): params = sys.argv print params print 'Here is the main' if __name__ =='__main__': main()
true
8f6f34a49a9920138306f43dca03aaf9d4952df3
MilanaShhanukova/programming-2021-19fpl
/shapes/circle.py
803
4.125
4
""" Programming for linguists Implementation of the class Circle """ from math import pi from shapes.shape import Shape class Circle(Shape): """ A class for circles """ def __init__(self, uid: int, radius: int): super().__init__(uid) self.radius = radius def get_area(self): """ Returns the area of a circle :return int: the area of a circle """ return self.radius **2 * pi def get_perimeter(self): """ Returns the perimeter of a circle :return int: the perimeter of a circle """ return self.radius * pi * 2 def get_diameter(self): """ Returns the diameter of a circle :return int: the diameter of a circle """ return 2 * self.radius
true
1c14f80470bc5c858587261c932b8fe958f1b1c3
yvonneonu/Test8
/test8.py
774
4.34375
4
# A Simple Python 3 program to compute # sum of digits in numbers from 1 to n #Returns sum of all digits in numbers from 1 to n def countNumberWith3(n) : result = 0 # initialize result # One by one compute sum of digits # in every number from 1 to n for x in range(1, n + 1): if(has3(x) == True): result = result + 1 return result # A utility function to compute sum # of digits in a given number x def has4(x): while (x != 0): if (x%10 ==4): return True x = x //10 return False # Driver Program n = 35 print ("Count of numbers from 1 to ", n, " that has 3 as a digit is", countNumbersWith3(n))
true
0efc63ac7d07f35ae5d978169adb8849f175bad4
eawww/BI_HW
/HW1/seqid.py
2,201
4.125
4
#Bridget Mohn and Eric Wilson #CS 466R #Homework 1 #Reads an input filename from command line, opens the file, reads each character #in the file to see whether the file contains a DNA, RNA, or Protein sequence import sys #Input filename is taken from the command line which is the second argument InputFile = sys.argv[1] #Opens the file read from the command line fin = open(str(InputFile), "r") #Array and array length needed to turn the lines in the file one string temp = [] sequence_length = 80 sequence = "" #To take the header off of the biological sequence for line in fin.readlines(): #Add each line in the file into the array temp.append(line) #Delete the first line since it's not apart of the sequence del temp[0] #Put all the lines of the file into one big string for line in temp: modified_line = line.strip() sequence = sequence + modified_line seq_type = "" for char in sequence: #Checks if U is in the sequence since it is unique to RNA if('U' in line): #print("RNA") seq_type = "RNA" #Checks the file for all of the possible amino acid codes that make a protein elif('B' in line or 'D' in line or 'E' in line or 'F' in line or 'H' in line or 'I' in line or 'K' in line or 'L' in line or 'M' in line or 'N' in line or 'Q' in line or 'X' in line or 'R' in line or 'S' in line or 'P' in line or 'V' in line or 'W' in line or 'Y' in line or 'Z' in line): #print("Protein") seq_type = "Protein" #Checks if T is in the sequence since it is only found in DNA and Protein elif('T' in line): #print("DNA or Protein") seq_type = "DNA or Protein" #If just A, G, and C are found in the sequence then it could be any of the options elif('A' in line and 'G' in line and 'C' in line): #print("DNA or RNA or Protein") seq_type = "DNA or RNA or Protein" #If none of those are found in the sequence then it is none of the above else: #print("None") seq_type = "None" print(seq_type) #Close input file fin.close()
true
43af2548dc114926d4484a64679589929aa3f22a
cifpfbmoll/practica-5-python-joseluissaiz
/P5E10.py
768
4.21875
4
#Practica 5 # Ejercicio 10 # Escribe un programa que pida la altura de un triángulo y lo # dibuje de la siguiente manera: # #--------Variables numeroLinea = 1 # #---------Imports import sys #---------Inputs altura = input("Introduce la altura del triangulo : ") try: altura = int(altura) except ValueError: print ("Valor no valido") sys.exit() # espacios = altura -1 # #--------Mostrar Menu print("") print("") print("ESTE ES TU TRIANGULO BONITO") print("") #--------Logic for numeroIntermedio in range(altura): for i in range(espacios): print(" ",end='') for i in range(numeroLinea): print("*",end='') print("") numeroLinea += 2 espacios -= 1
false
504b89011418c1661929552c52e3fe9842f7ad52
cifpfbmoll/practica-5-python-joseluissaiz
/P5E3.py
1,277
4.34375
4
# Practica 5 # Ejercicio 3 # Escribe un programa que pida dos números y escriba la suma de enteros # desde el primero hasta el último. # # #------------------------imports import sys # #------------------------variables numeroCuenta = 0 numeroCuentaMostrar = "" # #------------------------inputs #numUno numUno = input ("Introduce un numero :") # #comprobacion de numUno try: numUno = int(numUno) except ValueError: print ("El valor uno no procede") sys.exit() # #numDos numDos = input ("Introduce otro numero mayor que " + str(numUno) + " :") # #comprobacion de numDos try: numDos = int(numDos) except ValueError: print ("El valor dos no procede") sys.exit() # # if numDos <= numUno: print ("El valor introducido es inferior o igual al anterior") sys.exit() # # # #-----------------------logic for numeroIntermedio in range(numUno,(numDos + 1)): numeroCuenta += numeroIntermedio if numeroIntermedio == numDos: print ("La suma desde " + str(numUno) + " hasta " + str(numDos) + \ " es : " + str(numeroCuenta) ) numeroCuentaMostrar += str(numeroIntermedio) print (numeroCuentaMostrar + " = " + str(numeroCuenta)) else: numeroCuentaMostrar += str(numeroIntermedio) + " + "
false
3267bcaa907a1eda60abe8c60ff69b7cc7cff0a9
Ryan-Lawton-Prog/IST
/IST Assessment Program/I1.py
2,768
4.28125
4
def a(): while = True: print """ \tGuide Contents: \t* raw_input() = Gives the user the option to input data to the user, anything inbetween the '()' will be displayed before the users input. """ raw_input() break test = True while test: print "print \"How old are you?\"," a = raw_input("> ") if a == "print \"How old are you?\",": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "age = raw_input()" b = raw_input("> ") if b == "age = raw_input()": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "print \"How tall are you?\"," c = raw_input("> ") if c == "print \"How tall are you?\",": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "height = raw_input()" d = raw_input("> ") if d == "height = raw_input()": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "print \"How much do you weigh?\"," e = raw_input("> ") if e == "print \"How much do you weigh?\",": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "weight = raw_input()" f = raw_input("> ") if f == "weight = raw_input()": test = False print "" else: print "Please Check Over Your Code" print "" test = True while test: print "print \"So, you're %r old, %r tall and %r heavy.\" % (age, height, weight)" g = raw_input("> ") if g == "print \"So, you're %r old, %r tall and %r heavy.\" % (age, height, weight)": test = False print "" else: print "Please Check Over Your Code" print "" print "You have wrote" print "" print a print b print c print d print e print f print g Exit = raw_input() print "This is what would happen if you ran it." print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
true
9bc1edb29c6feb34e3384611c3353014579821d0
Ryan-Lawton-Prog/IST
/IST Assessment Program/Run.py
1,632
4.15625
4
import Beginner # Program Varriable is now True Program = True # 'while' Program is true run and loop this while Program: # select your difficulty text print "Please select your Stream" print "Beginner:" print "Intermediate:" print "Advanced:" # difficulty input Difficulty = raw_input("> ") # 'if' difficulty is 'Beginner': if Difficulty == "Beginner": print "Please select your exercise" print """ \t* Intro: \t* 1: A Good First Program \t* 2: Comments And Pound Characters \t* 3: Numbers And Math \t* 4: Variables And Names \t* 5: More Variables And Printing \t* 6: Strings And Text \t* 7: More Printing \t* 8: Printing, Printing \t* 9: Printing, Printing, Printing \t* 10: What Was That """ ExerciseB = raw_input("> ") Beginner.run(ExerciseB) # 'if' difficulty is 'Intermediate': elif Difficulty == "Intermediate": print "Please select your exercise" print """ \t* Intro: \t* 1: \t* 2: \t* 3: \t* 4: \t* 5: \t* 6: \t* 7: \t* 8: \t* 9: \t* 10: """ ExerciseI = raw_input("> ") Beginner.run(ExerciseI) # 'if' difficulty is 'Advanced': elif Difficulty == "Advanced": print "Please select your exercise" print """ \t* Intro: \t* 1: \t* 2: \t* 3: \t* 4: \t* 5: \t* 6: \t* 7: \t* 8: \t* 9: \t* 10: """ ExerciseA = raw_input("> ") Beginner.run(ExerciseA) # if no 'if' or 'elif' statments are run, run this: else: print "Invalid" # repeat to beggining of program Program = True
true
5cbe7b44640c6d2c81d1d791e9c5f057b59c03fc
huytranvan2010/Python-Tutotial
/OOP/inheritance.py
1,497
4.21875
4
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) # Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() """ Tạo class kế thừa từ class Person """ class Student(Person): pass # khi ko muốn add thêm attribute hay methods nào, kế thừa toàn bộ base class x = Student("Mike", "Olsen") x.printname() class Student(Person): def __init__(self, fname, lname): # có self ở đây để còn lưu attribute cho object Person.__init__(self, fname, lname) x = Student("John", "Doe") x.printname() # thêm attribute class Student(Person): def __init__(self, fname, lname, age): # có self ở đây để còn lưu attribute cho object # Phải dùng self không sẽ báo lỗi Person.__init__(self, fname, lname) self.age = age def printage(self): print(self.age) x = Student("John", "Doe", 15) x.printname() x.printage() # sử dụng super() function sẽ làm cho class con kế thừa tất cả phương thức và thuộc tính của class cha class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) # sử dụng super sẽ không cần tên của class cha, ở đây ko cần dùng self anh = Student("Huy", "Tran") anh.printname()
false
40917733d3f5c754297756d8e440bdb2c96d5607
calvinwalterheintzelman/Computer-Security-Algorithms
/Finding Primes/Fields.py
1,307
4.125
4
# Calvin Walter Heintzelman # ECE 404 # Homework 3 # Python 3.7.2 import os import sys print("Please enter a small digit: ") number = input() while(number.isdigit() is False or int(number) < 1): print("Error! Please only input a single small positive integer!") number = input() if(int(number) >= 50): print('Warning! The input is not that small. Are you sure you want to input an integer that is 50 or greater?') print('Please anser "y" or "n"') continue_running = input() while(not(continue_running == 'y' or continue_running == 'n')): print('Error! Please enter "y" or "n"') continue_running = input() if continue_running == 'n': print('Please enter a number less than 50') number = input() while(number.isdigit() is False or int(number) >= 50 or int(number) < 1): print('Error! Please only input a positive single integer that is less than 50') number = input() number = int(number) test_prime = 2 is_prime = True if number == 1: is_prime = False while(test_prime <= number/2): possible_factor = number % test_prime if possible_factor == 0: is_prime = False break test_prime += 1 if is_prime is True: print('field') else: print('ring')
true
42efd486938984bf55bb1699472c9abca16e3106
Pratik180198/Every-Python-Code-Ever
/factorial.py
480
4.375
4
num1=input("Enter number: ") try: num=int(num1) fact=1 for i in range(1,num+1): #Using For Loop fact=fact*i print("Factorial of {} is {}".format(num,fact)) #For Loop Answer def factorial(num): #Using Recursive Method if num == 0 or num ==1: return 1 else: return num * factorial(num-1) print(f"Factorial of {num} is {factorial(num)}") #Recursive Method Answer except: print("Please enter only integer")
true
e37e9102d0cf0c191ee4b78bee54a22920f510c4
z21mwKYq/Python
/Lesson1/les1_task5.py
376
4.1875
4
# Пользователь вводит номер буквы в алфавите. Определить, какая это буква. num = int(input("Ввдеите порядковый номер буквы")) if (num > 26 or num < 1): print("Нет буквы с таким порядковым номером") exit(0) print(f"Эта буква - {chr(num+96)}")
false
1af7bd227c2e2a919baeda39d55c27d631b93908
maimumatsumoto/prac04
/list_exercises.py
2,474
4.28125
4
#//1. Basic list operations//# numbers=[] for i in range(5): value= int(input("Number: ")) numbers.append(value) print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) print("The smallest number is {}".format(min(numbers))) print("The largest number is {}".format(max(numbers))) print("The average of the numbers is {}".format(sum(numbers)/5)) #//2. Woefully inadequate security checker//# usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] username= input("Enter your username") if username in usernames: print("Access granted") if not username in usernames: print("Access denied") #//3. List comprehensions//# """ CP1404/CP5632 Practical List comprehensions """ names = ["Bob", "Angel", "Jimi", "Alan", "Ada"] full_names = ["Bob Martin", "Angel Harlem", "Jimi Hendrix", "Alan Turing", "Ada Lovelace"] # for loop that creates a new list containing the first letter of each name first_initials = [] for name in names: first_initials.append(name[0]) print(first_initials) # list comprehension that does the same thing as the loop above first_initials = [name[0] for name in names] print(first_initials) # list comprehension that creates a list containing the initials # splits each name and adds the first letters of each part to a string full_initials = [name.split()[0][0] + name.split()[1][0] for name in full_names] print(full_initials) # one more example, using filtering to select only the names that start with A a_names = [name for name in names if name.startswith('A')] print(a_names) # TODO: use a list comprehension to create a list of all of the full_names in lowercase format #for i in range(len(full_names)): # full_names[i]=full_names[i].lower() #print(full_names) lowercase_full_names =[name.lower() for name in full_names] print(lowercase_full_names) almost_numbers = ['0', '10', '21', '3', '-7', '88', '9'] # TODO: use a list comprehension to create a list of integers from the above list of strings numbers = [int(i) for i in almost_numbers] print(numbers) # TODO: use a list comprehension to create a list of only the numbers that are greater than 9 from the numbers (not strings) you just created greater_9 = [number for number in numbers if number>9] print(greater_9)
true
32aa4728228b484ee7688709d0afccabcda6b64e
Andrest07/26th-27th_Nov_2019
/Practice_Assorted_Problem/Num_14.py
1,026
4.15625
4
def makeForming(verb): if verb.endswith("ie"): verb = verb[0:len(verb)-2] + "ying" elif verb.endswith("e") and not verb == "be" and not verb == "see" and not verb == "flee" and not verb == "knee": verb = verb[0:len(verb)-1] + "ing" elif (verb.endswith("a") or verb.endswith("o") or verb.endswith("e") or verb.endswith("i") or verb.endswith("u"))\ and (not verb[len(verb)-2: len(verb)-1] == "a" or not verb[len(verb)-2: len(verb)-1] == "o" or not verb[len(verb)-2: len(verb)-1] == "e" or not verb[len(verb)-2: len(verb)-1] == "i" or not verb[len(verb)-2: len(verb)-1] == "u") and (verb[len(verb)-3: len(verb)-2] == "a" or verb[len(verb)-3: len(verb)-2] == "o" or verb[len(verb)-3: len(verb)-2] == "e" or verb[len(verb)-3: len(verb)-2]== "i" or verb[len(verb)-3: len(verb)-2] == "u"): verb = verb + verb[len(verb)-1] + "ing" else: verb = verb + "ing" print("Result: " + verb) makeForming(input("Please input the word: "))
false
d7a241d07e554b6b0b56913e51aa3a853ee5c6b9
gagnongr/Gregory-Gagnon
/Exercises/sum up odd ints.py
718
4.40625
4
# Sum up a series of even numbers # Make sure user input is only even numbers # Variable names without types are integers print("Allow the user to enter a series of even integers. Sum them.") print("Ignore non-even input. End input with a '.'") # Initialize input number and the sum number_str = input("Number: ") the_sum = 0 # Stop if a period (.) is entered # remember, number_str is a string until we convert it while number_str != ".": number = int(number_str) if number % 2 == 1: # number is not even (it is odd) print ("Error. Only even numbers, please.") number = int(0) else: the_sum += number number_str = input("Number: ") print ("The sum is: ", the_sum)
true
9fc52b2e6a2a43c2aa277e491f72319e29ba6a68
CodecoolBP20161/python-pair-programming-exercises-2nd-tw-toti_aron
/listoverlap/listoverlap_module.py
469
4.1875
4
def listoverlap(list1, list2): common_elements = [] for i in list1: for j in list2: if i == j and j not in common_elements: common_elements.append(j) return common_elements def main(): list1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] common_elements = listoverlap(list1, list2) print(common_elements) return if __name__ == '__main__': main()
false
f55ae7e36f0430c48633e5b032f0adf57c57c9b0
cserajeevdas/Python-Coding
/decorator.py
701
4.5625
5
#assigned a method to a variable and called the method # def f1(): # print("in f1") # x = f1 # x() #calling f2 from the rturn value of f1 # def f1(): # def f2(): # print("in f2") # return f2 # x = f1() # x() #calling the nested method through passed method # def f1(f): # def f2(): # print("before function call") # f() # print("after function call") # return f2 # def f3(): # print("this is f3") # x = f1(f3) # x() #creating the decorator function def f1(f): def f2(): print("before function call") f() print("after function call") return f2 @f1 def f3(): print("this is f3") f3()
true
fcdd687866bc08111a796b3f9650b6317c665049
LucasEvo/Estudos-Python
/ex022.py
690
4.3125
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # 1- O nome com todas a letras minúsculas # 2- O nome com todas a letras maiúsculas # 3- Quantas letras ao todo (sem considerar espaços). # 4- Quantas letras tem o primeiro nome. nome = str(input('Qual seu nome completo? R: ')).strip() print('Seu nome é {}.'.format(nome)) print('Seu nome com todas as letras maiúsculas é {}.'.format(nome.upper())) print('Seu nome com todas as letras minúsculas é {}.'.format(nome.lower())) print('Seu nome todo tem {} letras.'.format(len(nome) - nome.count(' '))) primeiro_nome = nome.split() print('Seu primeiro nome tem {} letras.'.format(len(primeiro_nome[0])))
false
1089725bb18a94128e2bf06a80ac8bd7ee1074db
BaiMoHan/LearningPython_ING_202002
/Part4/gobang.py
1,495
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/13 14:45 # @Author : Baimohan/PH # @Site : https://github.com/BaiMoHan # @File : gobang.py # @Software: PyCharm # def Count(radium): # from math import pi as p # C = 2 * p * radium # A = p * radium ** 2 # return C, A # # # if __name__ == '__main__': # radium = int(input('Please enter radium:')) # Circumference, area = Count(radium) # print('Circumference is %.2f' % (Circumference)) # print('Round area is %.2f' % (area)) # 定义棋盘的大小 BOARD_SIZE = 15 # 定义一个二维列表来充当棋盘 board = [] def initboard(): # 为每个元素赋值'✛',用于控制台画出棋盘 for i in range(BOARD_SIZE): row = ['✛'] * BOARD_SIZE board.append(row) # 在控制台输出棋盘 def printBoard(): # 打印每个列表元素 for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): # 打印列表元素后不换行 print(board[i][j],end='') # 每打印完一行输出一个换行 print() if __name__ == '__main__': initboard() printBoard() inputStr = input("请输入您下棋的坐标,应以x,y的形式:\n") while inputStr != None: x_str, y_str = inputStr.split(sep=',') # 为对应的列表元素赋值⚪ board[int(x_str)-1][int(y_str)-1] = '⚪' printBoard() inputStr = input("请输入您下棋的坐标,应以x,y的形式:\n")
false
ce110be374e105cbea1b7ae6befb50d7b034e457
walebash/Practice
/nameGenerator.py
1,392
4.21875
4
import random import string def name_generator(letters): vowels = ['a', 'e', 'i', 'o', 'u'] consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 'y', 'v', 'w', 'x', 'y', 'z'] v = [] c = [] names = [] for letter in letters: if letter.lower() in vowels: v.append(letter) elif letter.lower() in consonants: c.append(letter) if len(letters) < 3: raise Exception( 'There should be more than {} letters in the letters'.format(len(letters))) if len(v) == 0: raise Exception('There is no vowel in the letters') if len(c) == 0: raise Exception('There is no consonant in the letters') for i in range(5): first_name_len = random.randint(2, len(letters)) last_name_len = random.randint(2, len(letters)) first_name = random.choice( v) + "".join(random.sample(letters, first_name_len)) last_name = random.choice( c) + "".join(random.sample(letters, last_name_len)) full_name = first_name + " " + last_name user = { "first_name": first_name.title(), "last_name": last_name.title(), "full_name": full_name.title() } names.append(user) return names # print(name_generator(['v', 'w', 'A', 'I', 'T']))
false
2119fa5f8557ace83d4b4b1c8efddf7f050fff86
lz023231/CX.PY
/控制窗体、内存、异常、语音/异常处理.py
1,799
4.15625
4
''' ''' #当程序遇到问题是不让程序结束,而略过错误继续向下执行 ''' try……except……else 格式: try: 语句t except 错误码 as e: 语句1 except 错误码 as e: 语句1 …… except 错误码 as e: 语句n else: 语句e 注意:else可有可无 作用:用来检测try语句块中的错误,从而让except补货错误信息并处理 逻辑:当程序执行到try~expect~else语句时 1、如果当try“语句t”出现错误,会匹配第一个错误码,如果匹配上就执行对应的语句 2、如果当try“语句t”出现错误,没有匹配的异常,那么我们的错误将会被提交到上一层的try语句,或者到程序的最上层 3、如果当try“语句t”没有出现错误,执行else下的“语句e” (你得有) ''' try: print(3 / 0) except ZeroDivisionError as e: print("除数为零了") print("*******") #使用except而不使用任何的错误类型 try: print(4 / 0) except: print("程序出现了异常") #使用except带着多种异常 try: print(5 / 0) except (NameError,ZeroDivisionError): print("出现了NameError或ZeroDivisionError") #特殊的地方 #1、异常其实就是类,所有的异常都是承自BaseException,所有在捕获的时候,它捕获了该类型的错误,还把子类一网打尽 #2、跨越多层调用,也能捕获到异常 ''' try……except……finally try: 语句t except 错误码 as e: 语句1 except 错误码 as e: 语句1 …… except 错误码 as e: 语句n finally: 语句f 作用:无论语句f是否有异常都会执行最后的语句f ''' ''' 断言: ''' def func(num, div): assert (div != 0),"div不能为0" return num / div print(func(10, 0))
false
5c36b47de38425bf90e47c7348b525a35c173305
annewoosam/shopping-list
/shoppinglist.py
628
4.21875
4
print("create a quick, no duplicate, alphabetical shopping list by entering items then hitting enter when done.") shopping_list=[] while True: add_item=input("add item>") if add_item.lower()!="": shopping_list.append(add_item.lower()) shopping_list=set(shopping_list) print( "\noriginal order - no duplicates\n") print(shopping_list) shopping_list=list(shopping_list) print("\nduplicates removed and sorted\n") print(sorted(shopping_list)) else: print("\nYour final list is:\n") print(sorted(shopping_list)) break
true
987650133ed8611b645aef9a6c2ef0fef97dc2be
tasnia18/Python-assignment-certified-course-in-Coursera-
/Python Data Structure/7_2.py
954
4.125
4
""" 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. """ # Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) c=0 k=0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue else: c=c+1 a=line.find(':') s=line.find('/n',a) line=line[a+2:s] line=float(line) k=k+line p=(k/c) print('Average spam confidence:',p)
true
33791e76660c95af96ae04c7b45fd8b1bcfb5646
snowd25/pyPract
/stringPermutation.py
611
4.25
4
#Python Program to Print All Permutations of a String in Lexicographic Order using Recursion #without using permutations builtin def permuteStr(lst,l,r): if l == r: print("".join(lst)) else: for i in range(l,r+1): lst[l],lst[i] =lst[i],lst[l] permuteStr(lst,l+1,r) lst[l],lst[i] =lst[i],lst[l] # permutations using library function from itertools import permutations def permuteStr1(lst): print("Using permutations:") p = permutations(lst) for ch in p: print("".join(ch)) str1 = input() print("Without using permutations:") permuteStr(list(str1),0,len(str1)-1) permuteStr1(list(str1))
true
b299c50e3fa26dbf0c1f7dab579813670ec6dea1
moonlimb/tree_problems
/isBST.py
383
4.1875
4
from Node import Node def is_BST(node): """returns True if a given node is a root node of a binary search tree""" if node.is_leaf(): return True else: # Node class contains comparison methods if (node.left and node.left >= node) or (node.right and node >= node.right): return False return isBST(node.left) and isBST(node.right)
true
8db19628f571ab9cb2e0babcb961974c8baaf99d
imsreyas7/DAA-lab
/Recursion/expo3.py
263
4.21875
4
def expo3(x,n): if n=0: return 1 else: if n%2 ==0: return expo3(x,n/2)*expo(x,n/2) else: return x*expo(x,n-1) x=int(input("Enter a number whose power has to be found ")) n=int(input("Enter the power ")) print("The result is ",expo3(x,n))
true
ad02d70583ed30bea2710fbc61df4a00680dfdc0
Aksharikc12/python-ws
/M_2/Q_2.py
1,407
4.53125
5
'''2. Write a program to accept a two-dimensional array containing integers as the parameter and determine the following from the elements of the array: a. element with minimum value in the entire array b. element with maximum value in the entire array c. the elements with minimum and maximum values in each column d. the elements with minimum and maximum values in each row Example: Input: [[0 1 2 3] [3 4 5 5] [6 7 8 8] [9 0 1 9]] Output: minimum value element in the array: 0 maximum value element in the array: 9 elements with minimum values column-wise: [0 0 1 3] elements with maximum values column-wise: [9 7 8 9] elements with minimum values row-wise: [0 3 6 0] elements with maximum values row-wise: [3 5 8 9] ''' lst = [[0,1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 8], [9, 0, 1, 9]] lst_1=[] for num in lst: lst_1.extend(num) print(f"minimum value element in the array: {min(lst_1)}") print(f"maximum value element in the array: {max(lst_1)}") min_col=list(min(map(lambda x:x[i],lst)) for i in range(4)) print(f"elements with minimum values column-wise: {min_col}") max_col=list(max(map(lambda x:x[i],lst)) for i in range(4)) print(f"elements with minimum values column-wise: {max_col}") min_row=list(map(lambda x:min(x),lst)) print(f"elements with minimum values row-wise:{min_row}") max_row=list(map(lambda x:max(x),lst)) print(f"elements with minimum values row-wise:{max_row}")
true
211f7d8c6027e43fa5933eb581ecee3a8daf0edb
Aksharikc12/python-ws
/M_1/Q_1.py
413
4.25
4
'''1. Write a program to accept a number and determine whether it is a prime number or not.''' import math num=int(input("enter the number")) is_prime=True if num<2: is_prime=False else: for i in range(2,int(math.sqrt(num)) + 1): if num % i == 0: is_prime=False break if is_prime: print(f"{num} is prime number") else: print(f"{num} is not a prime number")
true
50959738f8045b5b3d0beea7c9992cbbe820dc82
murphy1/python_problems
/chapter6_string.py
1,577
4.1875
4
# file for Chapter 6 of slither into python import re # Question 1, user input will state how many decimal places 'e' should be formatted to. """ e = 2.7182818284590452353602874713527 format_num = input("Enter Format Number:") form = "{:."+format_num+"f}" print(form.format(e)) """ # Question 2, User will input 2 numbers and a string. The string will be sliced depending on the numbers # If the numbers are not in the range, the message will be displayed: Cannot slice using those indices """ string = input("Enter a string to slice:") num1 = int(input("First num:")) num2 = int(input("Second num:")) if num1 > len(string) or num2 > len(string): print("Cannot slice using those indices!") else: sliced = string[num1:num2] print(sliced) """ # Question 3, Will grade your password depending on how strong it is. Levels are 1 -> 4 depending on if it has # digits, lowercase letters, uppercase letters or special characters password = input("Please enter your password:") cap_check = re.findall('[A-Z]+', password) lowcase_check = re.findall('[a-z]+', password) digit_check = re.findall('[0-9]+', password) special_char_check = re.findall('[$,@.#<>%*!]+', password) strength = 0 if len(cap_check) > 0: strength += 1 else: pass if len(lowcase_check) > 0: strength += 1 else: pass if len(digit_check) > 0: strength += 1 else: pass if len(special_char_check) > 0: strength += 1 else: pass if strength >= 3: print("Strength: %d, Valid Password" % (strength)) else: print("Strength: %d, Invalid Password" % (strength))
true
83b2663bf20b961eb4ac3273e59dbadcb852b9d5
tommy-stone/Intro_CompSci_Python_Code
/Week_1/Problem Set 2.py
258
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 18 13:28:18 2017 @author: tstone """ s = 'bobobooooobbbooobobbo' count = 0 for vowel in s: if vowel in 'bob': count += 1 print("Number of times bob occurs is: " + str(count))
false
da1190857891ba038938c4e7bba4cd26dbcc21ac
zabdulmanea/movie_trailer_website
/media.py
555
4.125
4
class Movie(): """ This class provides the structure to store movie information Attributes: title (str): The movie title trailer_youtube_url (str): A link to the movie trailer on youtube poster_image_url (str): A link to the movie poster """ # constructor of Movie class, called when an instance of class is created def __init__(self, movie_title, movie_poster, movie_trailer): self.title = movie_title self.trailer_youtube_url = movie_trailer self.poster_image_url = movie_poster
true
b73b09b2466c362a584cada47b9ed0ba2c249d9e
Nitin-Diwakar/100-days-of-code
/day25/main.py
1,431
4.53125
5
# Write a Python GUI program # using tkinter module # to input Miles in Entry widget # that is in text box and convert # to Kilometers Km on button click. import tkinter as tk def main(): window= tk.Tk() window.title("Miles to Kilometers Converter") window.geometry("375x200") # create a label with text Enter Miles label1 = tk.Label(window, text="Enter Miles:") # create a label with text Kilometers: label2 = tk.Label(window, text="Kilometers:") # place label1 in window at position x,y label1.place(x=50,y=30) # create an Entry widget (text box) textbox1 = tk.Entry(window, width=12) # place textbox1 in window at position x,y textbox1.place(x=200,y=35) # place label2 in window at position x,y label2.place(x=50,y=100) # create a label3 with empty text: label3 = tk.Label(window, text=" ") # place label3 in window at position x,y label3.place(x=180,y=100) def btn1_click(): kilometers = round(float(textbox1.get()) * 1.60934,5) label3.configure(text = str(kilometers)+ ' Kilometers') # create a button with text Button 1 btn1 = tk.Button(window, text="Click Me To Convert", command=btn1_click) # place this button in window at position x,y btn1.place(x=90,y=150) window.mainloop() main()
true
3d6cab692c8588bf46a2f4f4b96c441141472660
Endie990/pythonweek-assigments
/Assignment_Guessing_game.py
534
4.125
4
#ass 2- guessing game import random guessnum=random.randint(1,9) num= int(input('Guess a number between 1 and 9: ')) while guessnum!='num': if num<guessnum: print('Guess is too low,Try again') num= int(input('Guess a number between 1 and 9: ')) elif num>guessnum: print('Guess is too high,Try again') num= int(input('Guess a number between 1 and 9: ')) else: print('****Congratulations!!Well Guessed****!!!!!!!!!!') break
true
5de52fcb51cf062e250533875d749f7fcd0c5a1e
AdityaJsr/Bl_week2
/week 2/dictP/createDict.py
587
4.125
4
""" Title - Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string. Sample string : 'w3resource' Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1} Access individual element through indexes. Author name - Aditya Kumar Ceation time - ‎‎04 ‎March ‎2021 ‏‎ Modified time - ‎‎‎04 ‎March ‎2021‎ """ from collections import defaultdict, Counter str1 = 'thisIsaSampleString' d = {} for letter in str1: d[letter] = d.get(letter, 0) + 1 print(d)
true
423df06c344e381a8d09156226b10ef17f37bebd
thatguysilver/pswaads
/listing.py
966
4.21875
4
''' Trying to learn about the different list concatenation methods in py and examine their efficiency. ''' import time def iterate_concat(): start = time.time() new_list = [] for i in range(1000): new_list += [i] end = time.time() return f'Regular iteration took {end - start} seconds.' def append_concat(): start = time.time() new_list = [] for i in range(1000): new_list.append(i) end = time.time() return f'Append method took {end - start} seconds.' def list_comp_concat(): start = time.time() new_list = [i for i in range(1000)] end = time.time() return f'Using a list comprehension took {end - start} seconds.' def make_list(): start = time.time() new_list = list(range(1000)) end = time.time() return f'Creating a list from a range took {end - start} seconds.' print(iterate_concat()) print(append_concat()) print(list_comp_concat()) print(make_list())
true
304769d3a15878e844f87a8fa360e8a7ee5a5c97
dan480/caesars-cipher
/main.py
1,364
4.3125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import argparse from src.select_alphabet import select_alphabet from src.decoding import decoding_func from src.encoding import encoding_func """ The main file that runs the program logic. The function of creating a command line parser is implemented here. In the main () function, the received data is processed. """ def create_parser(): # The function of creating a command line parser. parser = argparse.ArgumentParser(description="Process the string.") parser.add_argument("action", type=str, help="Choosing a function") parser.add_argument( "string", action="extend", nargs="+", type=str, help="Get a string for processing", ) return parser def main(): # A function that contains the logic for processing input data. parser = create_parser() args = parser.parse_args() letter = args.string[0] param = vars(args) action = param.get("action") string = param.get("string") string = " ".join(string) alphabet = select_alphabet(letter[1]) if action in ["e", "encoding"]: print(encoding_func(string, alphabet, -2)) elif action in ["d", "decoding"]: print(decoding_func(string, alphabet, -2)) else: print(f"{action} function does not exist") if __name__ == "__main__": main()
true
c9a18125f74caacb4b470d986bf7e09fe119b180
Tchomasek/Codewars
/Codewars/6 kyu/Sort the odd.py
663
4.3125
4
def sort_array(source_array): result = list(source_array) even = {} for index,num in enumerate(source_array): if num % 2 == 0: even[index] = num result.remove(num) result.sort() for index,num in even.items(): result.insert(index, num) return result print(sort_array([0, 1, 2, 3, 4, 9, 8, 7, 6, 5])) """You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]"""
true
0adb0d78954c719dadafd33dde275e43387b70bc
Machin-Learning/Exercises
/Section-1/Data Types/set.py
1,475
4.40625
4
# #Set # 1. Set in python is immuttable/non changeable and does not show duplicate # 2. Set are collection of element seprated by comma inside {,} # 3. Set can't be indexed or slice # 4. Set can't add/concat or scale/multiply # 5. we can use set to store multiple items in one variable # 6. set are itrator s = {1,2,3,4} print(s) #set are immuttable # s[0]= 5 #TypeError: 'set' object does not support item assignment # print(s) #TypeError: 'set' object is not subscriptable #Indexing :left to right [0][1][2][3][.][n] # right to left [-1][-2][-3][-.][-n] # print(s[0]) #TypeError: 'set' object is not subscriptable # print(s[0:3]) s1 = {1,2,5,6} # Operation on set # print(s+s1) #TypeError: unsupported operand type(s) for +: 'set' and 'set' # print(s*s1) #TypeError: unsupported operand type(s) for *: 'set' and 'set' print(s.intersection(s1)) #--->{1, 2} print(s.difference(s1)) #--->{3, 4} print(s1.difference(s)) #--->{5, 6} print(s.union(s1)) #--->{1, 2, 3, 4, 5, 6} print(s.pop()) print(s) print(s.pop()) print(s) print(s.pop()) print(s) print(s1) print(s1.remove(5)) print(s1) print() print(s1.discard(2)) print(s1) print() print(s1.symmetric_difference(s)) s2 = {1,2,1,5,4,4,6,8,7,8} print(s2)
true
f6b584f4a4315fc01bba5463bca09b968f9f2d76
Machin-Learning/Exercises
/Section-1/Data Types/variables.py
1,191
4.125
4
# Variables in python # var = 5 # print(var) # var = "Muzmmil pathan" # print(var) # Data Types # 1. int() # 2. str() # 3. float() # 4. list() # 5. tuple() # 6. set() # 7. dict() num = 4 #integers are a number "without point / non fractional / Decimal from 1-9 only" print(type(num)) # type() is a inbuilt function use to check the type/class of the object print() s = "Python is Easy to learn" # s is string/charectors # In python no charechter data type. # Remember to right in single or dubble qouts # print(type(s)) print() f = 3.14 # f is float due to fraction /point after the number print(type(f)) print() l = [1,2,3,4,5,6] # l is list due to it's [] .value written inside the bracket is list print(type(l)) print() t = (1,2,3,4,5,6) #t is tuple due to it's () we can also write tuple by seprating value using comma as bellow _t = 1,2,3,4,5,6 print(type(t)) print(type(_t)) print() S = {1,2,3,4,5} # S is set due to value seprated by comma and written inside the curly bracket print(type(S)) print() d = {"username":"Muzmmil","password":9145686396} # d is Dictionary due to its written inside {} and have value pair print(type(d)) #etc
true
94f03f87bc88a62fcdcb3e215b6d3157a5d77149
Machin-Learning/Exercises
/Section-3/Fuction and Method/User Input/user_input.py
251
4.28125
4
# User Input # To get input from user we use input() method name = input("Enter your name: ") # Remember input() take input in string format age = input("Enter your age: ") print(f"Welcom {name}") print(f"Your life Expectancy {100 - int(age)} Years")
false
d9e48b09f2c3a902b3009279f89263b5eee7087e
yashbagla321/Mad
/computeDistancePointToSegment.py
1,014
4.15625
4
print 'Enter x and y coordinates of the point' x0 = float(input()) y0 = float(input()) print 'Enter x and y coordinates of point1 then point2 of the line' x1 = float(input()) y1 = float(input()) x2 = float(input()) y2 = float(input()) import math def computeDistancePointToSegment(x1,y1, x2,y2, x3,y3): # x3,y3 is the point px = x2-x1 py = y2-y1 something = px*px + py*py u = ((x3 - x1) * px + (y3 - y1) * py) / float(something) if u > 1: u = 1 elif u < 0: u = 0 x = x1 + u * px y = y1 + u * py dx = x - x3 dy = y - y3 # Note: If the actual distance does not matter, # if you only want to compare what this function # returns to other results of this function, you # can just return the squared distance instead # (i.e. remove the sqrt) to gain a little performance dist = math.sqrt(dx*dx + dy*dy) return dist print(computeDistancePointToSegment(x1, y1, x2, y2, x0, y0))
true
e898d4e4b96bf10bdba01c473cfa8de608ff158d
mxu007/leetcode
/414_Third_Maximum_Number.py
1,890
4.1875
4
# Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). # Example 1: # Input: [3, 2, 1] # Output: 1 # Explanation: The third maximum is 1. # Example 2: # Input: [1, 2] # Output: 2 # Explanation: The third maximum does not exist, so the maximum (2) is returned instead. # Example 3: # Input: [2, 2, 3, 1] # Output: 1 # Explanation: Note that the third maximum here means the third maximum distinct number. # Both numbers with value 2 are both considered as second maximum. # https://leetcode.com/problems/third-maximum-number/description/ # 1) iterate the nums and compare with first, second and third, cannot sort as the problem specifies O(N) time class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ first, second, third = -sys.maxsize - 1, -sys.maxsize - 1, -sys.maxsize - 1 for num in nums: if num > first: first, second, third = num, first, second elif second < num < first: second, third = num, second elif third < num < second: third = num return third if third != -sys.maxsize - 1 else first # 2) use heapq, heapq.nlargest(n,B) takes O(mlog(n)) where m is number of elements in nums # https://stackoverflow.com/questions/23038756/how-does-heapq-nlargest-work # https://stackoverflow.com/questions/29109741/what-is-the-time-complexity-of-getting-first-n-largest-elements-in-min-heap?lq=1 import heapq class Solution: def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ B = set(nums) A = heapq.nlargest(3, B) A.sort() if len(A) != 3 : return A[-1] else: return A[0]
true
00a7856bbfb3690bf77899cfa4ce5e1c59b43191
saifeemustafaq/Magic-Maths-in-Python
/test.py
892
4.25
4
print "" print " Please press enter after each step!" print "" print ' Think of a number below 10...' a=raw_input( ) print ' Double the number you have thought.' b=raw_input() c= int(input(" Add something from 1-10 with the getting result and type it here (type only within 1-10):")) print "" print ' Half the answer, (that is divide it by 2.)' d=raw_input() print ' Take away the number you have thought from the answer\n that is, (subtract the number you have thought from the answer you have now.)' e=raw_input() if c==0 : print "Please be honest" if c==1 : print "0.5" if c==2 : print "1" if c==3 : print "1.5" if c==4 : print "2" if c==5 : print "2.5" if c==6 : print "3" if c==7 : print "3.5" if c==8 : print "4" if c==9 : print "4.5" if c==10 : print "5"
true
85f11d93c2b76f8a0f8def3f861002cb73056ef9
Hariharan-K/python
/remove_all_occurrences.py
1,086
4.34375
4
# Remove all occurrences of a number x from a list of N elements # Example: Remove 3 from a list of size 5 containing elements 1 3 2 3 3 # Input: 3 5 1 3 2 3 3 # Output: 1 2 # Input: 4 7 1 4 4 2 4 7 9 ######################## import sys def remove_all_occurrences(mylist,n): # loop to traverse each element in list # and, remove elements # which are equals to n i=0 #loop counter length = len(mylist) #list length while(i<length): if(mylist[i]==n): mylist.remove (mylist[i]) # as an element is removed # so decrease the length by 1 length = length -1 # run loop again to check element # at same index, when item removed # next item will shift to the left continue i = i+1 # print list after removing given element print ("list after removing elements:") print (mylist) #################### # Driver code ###### x = list(map(int, input("Enter a multiple value: ").split())) print("List of students: ", x) val = x[0] ar_size = x[1] x = x[2:] print ("val = ", val, "size = ", ar_size, x ) remove_all_occurrences(x, val)
true
b68c2c507980032894a5f75f3a3c619b28b559d1
Hariharan-K/python
/max_sum_of_non_empty_array.py
1,411
4.28125
4
""" Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element. Example 1: Input: arr = [1,-2,0,3] Output: 4 Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value. Example 2: Input: arr = [1,-2,-2,3] Output: 3 Explanation: We just choose [3] and it's the maximum sum. Example 3: Input: arr = [-1,-1,-1,-1] Output: -1 Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0. """ import sys def maximumSum(arr): del_sum = non_del_sum = 0 res = -sys.maxsize for i,a in enumerate(arr): del_sum = max(del_sum + a,a) print ("delsum ", del_sum) if i > 0: del_sum = max(del_sum,non_del_sum) print ("delsum ", del_sum) non_del_sum = max(non_del_sum + a,a) res = max(res, del_sum) return res #print(maximumSum([1,-2,0,3])) print(maximumSum([1,-2,-2,3])) #print(maximumSum([-1,-1,-1,-1]))
true
de2318e0e48f591e07074c66b6fe9bd924fbd358
xuzhanhao06/PythonBase
/20200602随机分配办公室.py
553
4.125
4
#将8人分配3教室 ''' 1. 准备数据 2.分配 3.验证 ''' import random #1. teachers=['A','B','C','D','E','F','G','H'] offices=[[],[],[]] #2. for name in teachers: #列表追加数据--append extend insert num=random.randint(0,2) offices[num].append(name) print(offices) #3. #办公室+个编号 i=1 for office in offices: #打印人数 print(f'办公室{i}人数:{len(office)},老师分别是:',end="") #打印名字 for name in office: print(name,end=' ') print() i+=1
false
a859cf7b8c1e199bc6a6ed9c4e649f1b0ea344cb
xuzhanhao06/PythonBase
/20200602元组.py
422
4.1875
4
#如果想要存储多个数据,但是这些数据是 不能修改的数据 ,----元组 #元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。 t1=(10,20,30) print(t1)#(10, 20, 30) print(type(t1))#<class 'tuple'> t2=(10,) t3=(10) print(type(t2))#'tuple' print(type(t3))# 'int' t4=('aaa') print(type(t4))# 'str' t5=('aaa',) print(type(t5))#tuple
false
feb56976564ffc9050e2fbfc0538ac172fb9b10b
huangzhilv/PythonPro
/python_demo/error_debug_test/debug.py
2,261
4.1875
4
import logging print('''---------------------调试--------------------- ''') # 需要一整套调试程序的手段来修复bug。 # 第一种 方法简单直接粗暴有效,就是用print()把可能有问题的变量打印出来看看: # 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息。所以,我们又有第二种方法。 def foo(s): n = int(s) print('>>> n = %d' % n) return 10 / n def main(): foo('0') # main() # 第二种 断言 # 凡是用print()来辅助查看的地方,都可以用断言(assert)来替代: def foo1(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main1(): foo1('0') # main1() # 程序中如果到处充斥着assert,和print()相比也好不到哪去。不过,启动Python解释器时可以用-O参数来关闭assert: # 第三种 logging # 把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件: def foo2(s): n = int(s) logging.info('n = %d' % n) return 10 / n def main2(): foo2('0') logging.basicConfig(level=logging.INFO) # main2() # 这就是logging的好处,它允许你指定记录信息的级别, # 有debug,info,warning,error等几个级别, # 当我们指定level=INFO时,logging.debug就不起作用了。 # 同理,指定level=WARNING后,debug和info就不起作用了。 # 这样一来,你可以放心地输出不同级别的信息,也不用删除,最后统一控制输出哪个级别的信息。 # # logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件。 # 第四种 pdb # 第4种方式是启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。我们先准备好程序: # 执行方法:python -m pdb debug.py # pdb.set_trace() # **************小结************** # 虽然用IDE调试起来比较方便,但是最后你会发现,logging才是终极武器。 def test(): print("使用方法一调试:", main()) # print("使用方法二调试:", main1()) # print("使用方法三调试:", main2()) test()
false
f398f63722bbc7361943d84f629334a9b880ed88
huangzhilv/PythonPro
/python_demo/func_program/higher_order_func/__init__.py
307
4.15625
4
# 高阶函数 # 变量可以指向函数 print("abs(-10)=", abs(-10)) print("abs=", abs) # 可见,abs(-10)是函数调用,而abs是函数本身。 f = abs print("\nf(-10)=", f(-10)) # 传入函数 # 一个最简单的高阶函数: def add(x, y, f): return f(x) + f(y) print(add(-5, 6, abs))
false
7cb9735d6e8c25d21f8bae96ca9780332eab0d27
kanglicheng/learn-python-2020
/yinqi/week3.py
2,359
4.21875
4
# examples of dictionary # Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} # print(Dict) # del Dict ['Charlie'] # print(Dict) # t = "Tim" in Dict # print(t) # res = {} # print("x" in res) """"""""" problem 1 """"""""" def get_rainfall(dat): res = {} for x in dat: city = x[0] amount = x[1] # print(type(city)) # print(type(amount)) if city in res: res[city] += amount else: res.update(dict([x])) # res[city] = amount return res # x = get_rainfall([("boston", 10), ("sf", 5), ("seattle", 20), ("sf", 3), ("boston", 5)]) # print(x) # The input of update of dictionary should be an object of length 2, therefore a Tuple of Tuple is allowed but a singe tuple is not, since the element of a simple tuple is "str" or "int" # y = (("boston", 10), ("sf", 5), ("seattle", 20), ("boston", 5)) # print(dict(y)) # {"a":1} """"""""" problem 2 """"""""" menu = {'sandwich': 10, 'tea': 7, 'salad': 9} def take_order(): ind = True while ind: order = input() if order not in ["sandwich", "tea", "salad"]: print("available on the menu: sandwich, tea, salad") elif menu[order] > 0: menu[order] -= 1 print("OK, stock = " + str(menu[order])) else: print("Item not available") if menu["sandwich"] == menu["tea"] == menu["salad"] == 0: ind = False # take_order() """"""""""" Problem 3 """"""""""" def most_repeating(words): res_count = 0 res_word = "" for i in range(len(words)): x = words[i] count = {} for j in x: if j in count: count[j] += 1 else: count[j] = 1 p = max(count.values()) if p > res_count: res_count = p res_word = x print(res_word + " is the most repeated word in the list, the most repeated number is " + str(res_count)) # words = ['this', 'is', 'an', 'elementary', 'test', 'example'] # most_repeating(words) """"""""""" Problem 4 """"""""""" def how_many_different(dat): res = {} for x in dat: if x in res: res[x] += 1 else: res[x] = 1 unique = res.keys() return len(unique) print(how_many_different([1, 2, 1, 1, 3, 1, 1, 6]))
false
9fd8b191b77e79f0c6e335ddefc35817e5edddd6
FengyiLi1102/Python-Learning
/check_fermat.py
749
4.21875
4
import math def check_fermat(a, b, c, n): if n <= 2 or type(a and b and c and n) is not int or a * b * c < 0: raise ValueError oo = 1 for b in range(1, b): for a in range(1, a): for n in range(2, n): c = math.log((a**n + b**n), n) if type(c) is int: print('Holy smokes, Fermat was wrong!') oo = 2 break if oo == 1: print('No, that doesn\'t work') def check_fermat_input(): a = int(input('Please type your a: ')) b = int(input('Please type your b: ')) c = int(input('Please type your c: ')) n = int(input('Please type your n: ')) check_fermat(a, b, c, n)
false
7bb3fd83c75400cf21e849e29494e117a57befa6
EchoDemo/Python
/Python_elementary/unit5/class.py
948
4.125
4
#coding:utf-8 #1、创建dog类: class Dog(object): """docstring for Dog""" def __init__(self, name,age): """初始化属性name和age""" self.name = name self.age = age self.master_numbers=0 #为属性指定默认值 def sit(self): print(self.name.title()+" is now sitting.") def roll_over(self): print(self.name.title()+" rolled over.") def update_master_numbers(self,master_numbers): if master_numbers>self.master_numbers: self.master_numbers=master_numbers; else: print("You can't change the master_numbers!") #2、根据类创建实例: my_dog=Dog('willie',6) print("My dog's name is "+my_dog.name.title()+".") print("My dog is "+str(my_dog.age)+" years old.") my_dog.sit() my_dog.roll_over() #3、修改属性的值:直接修改,通过方法修改, print(my_dog.master_numbers) my_dog.master_numbers=2 print(my_dog.master_numbers) my_dog.update_master_numbers(3) print(my_dog.master_numbers)
false
e832abb0aa4eb61822c58068c5ff12dfc06851cd
EchoDemo/Python
/Python_elementary/unit2/list_sort.py
540
4.25
4
#coding:utf-8 #1、使用sort()对列表进行永久性排序; cars=['bmw','audi','toyota','subaru'] cars.sort() #按字母顺序排列(永久性的) print(cars) cars.sort(reverse=True) #按字母逆序排列(永久性的) print(cars) #2、使用函数sorted()对列表进行临时排序; cars=['bmw','audi','toyota','subaru'] print(cars) print(sorted(cars)) #临时排序; print(sorted(cars,reverse=True)) print(cars) #3、永久性倒着打印列表; cars.reverse() print(cars) #4、确定列表的长度; print(len(cars))
false
88f55010db0303121f3c6ba25cba54efe923589f
Colfu/codewars
/6th_kyu/autocomplete_yay.py
2,620
4.21875
4
# It's time to create an autocomplete function! Yay! # The autocomplete function will take in an input string and a dictionary array # and return the values from the dictionary that start with the input string. **Cr.1 # If there are more than 5 matches, restrict your output to the first 5 results. **Cr.2 # If there are no matches, return an empty array. **Cr.3 # # Example: # autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport'] # # For this kata, the dictionary will always be a valid array of strings. # Please return all results in the order given in the dictionary, **Cr.4 # even if they're not always alphabetical. # The search should NOT be case sensitive, but the case of the word should be preserved when it's returned. **Cr.5 # For example, "Apple" and "airport" would both return for an input of 'a'. # However, they should return as "Apple" and "airport" in their original cases. **Cr.6 # # Important note: # Any input that is NOT a letter should be treated as if it is not there. **Cr.7 # For example, an input of "$%^" should be treated as "" and an input of "ab*&1cd" should be treated as "abcd". # ----------------------------------- # Plan: # Assumption: they say 'dictionary' but mean 'list', as that's what they show in the example. # 1. for word in dictionary, if word[0:len of input] = input, add to results list # 2. case sensitive using .lower() # 3. filter using >= a and <=z def autocomplete(input_, dictionary): """Take in an input string and a dictionary array and return the values from the dictionary that start with the input string. Args: input_ (string): letters used to start a word dictionary (list): valid list of strings Returns: list: values from dictonary list that start with input_ string """ # Make lowercase, remove non-alpha characters, and store **Cr.7 filtered_input = '' for char in input_.lower(): if char >= 'a' and char <= 'z': filtered_input += char # Store results autocomplete_list = [] for word in dictionary: # Compare characters in length of input to same length of each dictionary word, if the same, add to results list if word[:(len(filtered_input))].lower() == filtered_input.lower(): #**Cr.5 & 6 autocomplete_list.append(word) # **Cr.1, **Cr.4 # If no matches, return empty list if len(autocomplete_list) == 0: # **Cr.3 return [] else: return autocomplete_list[:5] # **Cr.2
true
8c1e72d62ca4f9dcdc61a861d0dc8ed095d922ba
sankari-chelliah/Python
/int_binary.py
414
4.34375
4
#Program to convert integer to Binary number num= int(input("Enter Number: ")) result='' #Check the sign of the number if num<0: isneg=True num = abs(num) elif num==0: result='0' else: isneg= False # Does actual binary conversion while num>0: result=str(num%2)+result num=num//2 #Display result with the sign of the input if isneg==True: print(f"-{result}") else: print(result)
true
3a40e7b025d83d81c9f59ee9b5774f4d68a5039b
ywkpl/DataStructuresAndAlgorithms
/Sort/MergeSort.py
1,611
4.15625
4
#归并排序,分而治之 import random,time class MergeSort: def __init__(self, capacity:int): self._arr=[] self._insert_values(capacity) def _insert_values(self, capacity:int): for x in range(capacity): self._arr.append(random.randint(1,100000)) def print_all(self): print(self._arr) def sort_split(self, start:int, end:int): if start>=end: return splitIndex=(start+end)//2 self.sort_split(start, splitIndex) self.sort_split(splitIndex+1, end) self.merge_sort(start, splitIndex, end) def merge_sort(self, left:int, mid:int, right:int): marge=[] i,j=left,mid+1 #比较搬移 while i<=mid and j<=right: if(self._arr[i]<=self._arr[j]): marge.append(self._arr[i]) i+=1 else: marge.append(self._arr[j]) j+=1 #搬移剩余数据 while i<=mid: marge.append(self._arr[i]) i+=1 while j<=right: marge.append(self._arr[j]) j+=1 #复制 i=0 while i<len(marge): self._arr[left+i]=marge[i] i+=1 def sort(self): start=time.time() self.sort_split(0, len(self._arr)-1) end=time.time() print(end-start) def test_MergeSort(): print('初始化') sort=MergeSort(10000000) #sort.print_all() print('排序') sort.sort() #sort.print_all() if __name__=="__main__": test_MergeSort()
false
e00cd5b8f7123eb566e5bb8c84aaa479e2300877
namand010/Project4091998
/Learning_code/DaysinBtwDates.py
1,661
4.1875
4
def isleapyear(year): if year % 4 == 0 or year % 400 == 0: return True else: return False def DaysInmonth(year,month): if month == 1 or month == 3 or month == 5 or month == 7 \ or month == 8 or month == 10 or month == 12: return 31 else: if month == 2: if isleapyear(year): return 29 else: return 28 return 30 def nextDay(year,month,day): if day < DaysInmonth(year,month): return year,month,day + 1 else: if month == 12: return year+1,1,1 else: return year, month+1, 1 def DatesBetweenBig(year1,month1,day1,year2,month2,day2): if year2 > year1: return True if year1 == year2: if month2 > month1: return True if month1 == month2: return day2 > day1 return False def DaysBetweenDates(year1,month1,day1,year2,month2,day2): days = 0 while DatesBetweenBig(year1,month1,day1,year2,month2,day2): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def test(): TestCases = ((2012, 9, 30, 2014, 10, 30), 30),\ ((2012, 1, 1, 2013, 1, 1),366) for args, answer in TestCases: result = DaysBetweenDates(*args) if result == answer: print("The Result is {}".format(result)) else: print(result) #assert DaysBetweenDates(2012, 9, 30, 2012, 10, 30) == 30, "Failed" #assert DaysBetweenDates(2012, 1, 1, 2013, 1, 1) == 366, "Failed" #assert DaysBetweenDates(2012, 9, 1, 2012, 9, 4) == 3, "Failed" test()
false
932e7ff84d93da6509d9a8b44eb161d873ec72a4
uestcljx/pythonBeginner
/prime.py
1,415
4.15625
4
#odd_iter 生成一个无穷奇数数列,作为初始数列(2以外的偶数都不是素数) def odd_iter(): n = 1 while True: n = n + 2 yield n #not_divisible 输入参数n, 内部定义一个匿名函数,输入参数x, 判断x是否能被n整除 def not_divisible(n): return lambda x: x % n > 0 # 注意这里定义了一个匿名函数,所以实际上not_divisible函数要接受两个参数 #生成无穷素数数列 def prime(): _iter = odd_iter() #初始数列 yield 2 while True: n = next(_iter) yield n _iter = filter(not_divisible(n), _iter) #得到新的数列 def primes_under_n(): boundary = int(input("> Boundary: ")) print("The primes under boundary are: ") for n in prime(): if n < boundary: print(n, end = ' ') else: break def amount_of_primes(): i = 0 amount = int(input("> How many primes: ")) print(f"The {amount} primes are: ") for n in prime(): if i < amount: print(n, end = ' ') i = i + 1 else: break while True: print("\n1. Print primes under n;\n2. Print n primes;\n3. Quit") opt = input("> ") if opt == '1': primes_under_n() elif opt == '2': amount_of_primes() elif opt == '3': break else: print("Invalid Input!") print("\n")
false
ec094d809089a6cff9ded0f6cd4a10e98a698e60
rstrozyk/codewars_projects1
/#8 alternate_capitalization.py
673
4.28125
4
# Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0 will be considered even. # For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples. # The input will be a lowercase string with no spaces. # Good luck! def capitalize(s): outcome = ["",""] i = 0 for char in s: if i % 2 == 0: outcome[0] += char.capitalize() outcome[1] += char i += 1 else: outcome[0] += char outcome[1] += char.capitalize() i += 1 return outcome print(capitalize("abracadabra")) # test
true
1a84de296000421f725a38ef905ab5f590d085ac
SanghamitraDutta/dsp
/python/markov.py
2,440
4.5625
5
#!/usr/bin/env python # Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing *text to read*, and the *number of words to generate*. For example, if `chains.txt` contains the short story by Frigyes Karinthy, we could run: # ```bash # ./markov.py chains.txt 40 # ``` # A possible output would be: # > show himself once more than the universe and what I often catch myself playing our well-connected game went on. Our friend was absolutely correct: nobody from the group needed this way. We never been as the Earth has the network of eternity. # There are design choices to make; feel free to experiment and shape the program as you see fit. Jeff Atwood's [Markov and You](http://blog.codinghorror.com/markov-and-you/) is a fun place to get started learning about what you're trying to make. import sys import random from collections import defaultdict def readfile(in_file): with open(in_file) as f: text = f.read() return text def nxt_wrds_dict(text): # Makes dict with Keys: words from file & Values: list of words that follow the key word in the file word_list = text.split() d = defaultdict(list) for i in range(0,len(word_list)-1): # for loop goes up to penultimate word in file as no words follow the last word d[word_list[i]].append(word_list[i+1]) # for every word key append the value list with the word that follows the key in the file return d def markov_generator(nxt_word_dict, n): StartWordsList = [word for word in nxt_word_dict.keys() if word[0].isupper()] #List all keys with Capital letter as they start a sentence First_word = random.choice(StartWordsList) # find a random starting word Output_List = [First_word] i=1 while i< n: NextWord = random.choice(nxt_word_dict[Output_List[-1]]) #for each output word(key) find next word randomly(from value list) Output_List.append(NextWord) i+=1 MarkovOutput = " ".join(Output_List) return MarkovOutput if __name__ == '__main__': input_file = sys.argv[1] # 2nd argument entered on terminal word_count = int(sys.argv[2]) # 3rd argument entered on terminal input_text = readfile(input_file) nextword_dict = nxt_wrds_dict(input_text) markov_text = markov_generator(nextword_dict, word_count) print(markov_text) #print(nextword_dict)
true
14f4b6abd789bffaf54ab8587be22f13dd87e572
j721/cs-module-project-recursive-sorting
/src/searching/searching.py
1,128
4.4375
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # Your code here middle = (start +end)//2 if len(arr) == 0: return -1 #empty array #if target is equal to the middle index in the array then return it if arr[middle] == target: return middle #if target is less than middle than call recursion and focus on the left side #disregard the middle index and those on the right side elif arr[middle] > target: return binary_search(arr, target, end, middle -1) #if target is greater than the middle index than focus on the right side #disregard the middle index and those on the left else: return binary_search(arr, target, start, middle + 1) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # def agnostic_binary_search(arr, target): # Your code here
true
570b85577fcc8343c1d9fa11d8e0bd95eb3a4e3f
kulsuri/playground
/daily_coding_problem/solutions/problem_9.py
611
4.1875
4
# Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. # For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. def largest_sum(l): inclusive = 0 exclusive = 0 for i in l: temp = inclusive inclusive = max(inclusive, exclusive + i) exclusive = temp answer = max(inclusive, exclusive) return answer print(largest_sum([2, 4, 6, 2, 5])) print(largest_sum([5, 1, 1, 20, 2])) print(largest_sum([5, 1, 1, 5]))
true
4ecf79677118a95f24d80fe0ead4272e8f61eeec
kulsuri/playground
/udemy-11-essential-coding-interview-questions/1.1_arrays_most_freq_no.py
911
4.21875
4
# return the most frequent element in an array in O(n) runtime def most_frequent(given_array): # insert all elements and corresponding count in a hash table Hash = dict() for c,v in enumerate(given_array): if given_array[c] in Hash.keys(): Hash[given_array[c]] += 1 else: Hash[given_array[c]] = 1 # find the max frequency max_count = 0 result = None for i in Hash: if max_count < Hash[i]: result = i max_count = Hash[i] return result # Examples # most_frequent(list1) should return 1 list1 = [1, 3, 1, 3, 2, 1] # most_frequent(list2) should return 3 list2 = [3, 3, 1, 3, 2, 1] # most_frequent(list3) should return None list3 = [] # most_frequent(list4) should return 0 list4 = [0] # most_frequent(list5) should return -1 list5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1] print(most_frequent(list1))
true
07d0eb183fcc1f3fd342e785a743043658114649
kylebush1986/CS3080_Python_Programming
/Homework/Homework_3/hw3_kyle_bush_ex_3.py
1,708
4.4375
4
''' Homework 3, Exercise 3 Kyle Bush 9/21/2020 This program stores a store inventory in a dictionary. The user can add items, delete items, and print the inventory. ''' def printInventory(inventory): print() print('Item'.ljust(20), 'Quantity'.ljust(8)) for item, number in inventory.items(): print(item.ljust(20), str(number).ljust(8)) print() def addItem(inventory, item): inventory.setdefault(item, 0) inventory[item] += 1 print('Item added: ' + item + ', Quantity in Inventory: ' + str(inventory[item])) def deleteItem(inventory, item): if item in inventory and inventory[item] >= 0: inventory[item] -= 1 print('Item deleted: ' + item + ', Quantity in Inventory: ' + str(inventory[item])) else: print(item + ' is not in inventory.') def main(): inventory = { 'Hand sanitizer': 10, 'Soap': 6, 'Kleenex': 11, 'Lotion': 16, 'Razors': 12 } while True: print('MENU') print('1. Add Item') print('2. Delete Item') print('3. Print Inventory') print('4. Exit') menuSelection = input() if menuSelection == '1': print('Enter an item to add to the inventory.') item = input() addItem(inventory, item) elif menuSelection == '2': print('Enter an item to delete from the inventory.') item = input() deleteItem(inventory, item) elif menuSelection == '3': printInventory(inventory) elif menuSelection == '4': break else: print('Please enter a valid menu option.') if __name__ == "__main__": main()
true
1270188cab6e1d289056abee5013a4f729bfb40d
justinDeu/path-viz
/algo.py
1,273
4.40625
4
from board import Board class Algo(): """Defines an algorithm to find a path from a start to an end point. The algorithm will be run against a 2D array where different values signify some state in the path. The values are as follows: 0 - a free cell 1 - a blocked cell (cannot take) 2 - the start point 3 - the end point 4 - an explored point All algorithms will expose 3 public functions: a constructor, the step function, and a boolean solved function. """ def __init__(self, board: Board): self._board = board self._start = board.start() self._end = board.end() self._path = [] def step(self) -> (int, int): """Advances the algorithm through one iteration exploring one more position on the board Returns a tuple of the position explored """ pass def running(self) -> bool: """ Returns a boolean value of whether the algorith has found a True - path has been found/no possible path False - path has not been found """ pass def set_path(self): self._board.set_path(self._path)
true
5d3f9ba65e4c68e743ea21a0db8dbbb54c92bd6f
prahate/python-learn
/python_classes.py
926
4.21875
4
# self is defined as an instance of a class(similar to this in c++),and variables e.g. first, last and pay are called instance variables. # instance variables are the ones that are unique for each instance e.g. first, last and pay. They are unique to each instance. # __init__ is called as constructor(in languages like c++), this function is called as soon as we create object/instance of the class. # we can pass default values to functions as __init__(self, pay=3000) class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay def full_name(self): return '{} {}'.format(self.first, self.last) # below e1 and e2 are called instances of class employee e1 = Employee('Prath', 'rahate', 5000) e2 = Employee('Prathamesh', 'rahate', 5000) print(e1.full_name()) # other way to call function instaed of using object # print(Employee.full_name(e1)) print(e2.full_name())
true
e9d4a5afa1859ec6b3ad87a3000bee910afef669
prahate/python-learn
/python_sqlite.py
698
4.5
4
import sqlite3 # Creating a connection sqlite database, it will create .db file in file system # other way to create is using memory, so database will be in memory (RAM) # conn = sqlite3.connect(':memory:') conn = sqlite3.connect('employees.db') # To get cursor to the database c = conn.cursor() # Create table using cursor #c.execute("""CREATE TABLE employees # ( # first test, # last text, # pay integer # )""") #c.execute("""INSERT INTO employees VALUES ('sheldon', 'cooper', '50000')""") c.execute("SELECT * FROM employees WHERE last='cooper'") print(c.fetchone()) # Always use conn.commit after execute statement conn.commit() # always good to close a connection conn.close()
true
3175206b9d152bed4e484eff5dc8c229c9fa74af
ruthiler/Python_Exercicios
/Desafio077.py
526
4.15625
4
# Desafio 077: Crie um programa que tenha uma tupla # com várias palavras (não usar acentos). Depois disso, # você deve mostrar, para cada palavra, quais são as suas vogais. palavras = ('aprender', 'programar', 'linguagem', 'python', 'curso', 'gratis', 'estudar', 'praticar', 'trabalhar', 'mercador', 'programador', 'futuro') for p in palavras: print('\nNa palavra {} temos '.format(p.upper()), end='') for letra in p: if letra.lower() in 'aeiou': print(letra, end=' ')
false
6cd508557a1fe3d17d7e1eb8a051e0b5282b96cf
ruthiler/Python_Exercicios
/Desafio085.py
630
4.21875
4
# Desafio 085: Crie um programa onde o usuário possa digitar sete valores # númericos e cadastre-os em uma lista única que mantenha separados os valores # pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente # encoding: utf-8 numeros = [[], []] for n in range(1, 8): num = int(input('0{}º número: '.format(n))) if num % 2 == 0: numeros[0].append(num) else: numeros[1].append(num) numeros[0].sort() numeros[1].sort() print('-=' * 35) print('Os valores pares digitados foram: {}'.format(numeros[0])) print('Os valores ímpares digitados foram: {}'.format(numeros[1]))
false