blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d6f6ecb597499b253b1ccb1c7230c8eb03713ee8
AdamC66/Aug-19th-01---Reinforcing-Exercises-OOP
/reinforcement.py
1,362
4.53125
5
# Create a Location class with a name. # Create a Trip class with a list of Location instances (called stops or destinations or something similar). Define a method that lets you add locations to the trip's list of destinations. # Make several instances of Locations and add them to an instance of Trip. # Define a method in the Trip class that iterates through the list of locations and prints something similar to the following: # "Began trip." # "Travelled from Toronto to Ottawa." # "Travelled from Ottawa to Montreal." # "Travelled from Montreal to Quebec City." # "Travelled from Quebec City to Halifax." # "Travelled from Halifax to St. John's." # "Ended trip." class Location: def __init__(self, name): self.name = name class Trip: def __init__(self): self.stops = [] def add_stop (self, stop): self.stops.append(stop) def describe_trip(self): print("Began trip") for i in range(len(self.stops)-1): print(f'Travelled from {self.stops[i].name} to {self.stops[i+1].name}') print('Finished trip') toronto = Location('Toronto') halifax = Location('Halifax') montreal = Location('Montreal') winnipeg = Location('Winnipeg') my_trip = Trip() my_trip.add_stop(toronto) my_trip.add_stop(halifax) my_trip.add_stop(montreal) my_trip.add_stop(winnipeg) my_trip.describe_trip()
true
16be0297f5741502884686ed20ef2be72931d9d4
majard/prog1-uff-2016.1
/Main Diagonal.py
388
4.1875
4
matrix = [] for i in range(3): line = [] for j in range(3): line.append(eval(input('Input column {}, row {}: '.format(i + 1, j + 1)))) matrix.append(line) k = eval(input('Input k: ')) print('Matrix before multiplying: ', matrix) for i in range(3): matrix[i][i] *= k #the main diagonal is where j = i print('Matrix after multiplying: ', matrix)
false
3dba82bc1968aa513c1877678adbc9fda8ac36ab
majard/prog1-uff-2016.1
/BACKWARDS.py
330
4.3125
4
def upper_backwards(string): string = string.upper() new_string = '' last_char = -len(string) - 1 for char in range(-1, last_char, -1): new_string += string[char] return new_string string = input('Input a string: ') print('This string backwards is "{}"'.format(upper_backwards(string)))
true
eeaa9843d04f91ade26d7ef612123d34226ecfa4
watxaut/python_training
/src/examples/the_magic_behind_mutable_vars.py
1,389
4.65625
5
# As mutable types, they are pointing to the same memory location (they are pointers, like C), so if you have the great # idea of doing list_1 = list_2, you won't be copying the list, you will be actually copying the pointer location, so if # you change one, the other also changes. Play the video! -> # instantiate a list whoops_list = ["I", "am", "really good", "at Python"] # play with the devil i_am_really_bad_at_python_list = whoops_list i_am_really_bad_at_python_list.append("..OR AM I????") print(whoops_list) # will print ["I", "am", "really good", "at Python", "..OR AM I????"] print(i_am_really_bad_at_python_list) # will print ["I", "am", "really good", "at Python", "..OR AM I????"] # And of course, you can check if they are the same object with 'is'. Spoiler, it's True print(whoops_list is i_am_really_bad_at_python_list) # WAIT, so if I want to copy a list, how do I do it? # --> METHOD 1: The Pythonic way import copy list_copy = copy.deepcopy(whoops_list) print(list_copy is whoops_list) # Spoiler, it's False # --> METHOD 2: The 'I don't have time for this!' guy - don't be this guy list_copy_2 = whoops_list[:] print(list_copy_2 is whoops_list) # Spoiler, it's False # This, obviously, happens with every MUTABLE variable. So you have to know exactly what you are doing when doing # this_mutable_var = this_other_mutable_var. Don't say I didn't warn you
true
2d1b3bac51f7b7564fc847c9b34c88682b329966
mennthor/splines
/SciPy_UnivariateSpline.py
852
4.15625
4
import numpy as np import scipy.interpolate as si import matplotlib.pyplot as plt # Known function values = N equally spaced data points N = 10 x = np.linspace(0, 10, N) y = np.sin(x)**2 # Find the interpolating cubic spline. It goes through all data points (x,y) tck = si.splrep(x, y) # Construct a smoothing cubic spline with less points than data points given smooth = si.UnivariateSpline(x, y, s=0.1) # Plot values for the underlying true function (x2,yt) x2 = np.linspace(0, 10, 200) yt = np.sin(x2)**2 # Plot values for resulting spline (x2,y2) y2 = si.splev(x2, tck) # Plot values for smoothing spline (x2, y3) y3 = smooth(x2) # Plot used knots, splines and true function plt.plot(x, y, 'o', label="knots") plt.plot(x2, yt, label="true") plt.plot(x2, y2, label="spline") plt.plot(x2, y3, label="smooth") plt.legend(loc="best") plt.show()
true
d1836ca3bc8367464b03fa04b6a3f7f660d544b7
AndreKauffman/EstudoPython
/Exercicios/ex073 - Tuplas com Times de Futebol.py
488
4.15625
4
times = 'São Paulo', 'Corinthias', 'PaLmeiras', 'Santos', 'Atl.Mineiro', "Real", 'Barcelona', 'Atl.Madrid', 'Milan', 'Bayern' print('-='*8) print("Lista de Times: {}".format(times)) print('-='*8) print("Os cinco primeiros são {}".format(times[0:5])) print('-='*8) print("Os quatro ultimos são {}".format(times[6:])) print('-='*8) print('Em ordem alfabetica são: {}'.format(sorted(times))) print('-='*8) print(f"O Barcelona está na {times.index('Barcelona')+1}° posição")
false
6317aedc90f3f0f1be117b2d7c87bc5976c42e36
AndreKauffman/EstudoPython
/Exercicios/ex042 - Analisando Triângulos v2.0.py
578
4.15625
4
lado1 = float(input("Digite um lado do triangulo: ")) lado2 = float(input("Digite um outro lado do triangulo: ")) lado3 = float(input("Digite um outro lado do triangulo: ")) if lado1 < lado2 + lado3 and lado2 < lado1 + lado3 and lado3 < lado1 + lado2: print("Formam um triangulo.....") if lado1 == lado2 == lado3: print("é um triangulo equilatero") elif lado1 == lado2 or lado2 == lado3 or lado3 == lado1: print("é um triangulo isósceles") else: print("é um triangulo escaleno") else: print("Não pode formar")
false
5d1d157f3b919b8692115089262b691ed155dc52
ybcc2015/PointToOffer
/stack&queue.py
1,453
4.125
4
# 1.用两个栈实现一个队列 class MyQueue(object): def __init__(self): self.stack1 = [] self.stack2 = [] # 入队 def append_tail(self, value): self.stack1.append(value) # 出队 def delete_head(self): if len(self.stack2) == 0: if len(self.stack1) != 0: while len(self.stack1) != 0: value = self.stack1.pop() self.stack2.append(value) else: raise Exception("queue is empty") head = self.stack2.pop() return head def __len__(self): return len(self.stack1) + len(self.stack2) # 两个队列实现一个栈 class MyStack(object): def __init__(self): self.que1 = MyQueue() self.que2 = MyQueue() # 入栈 def push(self, value): self.que1.append_tail(value) # 出栈 def pop(self): if len(self.que1) == 0: raise Exception("stack is empty") elif len(self.que1) == 1: value = self.que1.delete_head() else: while len(self.que1) != 1: self.que2.append_tail(self.que1.delete_head()) value = self.que1.delete_head() while len(self.que2) != 0: self.que1.append_tail(self.que2.delete_head()) return value if __name__ == '__main__': stack = MyStack()
false
454b4b3fb38071bbf3f93e87a1a5b895a08d5734
matty2cat1/unit-1
/slope.py
379
4.15625
4
#Matt Westelman #1/18/18 #slope.py - What is the slope? xPoint1 = float(input("x1 = ")) yPoint1 = float(input("y1 = ")) xPoint2 =float(input("x2 = ")) yPoint2 = float(input("y2 = ")) print("slope = ", round((xPoint1-xPoint2)/(yPoint1 - yPoint2), 3)) slope = round((xPoint1-xPoint2)/(yPoint1 - yPoint2), 3) b = yPoint1-slope*xPoint1 print("b = ", b) print ("y = ", slope, "x + ", b)
false
7b1a69a20573cf0dba4480d84db18c444448ce53
m2angie94/BirthdayCalculator
/app.py
2,118
4.46875
4
todays_years =input("1. What year is it?: " ) todays_month =input("2. What month is it? Write full month, first letter capitalized. ") todays_day = input("3. What day of the month is this month? Just type the number. ") print("Today is " + todays_month + " " + todays_day + "," + " " + todays_years + ".") year = input("4. What year were you born?: ") month = input("5. What month were you born?: ") day= input("6. What day of the month were you born: ") print("You were born " + month + " " + day + "," + " " + year + ".") month_dictionary = {'January': 1, 'February': '2', 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12} #age = 2019- int(year) #print("You are " + str(age) + " " + "years old, as of Dec 2019. ") birth_month = month_dictionary[month] birth_month = int(birth_month) todays_month = month_dictionary[todays_month] todays_month = int(todays_month) new_month_age = 12 -int(birth_month) + int(todays_month) new_year_age_notyet = int(todays_years) -1 -int(year) new_year_age = int(todays_years) -int(year) if birth_month > todays_month: print("You haven't had a birthday yet this year :(") print("You are " + str(new_year_age_notyet) + " "+ "years old and" + " " + str(new_month_age) + " " + "months.") elif birth_month == todays_month and todays_day == day: print("Happy Birthday! You are " + str(new_year_age) + " " + "years old today!") elif birth_month == todays_month and todays_day > day: print("You are " + str(new_year_age) + " " + "years old. Happy Belated Birthday!") elif birth_month == todays_month and todays_day < day: print("You are " + str(new_year_age_notyet) + " " + "years old. Your birthday is coming up soon!") elif birth_month < todays_month: print ("It seems that your birthday has already passed, Happy Belated. You are " + " " + str(new_year_age) + " " + " years old and" + str(new_month_age) + " " + "months.") #print(birth_month) #print(todays_month) #print(str(new_month_age)) #print(new_year_age)
false
26958af38ca32e879a67ef44e154169e83064e22
dotslash-web/PY4E
/Course 4 - Using Databases with Python/Chapter 14 - Objects/Lecture Material/ObjectInheritance.py
947
4.375
4
'Inheritance' #When we make a new class - we can reuse an existing class and inherit all the capabilites of an existing class # and then add our own little bit to make our new class #Another form of store and reuse #Write once - reuse many times #The new class (child) has all the capabilities of the old class (parent) - and then some more class PartyAnimal: x = 0 name = "" def __init__(self, nam) : self.name = nam print(self.name, "constructed") def party(self) : self.x = self.x + 1 print(self.name, "party count", self.x) class FootballFan(PartyAnimal) : #a class which extends PartyAnimal. It has all the capabilites of PartyAnimal and more points = 0 def touchdown(self) : self.points = self.points + 7 self.party() print(self.name, "points", self.points) s = PartyAnimal("Sally") s.party() j = FootballFan("Jim") j.party() j.touchdown()
true
5f965385283d0c20c83b1c59fc640bca79c29f40
dotslash-web/PY4E
/Course 1 - Getting Started with Python/Chapter 2/Assignments/Assignment2-2.py
299
4.40625
4
''' 2.2 Write a program that uses input to prompt a user for their name and then welcomes them. Note that input will pop up a dialog box. Enter Sarah in the pop-up box when you are prompted so your output will match the desired output. ''' name = input("Enter your name") print("Hello " + name)
true
a23c84844941f6f5a4c71570d92642fa42fd38a3
dotslash-web/PY4E
/Course 2 - Python Data Structures/Chapter 08/Assignments/Assignment8-4.py
751
4.34375
4
'''8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.py4e.com/code3/romeo.txt''' fname = input('Enter file name: ') try: fhandle = open(fname) except: print('Error, could not open:', fname) quit() words = list() for line in fhandle : temp = line.strip().split() for w in temp : if w not in words : words.append(w) words.sort() print(words)
true
a43385002091dfd8a306c83a1340ff9df67faea4
ANKITPODDER2000/LinkedList
/27_lengthisEven.py
290
4.1875
4
from LinkedList import LinkedList from LinkedListHelper import CreateLinkedList def evenLength(l1): return (l1.length() % 2) == 0 def main(): l1 = LinkedList() CreateLinkedList(l1) print("Length of linkedlist is even : ",evenLength(l1)) if __name__ == "__main__": main()
false
f1c54f234b47b962339c32273c451e44445008aa
ANKITPODDER2000/LinkedList
/21_merge_list.py
736
4.25
4
from LinkedList import LinkedList from LinkedListHelper import CreateLinkedList def merge(head1 , head2): l1 = LinkedList() while head1 or head2: if not head1: l1.insert_end(head2.val) head2 = head2.next elif not head2: l1.insert_end(head1.val) head1 = head1.next elif head1.val > head2.val: l1.insert_end(head2.val) head2 = head2.next else: l1.insert_end(head1.val) head1 = head1.next return l1 def main(): l1 = LinkedList() CreateLinkedList(l1) l2 = LinkedList() CreateLinkedList(l2) l3 = merge(l1.head , l2.head) l3.display() if __name__ == "__main__": main()
false
1cdeb7ce14fff2e6ba0b80a7ce286fad2e1b66c4
coding1408/Python-Lessons
/Calculator.py
1,001
4.125
4
def addition(a, b): c = a + b return c def subtration(a, b): c = a - b return c def multiplication (a, b): c = a * b return c def division (a, b): c = a / b return c if __name__ == "__main__": print("Type quit at sign selection to quit") while True: number1 = int(input(" pick a number: ")) number2 = int(input(" pick another number: ")) sign = input("What sign (add, sub, div, mult): " ) if sign == "quit": break if sign == "add" or sign=="+": answer = addition(number1, number2) elif sign == "sub" or sign =="-": answer = subtration(number1, number2) elif sign == "div" or sign == "/": answer = division(number1, number2) elif sign == "mult" or sign == "*": answer = multiplication(number1, number2) else: answer = "Error, you either put a none int number or wrong spelling on sign" print(answer) print("you broke")
true
6440e974d127db155f9513cdadc1ce3ef8dd2758
alfonsog714/Algorithms
/stock_prices/stock_prices.py
1,616
4.34375
4
#!/usr/bin/python import argparse """ Example case: input of [1050, 270, 1540, 3800, 2] should return 3530 (why?) 1050: -------- -1050 + 270 = -780 -1050 + 1540 = 490 -1050 + 3800 = 2750 -1050 + 2 = -1048 270: ------- -270 + 1540 = 1270 -270 + 3800 = 3530 -270 + 2 = -268 1540: ------- -1540 + 3800 = 2,260 -1540 + 2 = -1,538 """ def find_max_profit(prices): # Example input: [1050, 270, 1540, 3800, 2] # 0 1 2 3 4 # Track the best profit so far max_profit_so_far = -20000 # better way of doing this somewhere \\ negative infinity or first profit as the base for i in range(0, len(prices)): # [1050, 270, 1540, 3800, 2] current_stock_price = prices[i] # print(f"Line 37: {current_stock_price}") for j in range(i + 1, len(prices)): # 1050, 270, [1540, 3800, 2] # print(f"Line 39: {prices[j]}") if -current_stock_price + prices[j] > max_profit_so_far: max_profit_so_far = -current_stock_price + prices[j] # print(f"Line 42: {max_profit_so_far}") # print(f"End price: {max_profit_so_far}") return max_profit_so_far # print(find_max_profit([100, 90, 80, 50, 20, 10])) if __name__ == '__main__': # This is just some code to accept inputs from the command line parser = argparse.ArgumentParser(description='Find max profit from prices.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price') args = parser.parse_args() print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))
false
431b0073b3a540c522b29b3306fb0b490c090c54
ramyamango123/test
/python/python/src/Practice1/ex3.py
284
4.1875
4
# To find no of chars present in each word of a list z = ['I', 'am', 'arranging', 'this', 'again', 'carry', 'this', 'this'] for eachword in z: count = 0 for eachchar in eachword: count += 1 print "Total no of letters in" , eachword , "is :" , count
true
8a6ab299fb1026147946761d2d2a4e6a9543c5e2
LawerenceLee/regex_PY
/address_book.py
2,659
4.21875
4
#This the regular expressions library import re #names file is a pointer to location of the file in the file system names_file = open("names.txt", encoding='utf-8') #Reads file and saves it to data data = names_file.read() #closes file and takes it of memory names_file.close() last_name = r'Love' first_name = r'Kenneth' #r tells python that string is a raw string #print(re.match(last_name, data)) #match looks to match at the beginning of the string #print(re.search(first_name, data)) #search looks to match at any part of the string #print(re.search(r'\(\d\d\d\) \d\d\d-\d\d\d\d', data)) #re.search only searches one line. re.findall searches entire document #print(re.findall(r'\(?\d{3}\)?-?\s?\d{3}-\d{4}', data)) #print(re.search(r'\w+, \w+', data)) #print(re.findall(r'\w*, \w+', data)) #print(re.findall(r'[-\w\d+.]+@[-\w\d.]+', data)) #print(re.findall(r'\b[trehous]{9}\b', data, re.I)) #print(re.findall(r''' # \b@[-\w\d.]* #First a word boundary, an @, and then any number of characters # [^gov\t]+ # Ignore 1+ instances of letters 'g', 'o', 'v' and a tab. # \b # Match another word boundary #''', data, re.VERBOSE|re.I)) #print(re.findall(r''' # \b[-\w]*, # Find a word boundary, 1+ hyphens or characters, and a comma # \s # Find 1 whitespace # [-\w]+ # 1+ hyphens and characters and explicit spaces # [^\t\n] # Ignore tabs and newlines #''', data, re.X)) #line = re.search(r''' # ^(?P<name>[-\w ]*,\s[-\w ]+)\t # Last and first names # (?P<email>[-\w\d.+]+@[-\w\d.]+)\t # Email # (?P<phone>\(?\d{3}\)?-?\s?\d{3}-\d{4})?\t # Phone # (?P<job>[\w\s]+,\s[\w\s.]+)\t? # Job and Company # (?P<twitter>@[\w\d]+)?$ # Twitter #''', data, re.X|re.MULTILINE) #print(line) #print(line.groupdict()) # Code Challenge # Create a variable names that is an re.match() against string. The pattern should provide two groups, one for a last name match and one for a first name match. The name parts are separated by a comma and a space. #import re #string = 'Perotto, Pier Giorgio' #names = re.match(r'([-\w]+),\s([-\w ]+)', string) line = re.compile(r''' ^(?P<name>(?P<last>[-\w ]*),\s(?P<first>[-\w ]+))\t # Last and first names (?P<email>[-\w\d.+]+@[-\w\d.]+)\t # Email (?P<phone>\(?\d{3}\)?-?\s?\d{3}-\d{4})?\t # Phone (?P<job>[\w\s]+,\s[\w\s.]+)\t? # Job and Company (?P<twitter>@[\w\d]+)?$ # Twitter ''', re.X|re.MULTILINE) #print(re.search(line, data).groupdict()) # This also works. line could be any pattern #print(line.search(data).groupdict()) for match in line.finditer(data): #print(match.group('name')) print('{first} {last} <{email}>'.format(**match.groupdict()))
true
6a458d2ca0da627db2ea7558fb02f1b655cfc0db
STEADSociety/FBC
/logest_name.py
201
4.21875
4
words = ["hello", "world", "hi", "bye"] def longest_word(data): max_len = len(max(data, key=len)) return [word for word in data if len(word) == max_len] print(longest_word(words))
false
3ccbf7fa9be1dc41987677bbf036658285cb7eea
rjmckenney/Learning-Python-the-Hard-Way-
/ex6.py
1,000
4.21875
4
# this variable equals "there are types of people" x = "There are %d types of people." % 10 # variable called binary binary = "binary" #variable do _not do_not = "don't" # variable y adding Binary, do_not where the place holders are # This where a String is placed inside of a String y = "Those who know %s and those who %s." % (binary, do_not) # this will print x variable print x #this will print y variable print y #this will print string with variable x # This where a String is placed inside of a String print "I said: %r." % x # this will pring string with variable y # This where a String is placed inside of a String print "I also said: '%s'." % y # will print answer to question hilarious = False # will print question joke_evaluation = "Isn't that joke funny?! %r" # print together on the same line question & answer print joke_evaluation % hilarious # Variables w & e w = "This is the left side of ..." e = "a string with a right side." # prints both variables together print w + e
true
6b4e077e8808172860164b9202d3f6e63da1493f
kbongco/python-practice
/Day 2/2-2.py
332
4.3125
4
#List Less than ten #Found on practicepython.org #Take a list, say for example this one: #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #write a program that prints out all the elements of the list that are less than 5. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] less = [] for x in a: if x < 5: less.append(x) print(less)
true
f9ef60ff1eccc3371c852e2ce3d199df5ab808f8
wilsonn/PythonBasico
/EjerciciosEstructurasSeleccion/MayorMenorTresNumeros.py
908
4.28125
4
print("######Mayor y Menor de Tres Numeros######") num1 = float(input("Ingresar primer numero")) num2 = float(input("Ingresar segundo numero")) num3 = float(input("Ingresar tercer numero")) if num1 > num2: if num1 > num3: if num2 < num3: print("El numero mayor es: ", num1) print("El numero menor es: ", num2) else: print("El numero mayor es: ", num1) print("El numero menor es: ", num3) else: print("El numero mayor es: ", num3) print("El numero menor es: ", num2) else: if num2 > num3: if num1 > num3: print("El numero mayor es: ", num2) print("El numero menor es: ", num3) else: print("El numero mayor es: ", num2) print("El numero menor es: ", num1) else: print("El numero mayor es: ", num3) print("El numero menor es: ", num1)
false
8cc9f0c84b938c722b5bed0eaa1bcdd043e6334f
chrisliatas/py_practice
/practice_3.py
1,365
4.5625
5
#----------------------------------------# # Question 19 # Level 3 # Question: # You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: # 1: Sort based on name; # 2: Then sort based on age; # 3: Then sort by score. # The priority is that name > age > score. # If the following tuples are given as input to the program: # Tom,19,80 # John,20,90 # Jony,17,91 # Jony,17,93 # Json,21,85 # Then, the output of the program should be: # [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] # Hints: # In case of input data being supplied to the question, it should be assumed to be a console input. # We use itemgetter to enable multiple sort keys. from operator import itemgetter def sort_students(): students = [] while True: student = input('Enter student data tuple (name,age,height): ') if student: # students.append(tuple([int(i) if i.isdigit() else i for i in student.split(',')])) students.append(tuple(student.split(','))) else: break print(sorted(students, key=itemgetter(0,1,2))) def testtupl(tpl): return tpl[2] if __name__ == '__main__': print(testtupl((4,5,6,7,8)))
true
224fe537c862780520c7436d370dbfaaeccfb653
deciduously/cmit135
/week3/guessing_game.py
664
4.21875
4
# guessing_game.py asks the user to guess its random nmber between 0 and 9 import sys # Select winning number from random import randint randomNum = randint(0, 9) # Function to get input and close the program if it's not an integer def getInt(): raw = input() try: return int(raw) except: print('Must be an integer!') sys.exit() # Gather input print('Enter your guess') guess = getInt() # Output either a win or a loss if guess == randomNum: print('You win! The number was ' + str(randomNum)) else: print('Sorry! Your guess of ' + str(guess) + ' does not match the winning number ' + str(randomNum))
true
1da5693613af676b6218173be8e0870435f4b8b1
deciduously/cmit135
/week4/multiplication.py
827
4.40625
4
# multiplication.py pretty prints a multiplication table # Function to return the number of digits a number n has def num_digits(n): # Converts it to a string a counts the length - the math way would work too but this is easy return len(str(n)) def draw_table(n): # calculate this outside the loop so we dont run it every iteration total_size = n*n for i in range(1, n): for j in range(1, n): # Print the product of the indices current_cell = i*j # Use the size difference betwene the max value and the current value to determine current cell padding padding = ' ' * (1 + num_digits(total_size) - num_digits(current_cell)) print(padding + str(i*j), end="") print() # draw with 10 draw_table(10)
true
9f92f0a4c566fe219a0de51a3c60448d18bbd5a3
mahesh-248/Programming_Practice_For_Beginners
/Python/Fibonacci.py
268
4.21875
4
endpt=int(input("How many numbers in fibonacci sequence you wish to print ")) first=0 second=1 third=0 print("%d\n%d"%(first,second)) for i in range(0,endpt): third=first+second first=second second=third print("%d"%third) #Contributed by Anurag
true
b9267e1d86b54619d81a54368e817268c7c0dd08
vincexi/algorithms
/arrays.py
790
4.28125
4
# An array is called monotonic if it is either monotone increasing or monotone decreasing. def isMonotonic(array): increasing = 0 for idx, i in enumerate(array): if idx+1 < len(array): if i < array[idx+1]: increasing += 1 return True if increasing == len(array) - 1 or increasing == 0 else False # Find the three largest numbers in an array def findThreeLargestNumbers(array): largest, second, third = float('-inf'), float('-inf'), float('-inf') for i in array: if i >= largest: third = second second = largest largest = i elif i >= second: third = second second = i elif i >= third: third = i return [third, second, largest]
true
362f6bc7d16ae3e70046abdf6101715aac57fc01
euirim/simple-analytics
/simplea/utils.py
415
4.3125
4
def add_suffix(txt, suffix): """add the given to every element in given comma separated list. adds suffix before -. Example: add_suffix("hello,john", "ga:") -> "ga:hello,ga:john" """ if txt is None: return None elements = txt.split(",") elements = ["-" + suffix + e[1:] if e[0] == "-" else suffix + e for e in elements] return ",".join(elements)
true
ad8446aad5f542b5b59836cba009c32403024ae0
DavidYi/Intro-to-Computer-Science-Trimester-1
/Python/KilogramsAndPounds.py
512
4.125
4
#Unit 1-Kilograms and Pounds #David Yi print("Kilograms\tPounds") #This variable acts as the counter as well as the kilograms x=1 while (x<200): #This variable is the pounds and it converts whatever x kg is to lbs. The following equations puts the decimal up to the tenths place y=10*(x*(2.2)) y//=1 y/=10 #This makes it so that it only prints odd integers of x if (x%2==1): print(x,"\t\t",y) #Acts as the counter so that the while loop can end at one point and it is used as kg x+=1
true
fdc2417d645db8e5a7701908840d4ce78e2a5c6f
DavidYi/Intro-to-Computer-Science-Trimester-1
/Python/AnalyzingScores.py
1,349
4.28125
4
def readinput(): numbers=input("Enter some numbers: ") lists=numbers.split() return lists def findmean(numlist): total=0 counter=0 for num in numlist: total+=int(num) counter+=1 mean= total/counter return mean def findifgreater(numlist, mean): x=0 #This variable will be used to count if the number is greater or equal to the mean for num in numlist: #This will cause num to go through every element in numlist if (int(num)>=mean): x+=1 #This adds one to y if the num is equal to or greater than the mean return x #returns the variables def findiflesser(numlist, mean): x=0 #This variable will be used to count if the number is less than the mean for num in numlist: if (int(num) < mean): x+=1 #This adds one to x if the num is less than the mean return x def main(): mylist=readinput() mymean=findmean(mylist) greater= findifgreater(mylist, mymean) lesser=findiflesser(mylist, mymean) print("The list of numbers are:", mylist) print("The mean of these numbers is:", mymean) print("The number of values equal to or greater than the mean is:", greater) print("The number of values less than the mean is:", lesser) #Calls all the functions and prints them out main()
true
27607e16a9473a772b39a29952f57d29cc7e9bc7
DavidYi/Intro-to-Computer-Science-Trimester-1
/Python/Dictionaries.py
984
4.3125
4
test_dict= {} #Makes empty dictionary test_dict["yankees"] = 80 test_dict["red soxes"] = 100 test_dict["blue jays"] = 95 """instead of a list where everything are defined by 0, 1, 2,...,n and u call them like list[0], you define them to whatever like this where where the "0" can become""" print("The yankees won", test_dict["yankees"], "games.") #print("The phillies won", test_dict["phillies"], "games.") #This alone is going to cause an error because there is no key for it and it prints out KeyError: 'phillies' games= test_dict.get("phillies", -10) """However, you can use this and it says that if there is no key, 'phillies', then -10 will be the value of the key. Does not add this to the dictionary""" print("The phillies won", games, "games.") key_lists= list(test_dict.keys()) #This converts all the keys to a list ***Not the value of the key the NAME*** key_lists.sort() for team in key_lists: #Finds the lists of the print(team+" won", test_dict[team], "games.")
true
68d93a96f1a5528d8ca64be34466b43665f23255
DavidYi/Intro-to-Computer-Science-Trimester-1
/Python/ReversePolishNotationCalculator.py
917
4.21875
4
#Unit 1- Reverse Polish Notation Calculator #David Yi #Sentry Variables/ variables I will use #Operands x=0 y=0 #Operators z="" #This prints out something and finds what x and y equals print("Input:") x=float(input()) y=float(input()) #This makes a loop while (y!='='): #This finds what the operator the user would like to use and stores it z=input() #This is to use the operator and operand and find the current total and make sure the key wasn't invalid if (z=='+'): x+=float(y) elif (z=='-'): x-=float(y) elif (z=='/'): x/=float(y) elif (z=='*'): x*=float(y) else: raise SyntaxError("Read token%s, expected operator" %z) #This finds what the next number will be or if they want to find the total because it loops again y=input() #This prints out output and the total with it rounded to the nearest hundreths print("Output:") print("%.2f" %(x))
true
221486f9bf2840b51315873c97d15eec054108fa
DavidYi/Intro-to-Computer-Science-Trimester-1
/Python/ListsOperations.py
839
4.4375
4
print ("Enter some numbers") num_list=[] #Creates empty lists num = int(input()) while (num!=0): num_list.append(num) #This adds an element to end of list num=int(input()) print(num_list) num_list.reverse() #This reverses the order of the list as the name implies print("Reverse:", num_list) num_list.sort() #This sorts the list according to smallest to biggest print("Min:", min(num_list)) #This finds the minimum of the list and can also be put as num_list.min() print("Max:", max(num_list)) #This finds the maximum of the list and can also be put as num_list.max() print("Len:", len(num_list)) #This finds the length of the list or number of elements in the list. print("List[2]:", num_list[2]) #Prints the 2nd element in the list list_product=1 for num in num_list: list_product *=num print("list_product:", list_product)
true
bf63325df962171d50c971ccf814fe9404d413e1
shilpasayura/algohack
/code-algo/golden.py
1,039
4.3125
4
#Golden Angle # in geometry, the golden angle is the smaller of the two angles # created by sectioning the circumference of a circle # according to the golden ratio. # Golden Angle ≈ 137.5° # Plants have their leaves spread all around the stem to soak # up as much sun as possible. # Using the golden angle between two consecutive leaves # is the most effective approach to spread the leaves around the stem. Let’s see how this work: import turtle import time def drawCircle(x, y, radius, color): global myPen myPen.setheading(0) myPen.penup() myPen.color(color) myPen.fillcolor(color) myPen.goto(x,y-radius) myPen.begin_fill() myPen.circle(radius) myPen.end_fill() myPen.pendown() myPen = turtle.Turtle() myPen.hideturtle() myPen.speed(0) #Draw Trunc drawCircle(0, 0, 20 , "#705623") myPen.goto(0,0) myPen.width(4) goldenAngle=137.5 myPen.setheading(90) for branch in range(0,50): #Draw Branch myPen.forward(150) myPen.forward(-150) myPen.right(goldenAngle) time.sleep(1)
true
0ecc5ba64ffce218f9c1b245c4bd444bab646a80
ogabriel/python_CS
/exercises_p1/ex_23.py
376
4.15625
4
num = int(input("Insira um número: ")) def prime(num): aux = num while(aux > 2): aux -= 1 if num % aux == 0: return False return True def not_prime(): print("Ñ é primo") def is_prime(): print("Primo") if(num == 2): is_prime() elif(num % 2 == 0): not_prime() elif(prime(num)): is_prime() else: not_prime()
false
d494c79723c92ebf10f19169223a25e29cb5baae
tjashaG/world_capitals_quiz
/main.py
1,656
4.21875
4
import datetime import time from generate_country import * # IDEA to expand: # could have capitals by continents (easy version) and all countries (difficult) name = input("Welcome to the world capitals quiz game! What's your name? ") print("Here are some RULES:") time.sleep(2) print("Watch your spelling, but you don't need to capitalize.") time.sleep(3) print("If you get stuck or just plain don't know, type in /help/ to get a hint.") time.sleep(3) print("You have two hints per question. The third time you type in help, it gives you the answer.") time.sleep(5) num_of_questions = int(input("How many questions would you like? ")) correct_answers = 0 wrong_answers = 0 for question in range(num_of_questions): question = generate_country() # generate random country through function num_of_questions -= 1 # reduce number of questions by one if question: # if correct answer, the function returns True correct_answers += 1 # if the user answers correctly, a correct answer is added else: wrong_answers += 1 #appending scores to capitas_scores in form of dict scores.append({ "name" : name, "correct answers" : correct_answers, "all questions" : (correct_answers + wrong_answers), "date" : str(datetime.date.today()) }) new_scores = json.dumps(scores) p2.write_text(new_scores) print(f"You answered {correct_answers} questions correctly out of {correct_answers + wrong_answers}!") #gives player chance to view scores see_scores = input("Would you like to see how others scored? (y/n) ") if see_scores == "y": for score in scores: print(score)
true
a83b7721e89627dd2a6c16202f4b28691b0c6034
Rushi21-kesh/30DayOfPython
/Day-8/Day_8_Ayushi.py
507
4.34375
4
# Day-8 Question for the day-8 is ---> # -> Question: Write a program to print the sum of all the even numbers between n and m ( n and m are user input). # -> Input: Take two number as input from the user and store it in a variables. # -> Output: print the sum of all even number between n and m. # -> Example # Input: n=0,m=10 # Output: 20 n = int(input("Enter starting number: ")) m = int(input("Enter ending number: ")) sum=0 for i in range(n+1,m): if i%2==0: sum+=i print("Sum: ",sum)
true
7426b634a8935bb6b507f879e2c2678c6fec2242
Rushi21-kesh/30DayOfPython
/Day-10/Day_10_Rushikesh_Lavate.py
854
4.1875
4
# method 1: using inbuilt function def sum_nat_1(num): s = sum(range(num+1)) print("Sum of natural number using inbuilt function is : ",s) # method 2: using mathematical formula def sum_nat_2(num): s = int((num*(num+1))/2) print("Sum of natural number using mathematical formula is : {}".format(s)) # method 3: using recursion # default recursion limit is 1000, it means that function call on itself only 1000 times # we can set it our own limit using below code import sys sys.setrecursionlimit(999999) def sum_nat_3(num): global s if num==0: s = s + num else: s = s + num return sum_nat_3(num-1) print(f"Sum of natural number using recursion is : {s}") if __name__ == '__main__': s = 0 num = int(input("Enter the number : ")) sum_nat_1(num) sum_nat_2(num) sum_nat_3(num)
true
3aee0344eb500a09192d020f86b6a2fbb7e41d7b
Rushi21-kesh/30DayOfPython
/Day-14/Day_14_AjayrajNadar.py
407
4.125
4
n = int(input('Enter number: ')) arr = [] for i in range (0, n): x = int(input('Enter element: ')) arr.append(x) def BubbleSort(arr): l = len(arr) for i in range(0, l-1): for j in range(0, l-1-i): if arr[j] > arr[j + 1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp BubbleSort(arr) print("The sorted array is:", arr)
false
19bff0a11098aca76d6eff9a5d8f269e96297a80
Rushi21-kesh/30DayOfPython
/Day-14/Day_14_Freya.py
359
4.25
4
#bubble sort n=int(input("enter size of array")) a=[] for i in range(0,n): x=int(input("enter element")) a.append(x) print("Before sorting:",a) def bubble_sort(a): n = len(a) for i in range (0,n-1): for j in range(0,n-i-1): if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j] bubble_sort(a) print("After sorting:",a)
false
5befd806e0c4861f36d457e8f594037bcf9b5bbd
Rushi21-kesh/30DayOfPython
/Day-7/Day7_NikhilDesai.py
825
4.28125
4
value = [] def natural_numbers(num_1, num_2): """ This function returns natural numbers between user inputs :param num_1: 6 :param num_2: 12 :return: [7, 8, 9, 10, 11] """ if (num_1 > 0) & (num_2 > 0): for i in range(1, num_2): num = num_1 + i value.append(num) if num == num_2 - 1: break return value else: for i in range(-1, num_2, -1): num = num_1 + i value.append(num) if num == num_2 + 1: break return value if __name__ == "__main__": num1 = int(input("Enter a 1st Number: ")) num2 = int(input("Enter a 2nd Number: ")) numbers = natural_numbers(num1, num2) print(f'Natural Numbers between {num1} and {num2} are: {numbers}')
false
2d8479fccd505babb7d076d3acda26de63e1eb42
Rushi21-kesh/30DayOfPython
/Day-6/Day_6_Mohit.py
376
4.34375
4
# Write a program to find ascii code of the given input character. i = input("Enter the value whose ASCII value you want to know : ") print(ord(i), "is the ASCII value of ", i, ".") def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2, end='') dec = ord(i) convertToBinary(dec) print(" is the binary conversion of ", i, "'s ASCII value.")
true
67488cb7df6e588c159a7812463ed6a8752c6548
Rushi21-kesh/30DayOfPython
/Day-3/Day_3_AjayrajNadar.py
210
4.125
4
n=int(input('Enter a Number: ')) if n%10 == 0 and n%20 == 0: print("Yes,the number "+str(n)+" is divisible by both 10 and 20") else: print("No,the number "+str(n)+" is not divisible by both 10 and 20")
true
12a2de05e90b1586a4d455104725d422e06dc332
Rushi21-kesh/30DayOfPython
/Day-2/Day_2_Adnan_Samol.py
205
4.28125
4
#Day-2 a = float(input("Enter the number to find cube root:")) def cubeRoot(a): if(a == 0): return 0; else: return (a**(1/3)) print("The cube root of",int(a), "is",cubeRoot(a))
true
d51959fc4066f0b40004c90c2e383b5ed2925610
Rushi21-kesh/30DayOfPython
/Day-7/Day_7_Nidhir.py
231
4.125
4
n=int(input("Enter the starting value n : ")) m=int(input("Enter the ending value m : ")) for i in range(n+1,m): if (n>0 and m>n): print(i,end=" ") else: print("Please enter n>0 or m>n") break
false
ae206fb1b29554c1bb2a9c3421e27a48a079ff76
Rushi21-kesh/30DayOfPython
/Day-21/Day21_DignaM.py
821
4.125
4
# Day-21_Hackclubsal_30DayOfPython_Solution #Program to Implement a Queue with the help of two stacks in Python class Queue: def __init__(self): self.stack1 = [] self.stack2 = [] def enQueue(self, x): while len(self.stack1) != 0: self.stack2.append(self.stack1[-1]) self.stack1.pop() self.stack1.append(x) while len(self.stack2) != 0: self.stack1.append(self.stack2[-1]) self.stack2.pop() def deQueue(self): if len(self.stack1) == 0: print("Q is Empty") x = self.stack1[-1] self.stack1.pop() return x if __name__ == '__main__': q = Queue() q.enQueue(10) q.enQueue(11) q.enQueue(12) print(q.deQueue()) print(q.deQueue()) print(q.deQueue())
false
9777ffcb184d6b7aa33d4cef123ca71ab45a83fd
Rushi21-kesh/30DayOfPython
/Day-2/day_2_Premkumar.py
416
4.5
4
def cubeRoot(a): """ This function returns the cube root of the given value 'a' (assumeing a value is positive) eg:- if a = 125 this function returns cube root of a i.e. 5 """ if a<0: return "Please try with positive number" cubeRootVal = a**(1/3) return round(cubeRootVal, 3) if __name__ == "__main__": a_val = float(input("Enter a valid Number :- ")) print(cubeRoot(a_val))
true
b314297e912b642f3748fed20bcdeba65ee07505
Rushi21-kesh/30DayOfPython
/Day-12/Day12_ShrutiLad.py
328
4.15625
4
n = int(input('Enter number of elements: ')) arr = [] for i in range (0,n): arr.append(int(input('Enter element: '))) print(arr) k = int(input('Enter the element you want to search: ')) def LinearSearch(k, arr): if k in arr: print("Index of element", k, "is", arr.index(k)) else: print(-1) LinearSearch(k, arr)
false
e77ef1d7733ce00e8022ee0ff928af5821fe14b1
pranavraj101/python-
/visual_calculators.py
530
4.15625
4
print("Visual Calculator for Programmers") print("Enter the data as per the operation you have to perform") print("1.for ADDITION") print("2.for SUBTRACTION") print("3.for MULTIPLICATION") print("4.for DIVISION") c=int(input()) print("Enter to number for the above mentioned operation") a=int(input()) b=int(input()) result=0 if(c==1): result= a+b elif(c==2): result=a-b elif(c==3): result=a*b elif(c==4): result=a/b else: print("Invalid input") if(result != 0): print("The required output :",result)
true
abfb3d97f5779bc90fcb73be11cfa33a2fc16126
robertpolak1968/Python
/rob-lekcje-python/fig02_22.py
756
4.21875
4
# Fig. 2.22: fig02_22.py # Compare integers using if structures, relational operators # and equality operators. print "Enter two integers, and I will tell you" print "the relationships they satisfy." # read first string and convert to integer number1 = raw_input( "Please enter first integer: " ) number1 = int( number1 ) # read second string and convert to integer number2 = raw_input( "Please enter second integer: " ) number2 = int( number2 ) if number1 == number2: print "%d is equal to %d" % ( number1, number2 ) if number1 != number2: print "%d is not equal to %d" % ( number1, number2 ) if number1 < number2: print "%d is less than %d" % ( number1, number2 ) if number1 > number2: print "%d is greater than %d" % ( number1, number2 )
true
94badbf2fe799037801cfa8f9a7bb180c7ca8840
flyboy85749/100-days-of-code
/Day30/hangman.py
1,657
4.1875
4
#Step 1 import random stages = [''' +---+ | | O | /|\ | / \ | | ========= ''', ''' +---+ | | O | /|\ | / | | ========= ''', ''' +---+ | | O | /|\ | | | ========= ''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | | | | | ========= ''', ''' +---+ | | O | | | | ========= ''', ''' +---+ | | | | | | ========= '''] end_game = False word_list = ["aardvark", "baboon", "camel"] #TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. chosen_word = random.choice(word_list) lives = 6 # guessed_letters = [] display = [] wordlength = len(chosen_word) for _ in range(wordlength): display += "_" print(display) #TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase. while not end_game: guess = input("Guess a letter: ").lower() # print(guess) # print(guessed_letters) #TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word. for position in range(wordlength): letter = chosen_word[position] print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}") if letter == guess: display[position] = letter if guess not in chosen_word: lives -=1 if lives == 0: end_game = True print("You lose.") print(f"{' '.join(display)}") print(display) if "_" not in display: end_game = True print("You Win!") print(stages[lives])
false
08f726df94fe6ea661bfa81526220bce9897c074
bc-maia/hacker_rank_python
/DataStructure/NestedList.py
1,013
4.25
4
""" # Input Format The first line contains an integer, , the number of students. The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade. # Constraints There will always be one or more students having the second lowest grade. Output Format Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. SAMPLE INPUT: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 SAMPLE OUTPUT: Berry Harry """ if __name__ == "__main__": students = [] for _ in range(int(input())): name = input() score = float(input()) students.append([name, score]) _, scores = zip(*students) second_score = sorted(set(scores))[1] # Set removes duplicated scores names = [name for name, score in students if score == second_score] for name in sorted(names): print(name)
true
b89e20f74b9bd41aa1516e6b88b3627b62340665
jpardike/python-control-flow-lab
/exercises/exercise-5.py
702
4.21875
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it number_sequence = 0 last_number = 1 number_before_last = 0 for i in range(0, 51): number_sequence = last_number + number_before_last number_before_last = last_number last_number = number_sequence print(f'term: {i} / number: {number_sequence}')
true
b4749b8584a56676a80d28c6191ee57133f4d1a0
jazdao/FlashcardCreator
/flashcards.py
2,891
4.125
4
import random print("Flashcard Creator\n-----------------------------------------------------------------") q_number = 1 # question number questions = [] # list of questions answers = [] # list of answers print("Enter 'done' when you have finished registering your flash cards.") question = "N/A" answer = "N/A" while question != "done" and answer != "done": # loop entry of flashcards until input = 'done' print("\nEnter the question for flashcard #", q_number, sep="", end="") print(":") question = str(input()) while question == "done" and q_number == 1: # if input = 'done' at the first entry print("Please create at least one flashcard entry:") question = str(input()) if question == "done" and q_number != 1: # break out of loop if input = 'done' after first entry q_number = q_number - 1 # revert q_number value because no new question added break else: questions.append(question) # add input to question list print("Enter the answer for flashcard #", q_number, sep="", end="") print(":") answer = str(input()) while answer == "done": # cannot create question without answer print("Please first enter the answer for flashcard #", q_number, sep="", end="") print(":") answer = str(input()) answers.append(answer) # add input to answer list q_number += 1 print("\nWould you like to review the flashcards (yes/no)?") test = str(input()) while test != "yes" and test != "no": # if non-answer print("\nPlease enter either 'yes' or 'no':", end=" ") test = str(input()) if test == "yes": # review flashcards print("\nEnter 'show' to reveal the answer, 'next' to move on to the next card, and 'exit' to quit the program.") flashcards = "next" while flashcards != "quit": # loop through flashcard entries until input = 'quit' if flashcards == "show": # show answer print("Answer: " + answers[ran]) print() flashcards = str(input()) elif flashcards == "next": # display random flashcard question ran = random.randint(0, q_number-1) print("Question: " + questions[ran]) flashcards = str(input()) else: # if non-answer print("\nPlease enter one of the following:") print("'show' = reveal the answer\n'next' = move on to the next card\n'quit' = exit the program\n") flashcards = str(input()) print("Exiting program...") # if input = 'quit' elif test == "no": # quit program print("\nExiting program...")
true
fb549ca03420030ffb47f11f4abdd0e026bdfda4
zhanyiduo/leetcode_practise
/680. Valid Palindrome II.py
716
4.125
4
''' Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum length of the string is 50000. ''' class Solution: def validPalindrome(self, s: str) -> bool: l=0 u = len(s)-1 while l<u: if s[l] == s[u]: l+=1 u-=1 else: temp1 = s[l+1:u+1] #skip l temp2 = s[l:u] #skip u return temp1==temp1[::-1] or temp2==temp2[::-1] return True
true
941aaedf920df638000c8fce96c1b658c46fa274
zhanyiduo/leetcode_practise
/951. Flip Equivalent Binary Trees.py
1,526
4.21875
4
''' For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1 and root2. Example 1: Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] Output: true Explanation: We flipped at nodes with values 1, 3, and 5. Flipped Trees Diagram Note: Each tree will have at most 100 nodes. Each value in each tree will be a unique integer in the range [0, 99]. ''' class Solution: def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: # checking root node should be the same if (not root1) and (not root2): return True elif (not root1) or (not root2): return False elif (root1.val != root2.val): return False if self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right): # if they are equivalent return True elif self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left): # if they are flip equi return True else: return False
true
2f3cbceb323336e281daf89e0ed399718640f1b3
rogerio5ouza/python-beginner
/semana-1/casting.py
1,389
4.625
5
''' Python Casting (Fusão) Especifica um tipo de variável Pode haver momentos em que você queira especificar um tipo para uma variável. Isso pode ser feito com Casting. Python é uma linguagem orientada a objetos e, como tal, usa classes para definir tipos de dados, incluindo seus tipos primitivos. Casting em Python é, portanto, feita usando funções de construtor: int() - constrói um número inteiro a partir de um literal int, um literal float (arredondando para baixo para o número int anterior) ou um literal string (desde que a string represente um número int). float() - constrói um número float a partir de um literal int, um float literal ou um string literal (desde que a string represente um número inteiro ou flutuante). str() - constrói uma string a partir de um ampla variedade de tipos de dados, incluindo strings, literais inteiros e literais float. ''' # Exemplos # Integers: x = int(1) # x será 1 y = int(2.8) # y será 2 z = int('3') # z será 3 print (x) print (y) print (type(z)) # Floats: x = float(1) # x será 1.0 y = float(2.8) # y será 2.8 z = float('3') # z será 3.0 w = float('4.2') # w será 4.2 print (x) print (y) print (z) print (type(w)) # Strings x = str('s1') # x será 's1' y = str(2) # y será '2' z = str(3.0) # z será '3.0' print (x) print (y) print (type(z))
false
d87a0acd3ad20b6712c675c7ec4bdbdbc68e1723
rogerio5ouza/python-beginner
/semana-4/math.py
738
4.1875
4
''' Python Math Python possui um conjunto de funções matemáticas nativa, incluindo um extenso módulo matemático, que permite realizar tarefas matemáticas com números. ''' # Funções matemáticas nativa # As funções min() e max() podem ser usadas para encontrar o valor mais baixo ou mais alto em um iterável: menor_valor = min(2, 4, 6, 8, 10) maior_valor = max(2, 4, 6, 8, 10) print(menor_valor) print(maior_valor) # A função abs() retorna o valor absoluto (positivo) do número especificado: numero_aleatorio = abs(-8.25) print(numero_aleatorio) # A função pow(x, y) retorna o valor de x elevado à potência de y (xy) # Exemplo # Retorna o valor de 4 à potência de 3 (igual a 5 * 5 *): x = pow(5, 3) print(x)
false
01d2818581d3805e67d9470ddd0144087e4449fc
rogerio5ouza/python-beginner
/semana-2/if_else.py
2,343
4.15625
4
''' If...Else O Python suporta as condições usuais lógicas da matemática: * É iguala: a == b * Diferente: a! = B * Menor que: a < b * Menor ou igual a: a <= b * Maior que: a > b * Maior que ou Igual a: a >= b Essas condições podem ser usadas de várias formas, mais comumente em 'instruções if' e loops. ''' # Exemplo: a = 14 b = 30 if b > a: print('b é maior que a.') ''' Elif A palavra-chave Elif é uma forma do Python dizer 'se a condição anterior não for verdadeira, tente esta condição'. ''' # Exemplo: a = 7 b = 7 if a > b: print('b é maior do que a.') elif a == b: print('a e b são iguais.') ''' Else O Else captura qualquer coisa que não seja capturada pelas condições anteriores. ''' # Exemplo: a = 20 b = 10 if b > a: print('b é maior que a.') elif a == b: print('a e b são iguais.') else: print('a é maior que b.') # Se tivermos apenas uma instrução para executar, podemos colocá-la na mesma linha que o If: a = 200 b = 100 # if a > b: print('a é maior que b.') # Se tivermos apenas uma instrução para executar, uma para If e outra para Else, podemos também colocá-las na mesma linha: a = 500 b = 1000 print('A') if a > b else print('B') # Podemos ainda colocar várias instruções Else na mesma linha: a = 1000 b = 1000 print('A') if a > b else print('=') if a == b else print('B') ''' AND A palavra-chave AND é um operador lógico usado para comparar instruções condicionais, quando AMBAS condições forem verdadeiras. ''' # Exemplo: a = 100 b = 55 c = 300 if a > b and c > a: print('Ambas condições são verdadeiras.') ''' OR A palvra-chave OR é um operador lógico usado para comparar instruções condicionais, qundo UMA das condições for verdadeiras. ''' # Exemplo: a = 100 b = 55 c = 300 if a > b or c > a: print('Uma das condições é verdadeira.') ''' IF ANINHADO Podemos ter instruções IF dentro de instruções IF, isso é chamado de intruções IF aninhadas. ''' # Exemplo: x = 57 if x > 10: print('Maior que 10,') if x > 20: print('e também maior que 20!') else: print('mas não maior que 60.') ''' A declaração PASS Se por algum motivo tivermos uma instrução IF sem conteúdo, inserimos uma instrução PASS para evitar erros. ''' # Exemplo: a = 30 b = 100 if b > a: pass
false
52601dc4532aed67104e6a847bc82c923dbe24c1
rogerio5ouza/python-beginner
/semana-1/numbers.py
2,010
4.40625
4
''' Python Numbers (Números em Ptyhon) Existem três tipos numéricos em Ptyhon: ''' # int # float # complex ''' Variáveis de tipos numéricos são criadas quando você atribui um valor para elas: ''' x = 1 # int y = 2.8 # float z = 1j # complex ''' Para verificar o tipo de qualquer objeto em Python, use a função type():''' print (type(x)) print (type(y)) print (type(z)) ''' Int Int, ou inteiro, é um número inteiro, positivo ou negativo, sem decimais, de comprimento ilimitado. ''' # Integers: x = 1 y = 35656222554887711 z = -325522 print (type(x)) print (type(y)) print (type(z)) ''' Float Float ou "número de ponto flutuante" é um número, positivo ou negativo, contendo uma ou mais casas decimais. ''' # Floats: x = 1.10 y = 1.0 z = 35.59 print (type(x)) print (type(y)) print (type(z)) ''' Float também pode ser um número científico com um "e" para indicar a potência 10. ''' # Floats: x = 35e3 y = 12E4 Z = -87.7e100 print (type(x)) print (type(y)) print (type(z)) ''' Complex Números complexos são escritos com um "j" como a parte imaginária: ''' # Complex x = 3+5j y = 5j z = -5j print (type(x)) print (type(y)) print (type(z)) ''' Type Conversion (Conversão de Tipo) Voçê pode converter de um tipo para outro com os métodos int(), float() e complex(): ''' # Converter de um tipo para outro: x = 1 # int y = 2.8 # float z = 1j # complex # converte de int para float: a = float (x) # converte de float para int: b = int (y) # converte de int para complex: c = complex (x) print (a) print (b) print (c) print (type(a)) print (type(b)) print (type(c)) ''' Random Number (Número Randômico) O Python não possui uma função random() para criar um núemro aleatório, mas o Python possui um módulo interno chamado ramdom que pode ser usado para criar números aleatórios: ''' # Importe o módulo aleatório e exiba um número aleatório entre 1 e 9: import random print (random.randrange(1, 10))
false
ce97c5b2c82651188e0e0aafd5c7048359125a54
rotsendroid/PySQLiteController
/db_controller/ValueNumbersException.py
812
4.40625
4
class ValueNumbersException(Exception): """ An exception class raised when the number of values the user tries to insert are different than the number of columns, works with Manipulation class Example insert_values(4, 1, 'Nick', 'A St') exception raised, because 1st arg->number of columns: 4 total number of values: 3 """ def __init__(self, numberColumns, numberValues): self.numberColumns = numberColumns self.numberValues = numberValues def __str__(self): return "\nValueNumberException\nNumber of values tried to insert is " \ "different than the number of columns\nNumber of values given: {}\n" \ "Number of columns: {}".format(self.numberValues, self.numberColumns)
true
442c0823c84c877c8ed3def63aac20e1ff5ba74d
chandan1602/Python_basics
/database.py
1,277
4.1875
4
#step 1 import sqlite3 #step 2 #connection_var=sqlite3.connect("database/database.sqlite/database.db") con=sqlite3.connect("chandan") if con: print("database craeted") else: print("error") ''' DML ---------- insert, delete, update | commit() sql queries ------------------- execute() method is used. syntax ----------- connect_var.execute("query") connect_var.commit() ''' #con.execute("create table stu(id int,name text)"); ''' con.execute("insert into stu values(1,'abc')") con.commit() print("Data inserted") ''' id=int(input("Enetr Id: ")) name=input("Enter Name:") ''' format specifier ------------------ %d int %s string %f float connection_var.execute("insert into tablename values(format_specifier)"%(var1,var_n)) ''' con.execute("insert into stu values(%d,'%s')"%(id,name)) con.commit() print("Data inserted") ''' cursor_object=connection_var.cursor() cursor_object.execute("sql query") ''' cur=con.cursor() ''' cur.execute("select * from stu") print(cur.fetchone()) cur.execute("select * from stu") print(cur.fetchall()) ''' cur.execute("select * from stu") ''' for x in cur: print(x) ''' print("id name") print("------------------") for x in cur: print(x[0]," ",x[1])
false
35232a8f0ab994f37702f7968865cf1aa13919d5
real-ashd/AutomateBoringStuffWithPython
/LoopsAndControlStatements/whileWithBreak.py
323
4.1875
4
#While Statement with break name='' while True: print("Please type your name") name=input() if name == "your name": break print("Thank you") # Output: # Please type your name # asutos # Please type your name # Ashutosh # Please type your name # Ashutosh Deshmukh # Please type your name # your name # Thank you
true
23c52d51c5367ca1c77f6dbab1a697d40f3cc3d7
real-ashd/AutomateBoringStuffWithPython
/List/SimilaritiesBetweenListAndString.py
1,044
4.15625
4
#List value is mutable datatype, it can have value added removed or changed #However String is immutable data type, its value can't be changed """ >>> list["Hello"] list['Hello'] >>> list("Hello") ['H', 'e', 'l', 'l', 'o'] >>> name='Sophie' >>> name[0] 'S' >>> name[1:3] 'op' >>> name[-2] 'i' >>> 'So' in name True >>> 'Abs' in name False >>> for letter in name: print(letter) S o p h i e >>> name='Sophie the cat' >>> name[7] 't' >>> name[7]='X' Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> name[7]='X' TypeError: 'str' object does not support item assignment >>> """ #To Modify a string create a new variable and use splicing """ >>> name="Sophie a cat" >>> newName=name[0:7]+"the"+name[8:] >>> newName 'Sophie the cat' >>> """ #List uses reference while strings do not """ >>> s=42 >>> c=s >>> s=100 >>> s 100 >>> c 42 >>> >>> >>> >>> s=[1,2,3,4,5,6] >>> c=s >>> c[4]="Hello" >>> c [1, 2, 3, 4, 'Hello', 6] >>> s [1, 2, 3, 4, 'Hello', 6] >>> """
true
c7d42938e565ec1f246c2112c358e58db7607d80
real-ashd/AutomateBoringStuffWithPython
/FileSystem/CopyingAndMovingFileAndFolders.py
1,233
4.34375
4
#Copying and Moving Files and Folders #Using shutil module for copy, paste, move, rename files #F:\Python Project\FileSystem\hello.txt import shutil #Now we copy the file hello.txt to a folder Folder1 using copy() function, it takes 2 args print(shutil.copy("C:\\Users\\Abc\\Documents\\hello.txt","C:\\Users\\Abc\\Documents\\Folder1")) #This prints out the path where the file is copied #We can also copy and rename the file at the same time by specifying the filename at the end print(shutil.copy("C:\\Users\\Abc\\Documents\\hello.txt","C:\\Users\\Abc\\Documents\\Folder1\\helloworld.txt")) #To copy an entire folder and all files and folder inside it use copytree() function, it takes 2 args print(shutil.copytree("C:\\Users\\Abc\\Documents\\Folder1","C:\\Users\\Abc\\Documents\\Folder1_backup")) #To move a file from one place to another use move function #Now we move the file hello.txt to a folder Folder1\Folder2 print(shutil.move("C:\\Users\\Abc\\Documents\\hello.txt","C:\\Users\\Abc\\Documents\\Folder1\\Folder2")) #To rename a file we have to use move function print(shutil.move("C:\\Users\\Abc\\Documents\\Folder1\\Folder2\\hello.txt","C:\\Users\\Abc\\Documents\\Folder1\\Folder2\\helloworld.txt"))
true
c31b240047a75483ba9f1c1d737793905caf7adf
real-ashd/AutomateBoringStuffWithPython
/RegularExpressions/RegexDotStar_Carat_Dollar.py
2,767
4.3125
4
#Check the second argument of re.compile() function re.DOTALL "prints all the matched pattern including new lines" #re.compile(r'pattern',re.I) or re.compile(r'pattern',re.IGNORECASE) "This ignores the case sensitive nature of the pattern" import re #'^' can be used to find if the string passed starts with the pattern beginsWithHelloRegex=re.compile(r'^Hello') print(beginsWithHelloRegex.search("Hello There!")) print(beginsWithHelloRegex.search("He said 'Hello!'")) #endWith using $ beginsWithHelloRegex=re.compile(r'There!$') print(beginsWithHelloRegex.search("Hello there!")) print(beginsWithHelloRegex.search("Hello There!")) #Using both '^' and '$' to indicate startswith and endswith #Both means the entire string must match allDigitsRegex=re.compile(r'^\d+$') print(allDigitsRegex.search("1245746757657")) print(allDigitsRegex.search("12457467 57657")) #Using Dot character. '.' it means any character except a new line atRegex=re.compile(r'.at') print(atRegex.findall("The cata in the hata sate on the flato matr.h\nat ")) atRegex=re.compile(r'at.') print(atRegex.findall("The cata in the hata sate on the flato matr.hat\n")) atRegex=re.compile(r'.at.') print(atRegex.findall("The cata in the hata sate on the flato matr.\nhat\n")) atRegex=re.compile(r'.{1,2}at') #It adds spaces print(atRegex.findall("The cat in the hat sat on the flat mat.")) print("------------------------------------------------------------------------") #Using Dot-Star pattern to avoid spaces '.' means any character and '*' means 1 or more #'(.*)' uses greedy mode to use non greedy mode use '(.*?)' string="First Name : Ash Last Name : Deshmukh" nameRegex=re.compile(r'First Name : (.*) Last Name : (.*)') #Greedy expresion print(nameRegex.findall(string)) serve = '<To serve humans> for dinner.>' nonGreedyRegex=re.compile(r'<(.*?)>') #NonGreedy Version print(nonGreedyRegex.findall(serve)) greedyRegex=re.compile(r'<(.*)>') #Greedy version print(greedyRegex.findall(serve)) prime = "Serve the public.\nProtect the innocent.\nUphold the Laws." print(prime) dotStar=re.compile(r'.*') #Greedy version print(dotStar.search(prime)) dotStar=re.compile(r'.*',re.DOTALL) print(dotStar.search(prime)) vowelRegex=re.compile(r'[aeiou]') #Returns only lowercase vowels print(vowelRegex.findall("Al, why does your programming book talk about RoboCop so much.")) vowelRegex=re.compile(r'[aeiou]',re.IGNORECASE) #Ignores the case senstiveness print(vowelRegex.findall("Al, why does your programming book talk about RoboCop so much.")) vowelRegex=re.compile(r'[aeiou]',re.I) #Ignores the case senstiveness print(vowelRegex.findall("Al, why does your programming book talk about RoboCop so much."))
true
e119cc7aecfd07a0274ac37aa90e7485abfeb92a
Deys2000/Basic-Python-Tutorial
/25-28 TurtleIntermediateGraphics/Star.py
471
4.40625
4
print('''python program #27 Hashir - June 1 2018 This program will use the turtle module to draw a star depending on how you play with the angle, the star changes its sharpness ''') import turtle t = turtle.Pen() def draw_star(size,points): for x in range(0,points*2): if(x%2 == 0): t.left(360*2/points) t.forward(size) else: t.right(360/points) t.forward(size) draw_star(70,10)
true
4d39cdd3fe9d684c68003a38aa048f06e108d93b
Deys2000/Basic-Python-Tutorial
/11-14 loops/loop_multiplying.py
354
4.125
4
print('''python program #14 Hashir - May 30 2018 This program will get your weight on the moon as your mass increases by a kilo each year ''') gravity_earth = 9.81 gravity_moon = gravity_earth*.165 initial_mass = 30 mass = None for year in range(0,15): mass = initial_mass + year print("Year %s: %skg" %(year+1,mass*gravity_moon))
true
341eab45db4c167cdb6abe33b887309f09821b1e
sbarbiero/project-euler
/problem-8/maxprod.py
632
4.25
4
def find_max_prod(number, n): """ Find the maximum product of n adjacent digits in a 1000 digit number Parameters: number - 1000 digit number to use n - the nth number of adjacent digits Returns: max_prod - the maximum product of all nth adjecent digits """ digits =[int(x) for x in str(number)] #break into digits max_prod = 0 for x in range(len(digits)): if x+n < len(digits): prod = np.prod(digits[x:x+n]) else: prod = np.prod(digits[-n]) if prod > max_prod: max_prod = prod return max_prod
true
c36de1347417263a20295ad93fecb58f074096a3
brandanmcdevitt/python.archive
/Udemy/Modern_Python3_Bootcamp/file_IO.py
1,786
4.28125
4
# Exercise # 1. write a function that takes in a file name and a new file name and copies # the contents of the first file to the second file. def copy(file_1, file_2): with open(file_1) as file: text_to_copy = file.read() with open(file_2, 'w') as file_copy: file_copy.write(text_to_copy) copy('Udemy/Modern_Python3_Bootcamp/story.txt', 'Udemy/Modern_Python3_Bootcamp/story_copy.txt') # 2. write a function that takes in a file name and a new file name and writes # the contents of the first file to the second file in reverse. def copy_and_reverse(file_1, file_2): with open(file_1) as file: text_to_reverse = file.read() with open(file_2, 'w') as file_copy: file_copy.write(text_to_reverse[::-1]) copy_and_reverse('Udemy/Modern_Python3_Bootcamp/story.txt', 'Udemy/Modern_Python3_Bootcamp/story_reversed.txt') # 3. write a function that takes in a file name and returns a dictionary with # the number of lines, words and characters in the file. def statistics(file_name): with open(file_name) as file: text = file.readlines() return {"lines" : len(text), "words": sum(len(t.split()) for t in text), "characters": sum(len(char) for char in text)} statistics('Udemy/Modern_Python3_Bootcamp/story.txt') # 4. write a function that takes in a file name, a word and a replacement word. # Read the file and replace all instances of word with replacement word. def find_and_replace(file_name, word, replacement): with open(file_name, 'r+') as file: text = file.read() text_updated = text.replace(word, replacement) file.seek(0) file.write(text_updated) find_and_replace('Udemy/Modern_Python3_Bootcamp/story.txt', 'Alice', 'Brandan')
true
b02bf13e339a8a1548acc6ffbaa8520d0cd911d2
brandanmcdevitt/python.archive
/Udemy/Modern_Python3_Bootcamp/lambdas.py
1,150
4.375
4
# Exercises # 1. Create a lambda expression that multiplies two numbers and set it equal to a variable. multiple = lambda n1, n2: n1*n2 print(multiple(2,7)) # 2. Write a function that takes a function as a parameter. Call that function with and pass it a lambda. def lambda_function_test(function, value): return function(value) lambda_function_test(lambda n: n**2, 8) # 3. Use the map() function along with a lambda to add each element in two lists. print(list(map(lambda x, y: x+y, [1,4,7,9], [8,4,1,6]))) # 4. Write a function that accepts a single list of numbers as a parameter. It should return a list where each item has been decremented by 1. def decrement(values): return list(map(lambda n: n - 1, values)) decrement([4,1,4,7,7,9]) # 5 Use the filter() function along with a lambda to test if each element in a list is odd. print(list(filter(lambda x: x % 2 != 0, [1,8,9,12,4,5,7,11]))) # 6. Write a function that accepts a list of numbers and returns a copy of the list with all negative values removed def remove_negatives(values): print(list(filter(lambda n: n >= 0, values))) remove_negatives([-13,9,1,-3,-7,9,2,5,-5])
true
96a0ab78e76134ac365d52e1ca4a6f843c97dd11
brandanmcdevitt/python.archive
/Udemy/Modern_Python3_Bootcamp/args_kwargs.py
1,381
4.25
4
# Exercises # 1. Define a function that accepts any number of arguments. It should return True if any of the arguments are "purple" def contains_purple(*args): return "purple" in args contains_purple(1, 2, 4, 7, "hello", 9.1, "white") # False contains_purple("red", 9, 1.3, False, "purple") # True # 2. Write a function which accepts a word and any number of additional keyword arguments. # if a prefix is provided, return the prefix followed by the word. If a suffix is provides, return the word followed by the suffix def combine_words(word, **kwargs): if "prefix" in kwargs: return kwargs["prefix"] + word elif "suffix" in kwargs: return word + kwargs["suffix"] return word combine_words("child") # child combine_words("child", prefix="man") # manchild combine_words("child", suffix="ish") # childish # 3. Create a function that counts how many times the number 7 appears in an unpacked list passed through as an argument nums = [90,1,35,67,89,20,3,1,2,3,4,5,6,9,34,46,57,68,79,12,23,34,55,1,90,54, 34,76,8,23,34,45,56,67,78,12,23,34,45,56,67,768,23,4,5,6,7,8,9,12,34, 14,15,16,17,11,7,11,8,4,6,2,5,8,7,10,12,13,14,15,7,8,7,7,345,23,34,45, 56,67,1,7,3,6,7,2,3,4,5,6,7,8,9,8,7,6,5,4,2,1,2,3,4,5,6,7,8,9,0,9,8,7, 8,7,6,5,4,3,2,1,7] def count_sevens(*args): return args.count(7) count_sevens(*nums) # 14
true
79caf474ff984007989f5b1a5342bfce630c238a
eecs110/winter2020
/course-files/lectures/lecture_14/00_error_handling.py
379
4.125
4
# This loop keeps going until the user has entered a valid age: while True: age = input('enter your age: ') year = input('enter a year in the future: ') print('Your age in 2050:', int(age) + int(year) - 2019) up_next = input('Do you want to try again (Y/n)?' ) if up_next.upper() == 'N': # Exit the loop... print('exiting...\n') break
true
f64c7069d7e5b8120c48aec2d6367d5f7b5cb648
P-Schlumbom/pastel-colours
/utils/quantisation/mmcq.py
1,746
4.28125
4
# pretty straightforward explanation here: https://en.wikipedia.org/wiki/Median_cut # otherwise also look here: https://muthu.co/reducing-the-number-of-colors-of-an-image-using-median-cut-algorithm/ # here: http://leptonica.org/papers/mediancut.pdf # or here: https://github.com/kanghyojun/mmcq.py/blob/master/mmcq/quantize.py import numpy as np def mmcq_loop(pixels, q): """ The main recursive loop of the MMCQ algorithm. Returns list of quantised pixels from each bin or itself. :param pixels: numpy array of shape (N, 3), of N RGB pixels :param q: int, quantisation level. Recursion stops when this reaches zero. :return: a list of numpy arrays of shape (1, 3), where each array represents the mean pixel value of a final leaf bin. """ variances = np.std(pixels, axis=0) sort_col = np.argmax(variances) pixels = pixels[pixels[:, sort_col].argsort()] halfway_index = pixels.shape[0] // 2 if q > 0 and halfway_index > 0: return mmcq_loop(pixels[:halfway_index, :], q - 1) + mmcq_loop(pixels[halfway_index:, :], q - 1) return [np.mean(pixels, axis=0)] def mmcq(im, n_bins=2): """ Given an image, quantise its pixel values into n_bins colours :param im: numpy array of shape (W, H, 3), the input image :param n_bins: the number of colours to quantise the pixels into. Note that this value should be in the form 2^x where x is a positive integer. :return: a list of n_bins numpy arrays, where each array is of shape (1, 3) and represents the RGB values of one particular colour. """ q = int(np.log2(n_bins)) pixels = np.reshape(im, (im.shape[0]*im.shape[1], im.shape[2])) quantised_pixels = mmcq_loop(pixels, q) return quantised_pixels
true
6ce655418e1a7da60f78ddfeea144677ef8cb167
dmarquesdev/ine5429-seguranca-em-computacao
/atividade1/vigenere.py
797
4.15625
4
#!/usr/bin/python2 from itertools import cycle KEY = 'INFOSEC' PLAINTEXT = 'DIEGO' def cipher(text, key): result = '' # Zip gets two lists and iterates through it combining all elements with # the same index on the other list. # # Cycle iterates through a list going back to the start # when the end is reached, just like is needed on Vigenere Algorithm. for comb in zip(text, cycle(key)): if ord(comb[0]) >= ord('A') and ord(comb[0]) <= ord('Z'): result += chr(ord('A') + ((ord(comb[0]) + ord(comb[1])) % 26)) return result def main(): print 'Vigenere Cipher' print 'Plain Text: %s' % PLAINTEXT print 'Key: %s' % KEY print 'Ciphered Text: %s' % cipher(PLAINTEXT.upper(), KEY.upper()) if __name__ == '__main__': main()
true
177de648d3fb1bbb4abd9fd681ca9586585cf031
velinovasen/python-adv-oop
/SoftuniAdvanced/ADVANCED/exam_preparation/advent_calendar.py
1,768
4.4375
4
numbers = [3, 2, 1, 4, 6, 5] def fix_calendar(numbers): for x in range(len(numbers)): for y in range(x + 1, len(numbers)): if numbers[x] > numbers[y]: numbers[x], numbers[y] = numbers[y], numbers[x] return numbers print(fix_calendar(numbers)) '''Advent Calendar While Santa is delivering all the presents to the kids, the parents are buing and hanging some advent calenedars for the kids to enjoy. While buying the advent calendars, most of the families saw that the numbers in the calendars are kind of messed up, so it is your job to fix them. Create a function called fix_calendar. The function should receive some shuffeled numbers (the days on the calender) and it should return them correctrly ordered (ascening). The numbers passed to your function will always be positive. You are not allowed to: ⦁ Use any of the built-in functions to sort the numbers. ⦁ Create new lists to help you ⦁ Delete items from the given list Note: Submit only your function in the judge system. Input ⦁ There will be no input ⦁ You can test your code using your own examples or those given below Output ⦁ Your function should return a list of the sorted numbers in ascending order Examples Test Code Output Comments numbers = [3, 2, 1] fixed = fix_calendar(numbers) print(fixed) [1, 2, 3] We start by comparing 3 with 2 -> 3 > 2, so we swap them: [2, 3, 1] We compare 3 with 1 -> 3 > 1, so we swap them: [2, 1, 3] We checked all the numbers, but there were swaps, so we loop again We copare 2 with 1 -> 2 > 1, so we swap them: [1, 2, 3] We compare 2 with 3 -> 2 < 3, no swap We checked all again, there was a swap, so we loop again This time we loop throug all of them with no swaps, so we have sorted the numbers '''
true
97aebe5668603f105e175aa2953858a9529fe54c
velinovasen/python-adv-oop
/SoftuniAdvanced/ADVANCED/tuples_and_sets/battle_of_names.py
1,427
4.21875
4
odd_nums = set() even_nums = set() counter = 0 for _ in range(int(input())): counter += 1 name = input() name_sum = 0 for x in name: name_sum += ord(x) name_sum //= counter if name_sum % 2 != 0: odd_nums.add(name_sum) else: even_nums.add(name_sum) if sum(odd_nums) == sum(even_nums): new_set = list(odd_nums.union(even_nums)) elif sum(odd_nums) > sum(even_nums): new_set = list(odd_nums.difference(even_nums)) elif sum(odd_nums) < sum(even_nums): new_set = list(odd_nums.symmetric_difference(even_nums)) print(", ".join([str(x) for x in new_set])) '''Battle of Names You will receive a number N. On the next N lines, you will be receiving names. You must sum the ascii values of each letter in the name and integer devise the value (current index). Save the devised number to a set of either odd or even numbers, depending if it's an odd or even number. After that, sum the values of the odd and even numbers. If the summed numbers are equal, print the union values, separated by ", ". If the odd sum is bigger than the even, print the different values, separated by ", ". If the even sum is bigger than the odd, print the symmetric different values, separated by ", ". NOTE: On every operation, the starting set should be the odd set Examples Input Output 4 Pesho Stefan Stamat Gosho 304, 128, 206, 511 6 Preslav Gosho Ivan Stamat Pesho Stefan 733, 101 '''
true
e54b38d219197c36a669e3d4f22484e2ac456f57
hillan1152/Algorithms
/recipe_batches/recipe_batches.py
1,956
4.15625
4
#!/usr/bin/python import math # UNDERSTAND # Take in a DICTIONARY of a RECIPE and AVAILABLE INGREDIENTS # Includes key - values: name - amount # RECIPE DICTIONARY: # amount = amt of each ingredient needed for the recipe # INGREDIENTS DICTIONARY: # amount = amt of the ingredient available to you # GOAL/NEED: Output max number of WHOLE BATCHES # 2nd Dictionary represents ingredients dictionary. def recipe_batches(recipe, ingredients): # PLAN # keep track of ingredient amt # ingredient_amt = 0 # keep track of recipe amt # recipe_amt = 0 # keep track of number of batches available batches = 0 # batch = ingredients // recipe # If the length of the recipe > length of ingredients return 0 # if len(recipe) > len(ingredients): # return 0 # else: # for key in ingredients: # print(key, '->', ingredients[key]) # for key in recipe: # print(key, '->', recipe[key]) # If values of ingredients (in the entire dictionary) are divisible by # values of recipe continue for key, value in recipe.items(): print("key", key) print("value", value) if key not in ingredients: return 0 if batches > ingredients[key] // value: print("ingredients--key -> ", batches) batches = ingredients[key] // value return batches recipe = {'milk': 100, 'butter': 50, 'flour': 5} ingredients = {'milk': 132, 'butter': 48, 'flour': 51} recipe_batches(recipe, ingredients) if __name__ == '__main__': # Change the entries of these dictionaries to test # your implementation with different inputs recipe = {'milk': 100, 'butter': 50, 'flour': 5} ingredients = {'milk': 132, 'butter': 48, 'flour': 51} print("{batches} batches can be made from the available ingredients: {ingredients}.".format( batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
true
5d7228226a2fb5eab676e7afb1d20ed84ea37b09
eyacdfn/Python-Generator
/Generator.py
766
4.15625
4
print "Generator implement is begin" def fib(max): "Python Gererator" a,b = 0,1 while a < max: yield a #print 'next?' a,b = b,a+b f= fib(1000) print f.next() print f.next() print f.next() print f.next() print "Iterator is in the front" for value in f: print value print "Generator implement is begin" def Fibs(): a,b = 0,1 while True: a,b = b, a+b yield a fibs = Fibs() print "Iterator implement is begin" for value in fibs: print value class Fibs: def __init__(self): self.a=0 self.b=1 def next(self): self.a,self.b=self.b,self.a+self.b return self.a def __iter__(self): return self fibs = Fibs() for f in fibs: print f
false
b5ad1992af7b20282e245082b73e0bf8d5494b7a
florin-postelnicu/Hello-World
/conversiontemp.py
608
4.1875
4
''' conversion from Celsius to Fahrenheit C*9/5 +32 = F conversion from Fahrenheit to Celsius (F - 32)* 5/9 = C ''' def conversion(degree, temp): if degree == 'f': C = (temp -32)*5/9 print(temp, "F converted in C is :", round(C)) elif degree =='c': F = temp*9/5 + 32 print(temp, "C converted in F is :",round(F)) else : print("There is no such type of degree: ", degree) print('Input the type ') deg = input("Enter c for Celsius, or f for Fahrenheit: ") temperature = int(input("Enter the value for temperature: ")) conversion (deg, temperature)
false
93caf7d0aa1db7d3257457c745e051633783fdfa
HodardHazwinayo/PurePPython
/index2.py
634
4.21875
4
# Control Flow # There are three control flow statements in Python: IF, FOR, and WHILE # The IF statement: number = 23 guess = int(input('Enter an integer : ')) if guess == number: # New block starts here print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') # New block ends here else if guess < number: # Another block print('No, it is a little higher than that') # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guessed > number to reach here print('Done') # This last statement is always executed, # after the if statement is executed.
true
a9e032524eded393921318b1c247d8c8c92ea946
manoelsslima/datasciencedegree
/tarefas/tarefa02/e02q02.py
219
4.21875
4
''' Faça um programa que peça um número e mostre se ele é positivo ou negativo. ''' numero = int(input('Informe um número: ')) if(numero < 0): print('O número é negativo') else: print('O número é positivo')
false
a4cadb46aaa9304168c671497ce34605c3854f5c
manoelsslima/datasciencedegree
/tarefas/tarefa01/e01q03.py
285
4.1875
4
''' Faça um programa que peça um número para o usuário (string), converta-o para float e depois imprima-o na tela. Você consegue fazer a mesma coisa, porém convertendo para int? ''' numero_str = input('Informe um número: ') numero_float = float(numero_str) print(numero_float)
false
14b67195e285e767ed6e249d6118ab1f0097cd2a
ZoranNik91/Anagrams
/anagrams2.py
1,596
4.28125
4
import sys def find_in_dict(argv_file, argv_word): anagrams = [] if len(argv_word) < 2: return print("INPUT ERROR: The entered word must be greater than one character") word_dict = read_word_list(argv_file) word_sorted = sortWord(argv_word) chars_array = list(word_sorted[0]) # Convert string to Array i.e: "abc" --> ["a","b","c"] all_are_equal = all(ch == chars_array[0] for ch in chars_array ) if all_are_equal: return print("INPUT ERROR: Input characters must be different") for word in word_dict.keys(): if (word_dict[word] == word_sorted[1] and word != word_sorted[0]): anagrams.append(word) print(len(anagrams)) def sortWord(input_word): """Lowercase and sort the user input word.""" word = input_word.lower().strip() return word, "".join(sorted(word)) # "".join Array to empty String def read_word_list(filename): """Open file and create a dictionary of {"word":"word_sorted"}.""" with open(filename, "r") as word_file: word_list = {} for text in word_file: word_sorted = sortWord(text) word_list.update({word_sorted[0]: word_sorted[1]}) # inserts property : value into word_list dictionary return word_list def main(): if len(sys.argv) != 3: return print("INPUT ERROR: Use like: anagram.py fileName.txt word") find_in_dict(sys.argv[1], sys.argv[2]) if __name__ == "__main__": # the test1.py is __main__ only when run directly from terminal. exit(main())
true
13654942a019ffb86be4cba390764a944d0e65c5
derevianko/geekpy
/les_1/6.py
376
4.3125
4
# 6. Write a script to check whether a specified value is contained in a group of values. # Test Data : # 3 -> [1, 5, 8, 3] : True # -1 -> (1, 5, 8, 3) : False x_str = input ('Enter 5 numbers aross ","') x_tuple = x_str.split(',') x_tuple = tuple(x_tuple) print (x_tuple) x_num = input ('Search number:') if x_num in x_tuple: print('True') else: print('False')
true
80e312213020d00289d3e3157549e0ee87ada9f3
UCD-pbio-rclub/Pithon_MinYao.J
/hw4-3_interactive_palindrome_ignore_capital.py
535
4.25
4
def is_palindrome(): while True: print('Welcome to is_palindrome.') user_input = input('Please enter a potential palindome: ') user_input = user_input.lower() if(user_input==user_input[::-1]): print(user_input.capitalize(), "is a palindrome") else: print(user_input.capitalize(), "isn't a palindrome") user_input = input('Do another search? [y/n]: ').lower() user_input = user_input or 'y' if user_input == 'n': break
false
419fb8d4c272371937004055c81259d6e145657f
DeependraChechani/file
/task2.py
201
4.28125
4
file = input("Input the file name(like abc.py): ") length = len(file) if file[length-2:length]=="py": print("The extension of file is : python") else: print("file has another extension")
true
a0b79a935c439aa7b0d071c4e522ca69fe78f42d
luminousbeam/Remove-Repeat-Characters
/remove_repeat.py
354
4.15625
4
```Remove duplicate characters in a given string keeping only the first occurrences. For example, if the input is ‘tree traversal’ the output will be "tre avsl".``` def get_unique(str): arr = list(str) print(arr) unique = [] for i in arr: if i not in unique: unique.append(i) print(''.join(unique)) get_unique('tree traversal')
true
0332ba82b9c9341a4a8ddfb221498a07d16321a5
sarahtabra/untitled1
/task 5.py
1,613
4.28125
4
import math user_choice = int(input("This is a menu-driven program, press 1 for quick pythagoras, press 2 for tip calculator and press 3 for temperature converter.")) #allows the user to choose 1,2 or 3, depending on which program they want to access. if user_choice == 1: print("quick pythagoras") a = int(input("enter a value for a")) #allows the user to enter a value for a to eventually calculate what c is. b = int(input("enter a value for b")) #allows the user to enter a value for b to eventually calculate what c is. c = math.sqrt(a*a + b*b) #calculates the square root for values a & b. print ("the value for c is ", c) if user_choice == 2: print("tip calculator") total = int(input("what is the value of the total?")) #asks the user to input a value for the total. tip = int(input("what tip percent do you want to give?")) #asks the user to input a percentage for tip. tip_total = total*(tip/100) #converts the percentage of the tip to a cost. print("the amount you're tipping is ", tip_total) if user_choice == 3: print("temperature converter") celsius = int(input("enter a temperature for celsius")) #asks the user to input a temperature in celsius. fahrenheit = int(input("enter a temperature for fahrenheit")) #asks the user to input a temperature in fahrenheit. new_fahrenheit = (celsius*9/5) + 32 #formula to convert celsius to fahrenheit. new_celsius = (fahrenheit-32) *5/9 #formula to convert fahrenheit to celsius. print("the temperature in celsius is ", new_celsius) print("the temperature in fahrenheit is ", new_fahrenheit)
true
c597e54f7f2438292b2063a3462881ee38861737
zelson71/python-challenge
/homework/extras/PyBoss/remove.py
492
4.28125
4
# put your code below def remove_vowels(string): ''' Removes all vowels from a string. Parameters: ---------- string : (str) The string from which vowels should be removed. Return: ---------- The string without any vowels. ''' vowels = ('a', 'e', 'i', 'o', 'u') for letter in string.lower(): if letter in vowels: string = string.replace(letter, '') return string print(remove_vowels("George"))
true
5a01ffdef0fbee8c8d30abc5421c11aa8f21c5ee
sammccauley117/daily-coding-problem
/solutions/problem_050.py
219
4.125
4
def is_rotation(a, b): if len(a) != len(b): return False return b in a + a if __name__ == '__main__': a = input('Input String 1: ') b = input('Input String 2: ') print('Output:', is_rotation(a, b))
false
5e7d2d90974cab1a6fff115844ffc1fbcfb0c97e
MARINEGUB/Projet_to_do_list
/main.py
1,261
4.15625
4
class App: def __init__(self, to_do_list): self.to_do_list = to_do_list self.running = False def start(self): self.running = True while self.running: answer = input("Voulez-vous ajouter un item? --> Ecrivez OUI ou NON: ") answer = answer.upper() if answer == "OUI": a = input("Que voulez-vous rajouter d'autre ?") self.to_do_list.insert(-1,a) print("Voici votre to-do list maj:") self.print() elif answer == "NON": answer = input("Voulez-vous supprimer un item? --> Ecrivez OUI ou NON: ") answer = answer.upper() if answer == "OUI": a = input ("Quel item voulez-vous supprimer ?") self.to_do_list.remove(a) print("Voici votre to-do list maj:") self.print() elif answer == "NON": print("Vous avez terminé votre to-do list") print("Voici votre to-do list:") self.print() self.running = False else: print("Ceci n'est pas une réponse par OUI ou par NON") else: print("Ceci n'est pas une réponse par OUI ou par NON") def print(self): [print(i) for i in self.to_do_list] app = App(["manger", "boire", "dormir"]) app.start()
false
aca1b3def7150d53a6426b8a6e13c49ec753a9f0
iamsomraj/Itertools
/1. itertools_count.py
901
4.6875
5
import itertools # count is a function for counting - starting from 0 # it returns an iterator # it has two arguments such as start ( first element ) and step ( difference ) print("\nitertools.count() is checked using the next method 2 times : \n") counter = itertools.count() # by default , start is 0 and step is 1 print(next(counter)) print(next(counter)) # it can also be used for indexing a list for the values # here a value of list is indexed with the help of itertools.count and zip # zip clubs consecutive elements of its arguement into a tuple # as zip returns an iterator , therefore we have to convert it to list print("\n\nReal life example of count is - List Indexing \n") numbers = [100, 200, 300, 400] print("List is - ") print("\n{}\n".format(numbers)) real_data = zip(itertools.count(),numbers) real_data = list(real_data) print("\nResult after zipping - \n") print(real_data)
true
38dfbb5a90ac0589824a28f81fc8a31fb364a5e4
saibharadwaj1992/Practice-Python
/PrimeOrNot.py
265
4.1875
4
def isPrime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return True return False num = int(input('Enter the number')) if isPrime(num): print(num, ' is not prime') else: print(num, ' is prime')
true
dfbe9fab0faea553fd269b2788bc71326f4353d2
Praful-a/Python-Programming
/Programs/List/set_3.py
1,392
4.375
4
"""Get the frequency of the elements in a list.""" """First Method""" # def get_freq(li): # freq = {} # count = 0 # for i in li: # if i not in freq: # freq[i] = 1 # else: # freq[i] += 1 # return freq # # lst = [10, 1, 1, 2, 3, 100, 200, 200] # print(get_freq(lst)) """Second Method""" # def countFreq(arr, n): # # Mark all array elements as not visited # visited = [False for i in range(n)] # # Traverse through array elements # # and count frequencies # for i in range(n): # # Skip this element if already # # processed # if (visited[i] == True): # continue # # Count frequency # count = 1 # for j in range(i + 1, n, 1): # if (arr[i] == arr[j]): # visited[j] = True # count += 1 # print(arr[i], count) # # # Driver Code # if __name__ == '__main__': # arr = [10, 1, 1, 2, 3, 100, 200, 200] # n = len(arr) # countFreq(arr, n) """Count the number of elements in a list within a specified range.""" def count_range_in_list(li, min, max): ctr = 0 for n in li: if min <= n <= max: ctr += 1 return ctr lst = [10, 20, 30, 40, 40, 40, 70, 80, 99] print(count_range_in_list(lst, 40, 100)) list2 = ['a','b','c','d','e','f'] print(count_range_in_list(list2, 'a', 'e'))
false
bf4964ce77767609c3ef6821e4b961b7073be681
Praful-a/Python-Programming
/Integers/exercise.py
962
4.4375
4
# num = 3 # type funciton use to see the type of your variable. print(type(num)) # Addition print(3 + 2) # Substraction print(3 - 2) # Multiplication print(3 * 2) # Division print(3 / 2) # Floor Division print(3 // 2) # Powers print(3 ** 2) # Modulus print(3 % 2) print(3 % 2) print(4 % 2) print(5 % 2) # Orders in python # In programming order terms this will use our BODMAS Rules. print(3 * (2 + 1)) num = 1 # num = num + 1 num += 1 print(num) num *= 10 print(num) # This abs funciton in python tell us the absolute values. print(abs(-3)) # return 3 in the output print(round(3.75, 1)) This is help funciton use to see any kind of help according to the function in python. help(round) # Comparisons num_1 = 3 num_2 = 2 print(num_1 == num_2) print(num_1 > num_2) print(num_1 < num_2) print(num_1 <= num_2) print(num_1 >= num_2) num_1 = '100' num_2 = '200' # Here we are using casting. num_1 = int(num_1) num_2 = int(num_2) print(num_1 + num_2)
true
3cb63b42640db12e53fd1d5e9025219adf4ad047
alexlapinskiy/labs
/venv/lab3_lev3.py
663
4.375
4
print("--- with IF ---") day=int(input("Enter day of month: ")) if (day>31): print("Wrong number of day, max value is 31. Try again.") elif(day==6): print("Petrenko A.O. Golos I.A.") elif (day==15): print("Aleksievich A.O. Ivanov N.I.") elif (day==18): print("Kurgan A.V. Males T.M. ") elif(day==29): print("Maksimov M.M. Zarubin A.D.") elif(day==3): print("Leonov A.P. Klinkov D.A.") else:print("There are no birthdays on this day") print("") print("--- without IF ---") day1=int(input("Enter day of month: ")) choices = {6:("Petrenko A.O. Golos I.A."), 15:("Aleksievich A.O. Ivanov N.I."), 18:("Kurgan A.V. Males T.M. "), 29:("Maksimov M.M. Zarubin A.D."), 3:("Leonov A.P. Klinkov D.A."),} result = choices.get(day1, 'There are no birthdays on this day') print(result)
false
949ec44663b9181db5548c8f3a054238b153f16c
EricWangyz/Exercises
/排序算法/插入排序.py
1,382
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/7 11:15 # @Author : Eric Wang # @File : 插入排序.py def insertionSort(nums): ''' 分为有序列表和无序列表,将无序列表中小于有序列表最后一个数的数插入到有序列表中合适的位置 :param nums: :return: ''' length = len(nums) for i in range(1, length): j = i -1 if nums[i] < nums[j]: tmp = nums[i] nums[i] = nums[j] j = j - 1 while j >= 0 and nums[j] > tmp: nums[j+1] = nums[j] j = j - 1 nums[j+1] = tmp return nums # def insert(nums): # length = len(nums) # for i in range(1,length): # j = i - 1 # # if nums[i] < nums[j]: # tmp = nums[i] # nums[i] = nums[j] # # j = j - 1 # while j > 0 and nums[j] > tmp: # nums[j+1] = nums[j] # j = j -1 # nums[j+1] = tmp def insert(nums): length = len(nums) for i in range(1, length): j = j - 1 if nums[i] < nums[j]: tmp = nums[i] nums[i] = nums[j] j = j - 1 while j > 0 and nums[j] > tmp: nums[j+1] = nums[j] j = j - 1 nums[j+1] = tmp return nums
false
9777ca1d3d5f3db121b832cd308d667892746e93
HongyuanZhang/Numerical-Algorithms
/equation_solver/false_position.py
677
4.15625
4
''' The Method of False Position for solving equations ''' import math # method of false position that stops when num_step iterations have been executed def false_position(func, a, b, num_step): if func(a)*func(b) >= 0: print("[a,b] is not a valid starting interval") return math.nan else: f_a = func(a) f_b = func(b) for i in range(num_step): c = (b*f_a-a*f_b)/(f_a-f_b) f_c = func(c) if f_c == 0: return c elif f_a*f_c < 0: b = c f_b = f_c else: a = c f_a = f_c return (a+b)/2
true