blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4345f6601d08be66b47368f450854c28a6bc8061
larrydanny/learning-python
/lists_method.py
1,790
4.3125
4
numbers = [3, 2, 7, 4, 5, 1] print("Add new value 22 at the end on the list") numbers.append(22) print(numbers) print("Add new value 10 at 2 index on the list") numbers.insert(2, 22) # 2 is index and 10 is value print(numbers) print("Get index of given item 7") print(numbers.index(7)) print("If given item not in lists index method given error") print("So, if we print print(numbers.index(70))") print("Getting below error") # print(numbers.index(70)) print(""" Traceback (most recent call last): File "lists_method.py", line 17, in <module> print(numbers.index(70)) ValueError: 70 is not in list """) print("Check item exist or not in list") print(70 in numbers) print("Count how many time add the given item 22 in list") print(numbers.count(22)) print("Sort the list") numbers.sort() print(numbers) print("Reverse the list") numbers.reverse() print(numbers) print("Copy the list into new variable") numbers2 = numbers.copy() numbers.append(11) print("Main => ", numbers) print("Copy => ", numbers2) print("Remove given item 7 of the list") numbers.remove(7) print(numbers) print("Remove last item of the list") numbers.pop() print(numbers) print("Remove all items of the list") numbers.clear() print(numbers) # Write a program to remove the duplicates in a list print("Write a program to remove the duplicates in a list") # numbers = [4, 3, 6, 2, 5, 3, 7, 8, 2] numbers = [2, 2, 4, 6, 3, 4, 6, 1] print(numbers) for number in numbers: count = numbers.count(number) if count > 1: numbers.remove(number) print(numbers) # this one given right output but indexing is different # Right one numbers = [2, 2, 4, 6, 3, 4, 6, 1] uniques = [] print(numbers) for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
true
594c5161b6fd9de2d840508cfb1a2f219a8fac81
larrydanny/learning-python
/lists.py
776
4.4375
4
names = ["Larry", "Danny", "Python", "List", "Name"] print("Full lists:") print(names) print("Get name using index of lists:") print(names[2]) print("Update 3 index text lists:") names[3] = "React" print(names) print("Using range operator [start:end]:") print("Display 2 and 3 index value means less one from end index") print(names[2:4]) print("if no start and end index display full lists") print(names[:]) print("if no start index, default start 0") print(names[:3]) print("if no end index, display start to rest of all from lists") print(names[2:]) # Write a program to find largest number in a list numbers = [12, 2, 234, 34, 113] largestNumber = numbers[0] for number in numbers: if largestNumber < number: largestNumber = number print(largestNumber)
true
aa5ae5867e1103ef8f5292bce27d53d022b0b065
nanako-chung/python-beginner
/Assignment 1/ChungNanako_assign1_problem2.py
1,666
4.46875
4
# Nanako Chung # September 16th, 2016 # M/W Intro to Comp Sci # Problem #2: Using the print function # First, we must name the class by asking the user to store data into a variable. We use the input function to do this. name1 = input("Please enter name #1: ") name2 = input("Please enter name #2: ") name3 = input("Please enter name #3: ") # Secondly, we create spaces on lines and print the data accordingly. print() print("Here are your names in every possible order:") print("--------------------------------------------") print() # The next three lines determine how the names are represented in #1. # The end function is used to prevent the comma used from the sep=", " of interfearing with the "1.", but to keep all the data on the same line separated by commas. print("1.", end=" ") print(name1, name2, name3, sep=", ") print() # This is the same as the previous three lines, except the variables are presented in a different order. print("2.", end=" ") print(name1, name3, name2, sep=", ") print() # This is the same as the previous three lines, except the variables are presented in a different order. print("3.", end=" ") print(name2, name1, name3, sep=", ") print() # There is a "\n" because we are indicating to Python that we would like this printed on the next line. print("4.", name2, "\n", name3, "\n", name1, sep="") print() # This is the same as the previous two lines, except the variables are presented in a different order. print("5.", name3, "\n", name2, "\n", name1, sep="") print() # This is the same as the previous two lines, except the variables are presented in a different order. print("6.", name3, "\n", name1, "\n", name2, sep="")
true
f329ca2ce2c101107f77409d0a0645c233ab2b95
nanako-chung/python-beginner
/Assignment 5/ChungNanako_assign5_problem1.py
1,970
4.3125
4
#Nanako Chung #Intro to Computer Programming M/W #October 24th, 2016 #Problem #1: Pizza Party #create counter for slices needed to get total amount of slices needed for order slices_needed=0 #ask user for budget, cost of each slice, cost of each pie, and num of people budget=float(input("Enter budget for your party: ")) cost_slice=float(input("Cost per slice of pizza: ")) cost_pie=float(input("Cost per whole pizza place: ")) people=int(input("How many people will be attending your party? ")) #create a for loop to count up the number of people for i in range(1, people+1): slices_per_person=int(input("Enter number of slices for person "+"#"+str(i)+": ")) #create while loop to ask user for number of slices per person while True: if slices_per_person<0: print("Not a valid entry, try again!") print() slices_per_person=int(input("Enter number of slices for person "+"#"+str(i)+": ")) else: break #get total number of slices needed slices_needed+=slices_per_person #calculate total cost of slices and format it total=(((slices_needed//8)*cost_pie)+((slices_needed%8)*cost_slice)) ftotal=format(total, ".2f") #calculate leftover cost leftover=budget-total fleftover=format(leftover, ".2f") #create if statements to produce output if leftover==0: print("You should purchase", slices_needed//8, "pies and", slices_needed%8, "slices") print("Your total cost will be:", ftotal) print("You will have no money left after your order.") elif leftover<0: print("Your order cannot be completed.") print("You would need to purchase", slices_needed//8, "pies and", slices_needed%8, "slices") print("This would put you over the budget by", format(total-budget, ".2f")) else: print("You should purchase", slices_needed//8, "pies and", slices_needed%8, "slices") print("Your total cost will be:", ftotal) print("You still have", fleftover, "after your order.")
true
e64be02c858f43b52e83a034195af1176159b8b0
carlosmaniero/ascii-engine
/ascii_engine/pixel.py
1,393
4.125
4
""" This module contains the a pixel representation In this case a pixel is a character in the screen """ class Pixel: """ A pixel is the small part in the screen. It is represented by a character with a foreground and background color. """ def __init__(self, char, foreground_color=None, background_color=None): self.__char = char self.__foreground_color = foreground_color self.__background_color = background_color def get_foreground_color(self): """ Get the pixel foreground color in a RGB format """ return self.__foreground_color def get_background_color(self): """ Get the pixel background color in a RGB format """ return self.__background_color def get_char(self): """ Get the pixel character. It returns a string of one character """ return self.__char def __eq__(self, other): if not isinstance(other, Pixel): return False same_char = self.get_char() == other.get_char() same_fg = self.get_foreground_color() == other.get_foreground_color() same_bg = self.get_background_color() == other.get_background_color() return same_char and same_fg and same_bg def __repr__(self): return 'Pixel({})'.format(repr(self.__char)) BLANK_PIXEL = Pixel(' ')
true
96057fafac5f7ed6ef5a7f48757d6ff954017122
Pavankumar45k/Python
/Array Programs/Array rotation.py
692
4.5
4
#Array Rotation from array import * n=int(input("Enter a Number to shift arrays towards left:")) a=array('i',{11,12,13,14,15}) print("Type of a is:",type(a)) #to print array before conversion print("\n Array Before conversion:") for i in range(len(a)): print(a[i],end=' ') # to move the array towards left by n times for i in range(0,n): #create a empty array to n no.of elements b= a[0] #move elements one by one to before index for j in range(0, len(a)-1): a[j] =a[j+1] # move the elements in b to last index of a a[len(a)-1] = b #to print array after rotation by n times print("\n Array after rotation: "); for i in range(0, len(a)): print(a[i],end=' ')
true
e1d6f5861ef558f55d25b36fa374db78e99c0ce9
paramprashar1/PythonAurb
/py5g.py
553
4.40625
4
# Dictionaries employee = {"eid": 101, "name": "John", "salary": 30000} print(employee) # eid is key and 101 is value print(max(employee)) print(min(employee)) print(len(employee)) employee["eid"] = 222 # updating values of keys KEYS cant be changed but there values can be print(employee["eid"]) print(list(employee.items())) print(list(employee.keys())) print(list(employee.values())) keys = list(employee.keys()) print("Keys:", keys) for key in keys: print(key, "=>", employee[key]) # Explore dictionary of dictionaries #list of dictionaries
true
bfcca2e9fe1fbd72974f1e1af21f8d33e08d4bce
paramprashar1/PythonAurb
/py4e.py
524
4.15625
4
#Cart is an empty list with len as 0 """ cart=["Chicken"] cart.append("Dal Makhni") cart.append("Paneer Butter Masala") print(cart) cart.extend(["Noodles","Manchurian"]) print(cart) cart.insert(1,"Soya Champ") print(cart) cart.pop(2) print(cart) print(cart[2]) """ cart=[] choice="yes" while choice=="yes" or choice=="Yes": foodItem=input("Add Food Item in Cart") cart.append(foodItem) choice=input("Would you like to add more Items?, yes or no?") print(cart) print("Thank you you've added",len(cart),"items")
true
610597451753b96e327a6667da5ea037c5de63b2
B-Rich/Python-Introduction
/Conjectures.py
1,248
4.46875
4
# Python 3.5.2 # TITLE: Conjectures # 1. The Collatz Conjecture - Recursive # Prints the Collatz Conjecture for integer n. # # Given any initial natural number, consider the sequence # of numbers generated by repeatedly following the rule: # - divide by two if the number is even or # - multiply by 3 and add 1 if the number is odd. # # The Collatz conjecture states that this sequence # always terminates at 1. # # For example, the sequence generated by 17 is: # 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 def check_argument(n): """ Check Exceptions. """ # TODO: Check other cases as well. if (n < 1): print ("ERROR: %.2f is less than 1!\n---" % n) return False else: return True def conjecture(n): """ Find conjecture. Recursive.""" print ("%.0f" % n) if (n == 1): print ("---") return elif (n % 2 == 0): n = n / 2 conjecture(n) else: n = n * 3 + 1 conjecture(n) def collatz(n): """ Find Collatz Conjecture if argument is valid. """ if (check_argument(n) == False): return else: conjecture(n) # TEST collatz(0) collatz(1) collatz(7) collatz(17) # 2 - Some Other Conjecture # Other information.
true
15604fd17c3cb6d1561ac199524e0fd25381d84e
maiarawill/python
/mundoDois_Atividade06.py
620
4.21875
4
import datetime atual = datetime.date.today().year nascimento = int(input('Qual o seu ano de nascimento')) idade = atual - nascimento if idade <= 9: print('O atleta tem {} anos e esta na categoria: Mirim'.format(idade)) elif 9 < idade <= 14: print('O atleta tem {} anos e esta na categoria: Infantil'.format(idade)) elif 15 <= idade <= 19: print('O atleta tem {} anos e esta na categoria: Junior'.format(idade)) elif 20 <= idade <= 25: print('O atleta tem {} anos e esta na categoria: Sênior'.format(idade)) elif idade > 25: print('O atleta tem {} anos e esta na categoria: Master'.format(idade))
false
e623d4524ddf421984209674ed104b63028cadee
dhanendraverma/Daily-Coding-Problem
/Day730.py
1,800
4.28125
4
''' /*************************************************************************************************************************************** Good morning! Here's your coding interview problem for today. This problem was asked by Google. What will this code print out? def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(): print(i) flist.append(print_i) return flist functions = make_functions() for f in functions: f() How can we make it print out what we apparently want? ***************************************************************************************************************************************/ ''' # Output of the code would be : 3 3 3 reason behind this is a closure caputures the variable, not the current variable value, for all the functios being # appended to the flist the same variale i is shared among them meaning that each i appended to the function refers to the same memory loction, # since last value stored to the location is 3 hence all three run would output same value.In order to make this work as expected we can get each function it's # own scope variable which would help to maintain the value coming from list in variable named i which has scope local to the function and hence value stored at # each referece would be the value of i at that particalar instace of loop. def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(i=i): print(i) flist.append(print_i) return flist functions = make_functions() for f in functions: f() #output = 1 2 3 # the local binding of the value in variabel i to the scope of the function by using the assignment i==i we can now refer to the value # of i when the function was being appended to the list.
true
3a5a348b95550fcf3e64bf989c252dc57908180e
JoonasSipilae/2021_Python_JoonasSipilae
/Examples/conditions.py
912
4.125
4
print() a = 10 b = 20 # Vertailuoperaattoreita # == yhtäsuuruusvertailu if a == b: print(a, "equals", b) # sep-parametrillä voidaan määritellä erotinmerkki else: print(a, "does not equal", b) # != erisuuruusvertailu if a != b: print(a, "does not equal", b) else: print(a, "equals", b) if not a == b: print(a, "does not equal", b) else: print(a, "equals", b) # and if a < 30 and b < 30: print(a, "and", b, "are both smaller than 30") # pienempi, suurempi if a < b: print(a, "is less than", b) elif a > b: print(b, "is less than", a) else: print(a, "equals", b) # <= , >= if a <= b: print(a, "is less than or equals", b) else: print(b, "is less than or equals", a) # vertailun tulos muuttujaan result = a == b print(result) if result: print(a, "equals", b) else: print(a, "does not equal", b) print() # pythonissa ei switch-case rakennetta
false
4a9fe3ccaf192afbdcac732dc1b9d043bd3eae3d
marioalvarez/master-phyton
/09-listas/predefinidas.py
719
4.5
4
#Funciones y metodos mas comunes cantantes = ['2pac','drake','bad bunny','julio iglesias'] numeros = [1,2,5.5,6,3,4] #ordenar print(numeros) numeros.sort() print(numeros) #añadir elementos cantantes.append("mario alvarez") cantantes.insert(1, "super mario") print(cantantes) #Eliminar elementos cantantes.pop(1) cantantes.remove('bad bunny') print(cantantes) #Darle la vuelta al arreglo print(numeros) numeros.reverse() print(numeros) #buscar dentro de una lista print('drake' in cantantes) #contar elementos print(cantantes) print(len(cantantes)) #cuantas veces aparece un elemento numeros.append(8) print(numeros.count(8)) #conseguir indice print(cantantes.index("drake")) #unir listas cantantes.extend(numeros) print(cantantes)
false
a8d8e375f3b2b6e92c774522a33ee26d8bc2189b
marioalvarez/master-phyton
/11-ejercicios/ejercicio1.py
1,513
4.59375
5
""" Ejercicio 1. Hacer un programa que tenga una lista de 8 numeros enteros y haga lo siguiente: hecho-Recorrer la lista y mostrarla hecho-hacer una funcion que recorra listas de numeros y devuelva un string hecho-ordenarla y mostrarla hecho-mostrar su longitud hecho-buscar algun elemento ( que el usuario pida por teclado) """ #Crear la lista numeros = [13, 64, 52, 73, 21, 7, 91, 63] #crear funcion que recorra lista y devuelva string def mostrarLista(lista): resultado= "" #for numero in numeros: cambiamos a datos genericos para abstraer la funcion for elemento in lista: resultado += "Elemento: " + str(elemento) resultado += "\n" return resultado #recorrer y mostrar print("### recorrer y mostrar ###") """ for numero in numeros: print(numero) """ print(mostrarLista(numeros)) print(mostrarLista(['victor','juan','pepe'])) #Parte2 #Ordenar y mostrar print("### Ordenar y mostrar ###") numeros.sort() print(mostrarLista(numeros)) #Mostrar su longitud print("### Mostrar su longitud ###") print(len(numeros)) #Busqueda en la lista print("### Busqueda en la lista ###") busqueda = int(input("introduce un numero: ")) comprobar = isinstance(busqueda, int) while not comprobar or busqueda <= 0: busqueda = int(input("introduce un numero: ")) else: print(f"Has introducido el {busqueda}") print(f"### Buscar en la lista el numero {busqueda} ###") search = numeros.index(busqueda) print(f"El numero buscado existe en la lista, es el indice: {search}")
false
f1af8664ba9acd95d8896575d605335fd14c4795
HectorGarciaPY/primer1.py
/Selecció simple/selsimp1.py
670
4.125
4
print("Selecciona un coche:") print("a) Porsche") print("b) Lamborghini") print("c) Maserati") x=input() if x=="a" or x=="A" or x=="a)" or x=="Porsche" or x=="porsche" or x=="Porche" or x=="porche" or x=="Porxe" or x=="porxe": print("Has escogido un Porsche") elif x=="b" or x=="B" or x=="b)" or x=="Lamborghini" or x=="lamborghini" or x=="Lamborgini" or x=="lamborgini" or x=="Lambo" or x=="lambo": print("Te van los Lamborghinis") elif x=="c" or x=="C" or x=="c)" or x=="Maserati" or x=="maserati" or x=="Maseratti" or x=="maseratti" or x=="Maseraty" or x=="maseratty": print("Has escogido un Maserati") else: print("Vuelve a intentarlo que no te entiendo")
false
d7d92a9e21aadd244e73b707f8de43be22824179
Elaviness/GB_start_python
/lesson5/task_5.py
724
4.21875
4
""" Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. """ with open("lesson5_5.txt", 'w') as num_file: num_file.write('1 6 7 8 2 9 3 4') with open("lesson5_5.txt", 'r') as num_file: str = num_file.read() num_list = str.split(' ') summary = 0 try: for itm in num_list: summary += int(itm) except ValueError: print("Неккоректно введены данные файл.") print(summary)
false
839a0bee39b3bdee1449563c823f613b2472c8b3
Elaviness/GB_start_python
/lesson5/task_2.py
651
4.125
4
""" Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ with open("lesson5_2.txt", 'r+' , encoding="utf-8") as file: str_list = ['stroka_1\n','stroka_2\n','stroka_3333\n'] file.writelines(str_list) lines_count = 0 for line in file: lines_count += 1 symbol_count = 0 for symb in line: symbol_count += 1 print(f'В {lines_count} строке {symbol_count} символов.')
false
abc009f223364ec951d3ebe0a8f39e7263a7c786
afaubion/Python-Tutorials
/Basic_Operators.py
1,115
4.34375
4
# basic order of operations number = 1 + 2 * 3 / 4.0 print(number) print("\n") # modulo remainder = 11 % 3 print(remainder) print("\n") # using two multiplication symbols creates power relationship squared = 7 ** 2 cubed = 2 ** 3 print(squared) print(cubed) print("\n") # using operators with strings helloworld = "hello" + " " + "world" print(helloworld) print("\n") lotsofhellos = "hello" * 10 print(lotsofhellos) # hellohellohellohellohello... print("\n") # operators with lists even_numbers = [2, 4, 6, 8] odd_numbers = [1, 3, 5, 7] all_numbers = odd_numbers + even_numbers print(all_numbers) print("\n") print([1, 2, 3] * 3) print("\n") # EXERCISE x = object() y = object() # TODO: change this code x_list = ([x] * 10) y_list = ([y] * 10) big_list = x_list + y_list print("x_list contains %d objects" % len(x_list)) print("y_list contains %d objects" % len(y_list)) print("big_list contains %d objects" % len(big_list)) # testing code if x_list.count(x) == 10 and y_list.count(y) == 10: print("Almost there...") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Great!")
true
77ee5325d1f6a6f0a8a63f3b12e8f7168df9535f
afaubion/Python-Tutorials
/Multiple_Function_Arguments.py
2,653
4.90625
5
# Every function in Python receives a predefined number of arguments, if declared normally, like this: # ----- def myfunction(first, second, third): # do something with the 3 variables ... # ----- # It is possible to declare functions which receive a variable number of arguments, # using the following syntax: # ----- def foo(first, second, third, *therest): print("First: %s" % first) print("Second: %s" % second) print("Third: %s" % third) print("And all the rest... %s" % list(therest)) # ----- # The "therest" variable is a list of variables, # which receives all arguments which were given to the "foo" function after the first 3 arguments. # So calling foo(1,2,3,4,5) will print out: # ----- def foo(first, second, third, *therest): print("First: %s" %(first)) print("Second: %s" %(second)) print("Third: %s" %(third)) print("And all the rest... %s" %(list(therest))) foo(1,2,3,4,5) # ----- # Outputs: """ First: 1 Second: 2 Third: 3 And all the rest... [4, 5] """ # It is also possible to send functions arguments by keyword, # so that the order of the argument does not matter, using the following syntax. # The following code yields the following output: The sum is: 6 Result: 1 # ----- def bar(first, second, third, **options): if options.get("action") == "sum": print("The sum is: %d" %(first + second + third)) if options.get("number") == "first": return first result = bar(1, 2, 3, action = "sum", number = "first") print("Result: %d" %(result)) # ----- # Outputs: """ The sum is: 6 Result: 1 """ # The "bar" function receives 3 arguments. # If an additional "action" argument is received, # and it instructs on summing up the numbers, # then the sum is printed out. # Alternatively, the function also knows it must return the first argument, # if the value of the "number" parameter, passed into the function, is equal to "first". # EXERCISE # Fill in the foo and bar functions so they can receive a variable amount of arguments (3 or more) # The foo function must return the amount of extra arguments received. # The bar must return True if the argument with the keyword magicnumber is worth 7, and False otherwise. # ----- # edit the functions prototype and implementation def foo(a, b, c, *args): return len(args) def bar(a, b, c, **kwargs): return kwargs["magicnumber"] == 7 # test code if foo(1,2,3,4) == 1: print("Good.") if foo(1,2,3,4,5) == 2: print("Better.") if bar(1,2,3,magicnumber = 6) == False: print("Great.") if bar(1,2,3,magicnumber = 7) == True: print("Awesome!") # ----- # Outputs: """ Good. Better. Great. Awesome! """
true
20396ec6f593c24fa5e7ed56b51f435e228bae31
afaubion/Python-Tutorials
/List_Comprehensions.py
1,378
4.75
5
# List Comprehensions is a very powerful tool, # which creates a new list based on another list, in a single, readable line. # For example, let's say we need to create a list of integers # which specify the length of each word in a certain sentence, # but only if the word is not the word "the". # Ex: ----- sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [] for word in words: if word != "the": word_lengths.append(len(word)) print(words) print(word_lengths) # ----- # Outputs: """ ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] [5, 5, 3, 5, 4, 4, 3] """ # Using a list comprehension, we could simplify this process to this notation: # ----- sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [len(word) for word in words if word != "the"] print(words) print(word_lengths) # ----- # Outputs: """ ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] [5, 5, 3, 5, 4, 4, 3] """ # EXERCISE # Using a list comprehension, create a new list called "newlist" out of the list "numbers", # which contains only the positive numbers from the list, as integers. # ----- numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] newlist = [int(x) for x in numbers if x > 0] print(newlist) # ----- # Outputs: """ [34, 44, 68, 44, 12] """
true
a18e422bb8013ca18c3786ea758b633a03990b1a
chrishoerle6/Leetcode-Solutions
/Python/Easy/Sorting and Searching/First_Bad_Version.py
1,429
4.25
4
## Author: Chris Hoerle ## Date: 08/20/2021 ''' You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. Examples: Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. Input: n = 1, bad = 1 Output: 1 Constraints: 1 <= bad <= n <= 231 - 1 ''' # The isBadVersion API is already defined for you. # @param version, an integer # @return an integer # def isBadVersion(version): class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ start = 1 end = n while start < end: mid = int(start + (end - start) / 2) if isBadVersion(mid): end = mid else: start = mid + 1 return start
true
b2a7820b20882ce1f52cc14c690d40088948f961
chrishoerle6/Leetcode-Solutions
/Python/Easy/Math/Count_Primes.py
775
4.1875
4
## Author: Chris Hoerle ## Date: 08/20/2021 ''' Count the number of prime numbers less than a non-negative number, n. Examples: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Input: n = 0 Output: 0 Input: n = 1 Output: 0 Constraints: 0 <= n <= 5 * 106 ''' class Solution: def countPrimes(self, n: int) -> int: if n == 0 or n == 1: return 0 primes = [1]*n primes[0] = 0 primes[1] = 0 i = 2 while i < n: temp = i if primes[i]: temp += i while temp < n: primes[temp] = 0 temp += i i += 1 return sum(primes)
true
5a8f02c10fbe40bdfd555d1b0d186b19ca38c7f1
chrishoerle6/Leetcode-Solutions
/Python/Easy/Trees/Validate_Binary_Tree.py
1,434
4.28125
4
## Author: Chris Hoerle ## Date: 08/12/2021 ''' Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Examples: Input: root = [2,1,3] Output: true Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: return self.validate(root, None, None) def validate(self, root, minimum, maximum): if root is None: return True elif minimum is not None and root.val <= minimum: return False elif maximum is not None and root.val >= maximum: return False return self.validate(root.left, minimum, root.val) and self.validate(root.right, root.val, maximum)
true
7c265be4916796794f9bca60890936bbc0ade1d9
chrishoerle6/Leetcode-Solutions
/Python/Easy/Trees/Convert_Sorted_Array_To_Binary_Search_Tree.py
1,467
4.125
4
## Author: Chris Hoerle ## Date: 08/20/2021 ''' Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one. Examples: Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted: Input: nums = [1,3] Output: [3,1] Explanation: [1,3] and [3,1] are both a height-balanced BSTs. Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums is sorted in a strictly increasing order. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: if len(nums) == 0: return None return self.constructTreeFromArray(nums, 0, len(nums) - 1) def constructTreeFromArray(self, nums, left, right): if left > right: return None midpoint = left + (right - left) // 2 node = TreeNode(nums[midpoint]) node.left = self.constructTreeFromArray(nums, left, midpoint - 1) node.right = self.constructTreeFromArray(nums, midpoint + 1, right) return node
true
2c1ac11465f615cb91c849da97e6a576598de69e
JacksonLeng/Computer-Science
/python_midterm_review 4/answers/16.py
517
4.40625
4
# 16. Movies You Want to See: # Use a for-loop and sorted() to print your list in alphabetical order # without modifying the actual list. # Show that your list is still in its original order by printing it as well. movies_i_want_to_see = ['Space Jam', 'Hidden Figures', 'The Pursuit of Happyness', 'Shrek', 'Independence Day'] # Print each Movie in Alphabetical Order With A For-Loop for movie in sorted(movies_i_want_to_see): print(movie) # Show list is still in its original order print(movies_i_want_to_see)
true
90b1816c6f0616b2787b56d0973135e50abe4921
JacksonLeng/Computer-Science
/PYTHON WOK/4-6--4-13/4.11.py
304
4.15625
4
pizzas=['tao yuan pizza','Cyn pizza','beef pizza'] friend_pizzas=pizzas[:] pizzas.append('wu han pizza') friend_pizzas.append('tomato pizza') print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("My friend’s favorite pizzas are:") for pizza in friend_pizzas: print(pizza)
false
c88b07dd9446dcf5d006d64a8f65168a9f4778ce
sb2rhan/PythonCodes
/MSTutorials/Conditionals.py
1,267
4.21875
4
# price = input("How much did you pay: ") # price = float(price) # converting price to float # if price >= 1.00: # tax = .07 # else: # tax = 0 # print("Tax rate is: " + str(tax)) # country = input("Enter the name of your country: ") # if country.capitalize() == "Kazakhstan": # print("Hey, I'm from there too") # else: # print("You are from: " + country) # country = input("What country do you live in: ") # province = input("What province do you live in: ") # tax = 0 # if country.capitalize() == "Canada": # # if province.capitalize() == "Alberta" or province.capitalize() == "Nunavut": # # tax = 0.05 # if province.capitalize() in("Alberta", "Nunavut", "Yukon"): # tax = 0.05 # elif province.capitalize() == "Ontario": # tax = 0.13 # else: # tax = 0.15 # else: # tax = 0.0 # print("Tax is: " + str(tax) + " %") # gpa = float(input("What is your GPA: ")) # lowest_grade = float(input("What is your lowest grade: ")) # honour_roll = False # booleans must be capitalized # if(gpa>=0.85 and lowest_grade>=0.7): # honour_roll = True # if honour_roll: # or if honour_roll = True: # print("You made the honour roll") # else: # print("You didn't make the honour roll")
false
6e3ecec16a91fd3bb6160ce85b791a0c9a3e3237
sb2rhan/PythonCodes
/ITStepTutorials/OOP/classes_intro.py
2,948
4.15625
4
class Car: mark = 'Tesla' model = 'P100D' year = 2019 def start(self): return f'Car {self.mark} {self.model} has been started' def stop(self): return f'Car {self.mark} {self.model} has been stopped' """ Difference between static method and class method: 1. Static method behaves as method that is not included in the class, so it behaves as module function 2. Class method takes cls argument and uses it for working with class """ @staticmethod def get_info(): return f'{Car.mark} {Car.model} {Car.year}' @classmethod def get_class_info(cls): return f'{cls.mark} {cls.model} {cls.year}' # car1 = Car() # print('Type of car1:', type(car1)) # car2 = Car() # print(car1.mark) # print(car2.model) # print(car1.start()) # print(car2.stop()) # print(Car.get_info()) # print(Car.get_class_info()) class Man: def __init__(self, name, lastname): self.name = name self.lastname = lastname def get_name(self): return self.name def __str__(self): return f'{Man.__name__}: {self.name} {self.lastname}' # user = Man('Mark', 'Wand') # print('Is id exists in user object:', hasattr(user, 'id')) # print('Let\'s create it') # setattr(user, 'id', 1) # id will be only in user objects # print(user, user.id) # __str__ method + id # print(dir(Man)) # print(dir(user)) # # Static constructer # class Counter: # count = 0 # @staticmethod # def __init__(): # Counter.count += 1 # print(Counter.count) # print(Counter()) # print(Counter()) # # Another type of constructor # class Vehicle: # def __new__(cls): # print('New vehicle object') # return super(Vehicle, cls).__new__(cls) # def __init__(self): # print('Initiate class') # def __del__(self): # print('Delete class') # v1 = Vehicle() # __new__ method works first then only __init__ method is invoked # # in the end, __del__ destructor works """ Modificators in Python is just an agreement between programmers So we just differentiate fields by _ """ class Transport: def __init__(self): self.mark = 'Toyoto' # public self._model = 'Camry' # protected self.__price = 300000 # private # transport1 = Transport() # print(transport1._model) # will print # print(transport1.__price) # will be error, cuz Python renames this property """ Inheritance Actually, every class in Python inherits from object class We can show by parentheses it like this: class Example(): pass """ class Horse: is_horse = True def race(self): print('Running in the race') class Donkey: is_donkey = True def push(self): print('Pushing the goods') class Mule(Horse, Donkey): is_mule = True mule = Mule() print(mule.is_donkey) print(mule.is_horse) print(mule.is_mule) mule.race() mule.push()
true
5bc4e90a4ad1e45ae203c529b5533631ebb7269f
sb2rhan/PythonCodes
/ITStepTutorials/Collections_Functools/func_tools.py
2,483
4.1875
4
# Functools # a module of high-level functions # they are used to modify other low-level functions # so they are decorators import functools # lru_cache for storing repetetive data import requests # # caches get_webpage function # @functools.lru_cache(maxsize=24) # def get_webpage(module): # webpage = f'https://docs.python.org/3/library/{ module }.html' # response = requests.get(webpage) # if response.status_code == 200: # return response.text # else: # return None # modules = ['os', 'functools', 'collections', 'sys'] # for m in modules: # html_page = get_webpage(m) # if html_page: # print(m, 'is found') # else: # print(m, 'is not found') # Another example of lru_cache # without lru_cache it is gonna stuck at numbers like 100 or more # @functools.lru_cache() # def fibonacci(n): # if n < 2: # return n # return fibonacci(n - 1) + fibonacci(n - 2) # print(fibonacci(100)) # Partial # allows us to invoke functions by parts # so we can give some parameters at the first invoke # and the rest of parameters at the next call # def getGreetingByName(name, age, last_char='!'): # return f'Hello, {name}{last_char} You are {age} y.o.' # result = functools.partial(getGreetingByName, name='Jack') # print(result) # stored declaration with name parameter only # print(result(age=20)) # now we can print cuz we give it age # Singledispatch # needed to overload functions # @functools.singledispatch # def print_with_type(arg): # print('object: %s' % arg) # # registered only for int variables # @print_with_type.register(int) # def print_int(arg): # print('int: %s' % arg) # @print_with_type.register(str) # def print_str(arg): # print('string: %s' % arg) # print_with_type(3) # print_with_type([3, 1, 'kdsf']) # print_with_type('Hello') # print(print_with_type.dispatch(int)) # to determine what function dispatches this type @functools.singledispatch def add(collection): return sum(collection) @add.register def add_list(list1: list): return sum(list1) @add.register def add_dic(dictionary: dict): return {sum(dictionary.keys()): sum(dictionary.values())} @add.register def add_tuple(tuple1: tuple): return sum(tuple1) @add.register def add_int(num: int): return sum(range(1, num + 1)) print('-' * 30, 'Test of add funcs', '-' * 30) print(add_int(5)) print(add_list([3, 1, 4])) print(add_dic({3: 21, 12: 92})) print(add_tuple((3, 12, 3)))
true
b706d6841a0b6897b63bdade35d603bb3d16e859
mehraveh/ChatSubjects
/filtering.py
456
4.1875
4
def filtering(str, words): if str.endswith("ها") : str = str.replace("ها" , "") elif str.endswith("هاش"): str = str.replace("هاش" ,"") elif str.endswith("های"): str = str.replace("هاش" , "") str_tmp = str if len(str_tmp) > 0: str_tmp = str.replace(str[len(str)-1] ,"") if str_tmp in words and str not in words: print("yes") str = str_tmp return str
false
8c2a61c1c0d630b774bc4b0bcdcbe78b1e1311e7
dunste123/cassidoo-rendezvous
/142_one_row/index.py
855
4.15625
4
# Given an array of words, return the words that can be typed using letters of only one row on a keyboard. # # Extra credit: Include the option for a user to pick the type of keyboard they are using (ANSI, ISO, etc)! # # Example: # # $ oneRow(['candy', 'doodle', 'pop', 'shield', 'lag', 'typewriter']) # $ ['pop', 'lag', 'typewriter'] rows = [ ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm'] ] def one_row(words): possible_words = [] for row in rows: for word in words: contains = all(letter in row for letter in word) if contains: possible_words.append(word) return possible_words print(one_row(['candy', 'doodle', 'pop', 'shield', 'lag', 'typewriter'])) # ['pop', 'typewriter', 'lag']
true
317253748627559c6b607815d60d04a0c77792b5
dunste123/cassidoo-rendezvous
/138_backspacing/index.py
942
4.21875
4
# Given two strings n and m, return true if they are equal when both are typed into empty text editors. The twist: # # means a backspace character. # # Example: # # > compareWithBackspace("a##c", "#a#c") # > true // both strings become "c" # # > compareWithBackspace("xy##", "z#w#") # > true // both strings become "" # import re # regex = r"(.?#)" def do_replace(str): chars = [] for s in str: if s != "#": chars.append(s) elif len(chars) > 0: chars.pop() # return str.replace("#", "\b").strip() # return re.sub(regex, "", str).strip() return "".join(chars) def compare_with_backspace(n, m): # Using == here https://stackoverflow.com/a/1504742/4807235 return do_replace(n) == do_replace(m) print(compare_with_backspace("a##c", "#a#c")) # True print(compare_with_backspace("xy##", "z#w#")) # True print(compare_with_backspace("##xy", "z#w#")) # False
true
df3a99027d7b39c8f83a46ec18018d1231a5fb62
shubhamjante/python-fundamental-questions
/Programming Fundamentals using Python - Part 01/Assignment Set - 03/Assignment on string - Level 2.py
1,081
4.34375
4
""" Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run. Write a python function which performs the run length encoding for a given String and returns the run length encoded String. Provide different String values and test your program ======================================== | Sample Input | Expected Output | ======================================== | AAAABBBBCCCCCCCC | 4A4B8C | | AABCCA | 2A1B2C1A | ======================================== """ def encode(message): # Remove pass and write your logic here encoded = "" message += " " counter = 1 character = message[0] for i in range(1, len(message)): if character == message[i]: counter = counter + 1 else: encoded += str(counter) + character character = message[i] counter = 1 return encoded encoded_message = encode("ABBBBCCCCCCCCAB") print(encoded_message)
true
7f7bbd1e45f33fd18705e43ef2f2185d33103ef5
shubhamjante/python-fundamental-questions
/Programming Fundamentals using Python - Part 01/Assignment Set - 02/Assignment on selection in python - Level 3.py
2,127
4.125
4
""" FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order. A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate. Their non-veg combo is really famous that they get more orders for their non-vegetarian combo than the vegetarian combo. Apart from the cost per plate of food, customers are also charged for home delivery based on the distance in kms from the restaurant to the delivery point. The delivery charges are as mentioned below: ===================================================== | Distance in kms | Delivery charge in Rs per km | ===================================================== | For first 3kms | 0 | | For next 3kms | 3 | | For the remaining | 6 | ===================================================== Given the type of food, quantity (no. of plates) and the distance in kms from the restaurant to the delivery point, write a python program to calculate the final bill amount to be paid by a customer. The below information must be used to check the validity of the data provided by the customer: Type of food must be ‘V’ for vegetarian and ‘N’ for non-vegetarian. Distance in kms must be greater than 0. Quantity ordered should be minimum 1. If any of the input is invalid, the bill amount should be considered as -1. """ """ ===================== Not able to solve ===================== """ def calculate_bill_amount(food_type, quantity_ordered, distance_in_kms): bill_amount = 0 if food_type not in "VN" or quantity_ordered < 1 or distance_in_kms <= 0: return -1 else: bill_amount += 120 if food_type == 'V' else 150 bill_amount *= quantity_ordered dist_01 = distance_in_kms - 3 dist_02 = dist_01 - 3 if dist_01 > 0: if dist_02 > 0: bill_amount += 3 * dist_01 + 6 * dist_02 else: bill_amount += 3 * dist_01 return bill_amount bill_amount = calculate_bill_amount("N", 1, 7) print(bill_amount)
true
bc98f7142d565d2ae272698b052eb1c61016453d
shubhamjante/python-fundamental-questions
/Programming Fundamentals using Python - Part 02/Assignment Set - 07/Assignment on list APIs - Level 3 (puzzle).py
1,726
4.1875
4
""" Use Luhn algorithm to validate a credit card number. A credit card number has 16 digits, the last digit being the check digit. A credit card number can be validated using Luhn algorithm as follows: Step 1a: From the second last digit (inclusive), double the value of every second digit. Suppose the credit card number is 1456734512345698. Take the double of 9,5,3,1,4,7,5 and 1 i.e., 18, 10, 6, 2, 8, 14, 10 and 2 Note: If any number is greater than 9, then sum the digits of that number. i.e., 9, 1, 6, 2, 8, 5 ,1 and 2 Step 1b: Sum the numbers obtained in Step 1a. i.e., 34 Step 2: Sum the remaining digits in the credit card and add it with the sum from Step 1b. i.e., 34 + (8+6+4+2+5+3+6+4) = 72 Step 3: If the total is divisible by 10 then the number is valid else it is not valid. Write a function, validate_credit_card_number(), which accepts a 16 digit credit card number and returns true if it is valid as per Luhn’s algorithm or false, if it is invalid. """ def sum_the_digits(number): return sum(map(int, list(str(number)))) def validate_credit_card_number(card_number): if len(str(card_number)) != 16: return False step_1a = list() for i in list(map(int, list(str(card_number)[:-1][::-2]))): step_1a.append(i+i) step_1b = sum([sum_the_digits(num) for num in step_1a]) step_2 = step_1b + sum(list(map(int, list(str(card_number)[::-2])))) if step_2 % 10: return False else: return True card_number = 1456734512345698 #4539869650133101 #1456734512345698 # #5239512608615007 result = validate_credit_card_number(4539869650133101) if result: print("credit card number is valid") else: print("credit card number is invalid")
true
f9264a548ddafcd40ffaa986e376baa7a219fbb5
drsantos20/mars-rover
/rover.py
2,640
4.21875
4
""" INPUT AND OUTPUT Test Input: 5 5 1 2 N LMLMLMLMM 3 3 E MMRMMRMRRM Expected Output: 1 3 N 5 1 E """ class rover: def __init__(self): """All the variables are initialised here.""" self.x = 0 self.y = 0 self.direction = 'N' self.left = 'L' self.right = 'R' self.move = 'M' self.north = 'N' self.south = 'S' self.east = 'E' self.west = 'W' self.coordinates = '' self.plateau_size = [] def set_data(self, plateau_size, x, y, direction, coordinates): """This function gets the input from main and sets all the variables of class.""" self.plateau_size = plateau_size self.x, self.y, self.direction = x, y, direction self.coordinates = coordinates def coordinates_follow(self): """This function iterates over each of the instruction and calls the respective command function.""" for steps in self.coordinates: if steps is self.left: self.turn_left() elif steps is self.right: self.turn_right() elif steps is self.move: self.move_forward() else: print("Wrong Instruction.") def move_forward(self): """Moves the rover based on the present direction the the rover. Assuming that the rover won't move after the plateau edge is reached.""" if self.direction == self.north and self.y < int(self.plateau_size[1]): self.y = self.y + 1 elif self.direction == self.east and self.x < int(self.plateau_size[0]): self.x = self.x + 1 elif self.direction == self.south and self.y > 0: self.y = self.y - 1 elif self.direction == self.west and self.x > 0: self.x = self.x - 1 def turn_left(self): """Turns the rover left.""" if self.direction == self.north: self.direction = self.west elif self.direction == self.east: self.direction = self.north elif self.direction == self.south: self.direction = self.east elif self.direction == self.west: self.direction = self.south def turn_right(self): """Turns the rover right.""" if self.direction == self.north: self.direction = self.east elif self.direction == self.east: self.direction = self.south elif self.direction == self.south: self.direction = self.west elif self.direction == self.west: self.direction = self.north def get_result(self): """Returns the final result.""" return self.x, self.y, self.direction def main(): r = rover() plateau_size = input().split() x, y, direction = input().split() coordinates = input() r.set_data(plateau_size, int(x), int(y), direction.upper(), coordinates.upper()) r.coordinates_follow() result = r.get_result() print(result[0], result[1], result[2]) if __name__ == '__main__': main()
true
1c9ab9ee06ed409ecd052ffae5dc104135ab1c3a
ziwuniao/py000
/ex07+.py
1,442
4.15625
4
# 1.注释 # 输出字符串。 print("Mary had a little lab.") # 输出带格式化变量的字符串。 print("Its fleece was white as {}".format('snow')) # 输出字符串。 print("And everywhere that Mary went.") # 输出字符串并且运算。额,真是个偷懒的好办法啊。 print("." * 10) # what'd that do? # 输出一系列单个字母型自串符。(做的时候不明所以。后来发现有彩蛋。作者的幽默。) end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e\000" # 参考http://www.runoob.com/python3/python3-string.html # 不得已而为之,否则输出的字母总是全部连在一起...不知其他同学如何解决这个问题。 end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # end=''的作用是,不用换行,继续显示输出。。。 # (PS:和前面的作业可以联系起来。不用换行的办法。) # watch end = '' at the end. try removing it to see what happens print(end1 + end2 + end3 + end4 + end5 + end6,end='') print(end7 + end8 + end9 + end10 + end11 + end12) # 2.已读。 #3.额,还是标点符号有时会遗漏一两个,以及更大的bug...。 # print("Its fleece was white as {}".format('snow')) # 应该是 print("Its fleece was white as {}.".format('snow')) # print(end7 + end8 + end9 + end11 + end12) 应该是 print(end7 + end8 + end9 + end10 + end11 + end12) #4.记住了。 #5.ok.这是安慰么?。。。
false
63be02823e11adf100f08cf09996b868a71f271e
saurav188/python_practice_projects
/square_root.py
397
4.3125
4
#Given a positive integer, find the square #root of the integer without using any built #in square root or power functions #(math.sqrt or the ** operator). #Give accuracy up to 3 decimal points. def sqrt(x): a=0 b=x y=(a+b)/2 while round(a,3)!=round(b,3): if y**2>x: b=y else: a=y y=(a+b)/2 return round(y,3) print(sqrt(6))
true
ad08317c8a72d9fd6d1f5439390b78ce4e9da8ea
chenxingyuoo/learn
/python_learn/廖雪峰python/1.python基础/3.使用list和tuple.py
1,128
4.125
4
# list 初始化后可以修改 classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) len(classmates) print(classmates[0]) print(classmates[-1]) classmates.append('Adam') classmates.insert(1, 'Jack') print(classmates) classmates.pop() classmates.pop(1) print(classmates) s = ['python', 'java', ['asp', 'php'], 'scheme'] print(s[2][1]) # tuple 初始化后不可以修改 c = ('Michael', 'Bob', 'Tracy') t = ('a', 'b', ['A', 'B']) t[2][0] = 'X' t[2][1] = 'Y' print(t) # ('a', 'b', ['X', 'Y']) 虽然改变了,但是只是第2个元素list改变了 # 表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。 # tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的! # 练习 L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[0][0]) print(L[1][1]) print(L[2][2])
false
387076d31be9acfd5f41edccab076a7e70149482
chenxingyuoo/learn
/python_learn/廖雪峰python/20.异步io/1.协程.py
1,081
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 生产者生产消息后,直接通过yield跳转到消费者开始执行,待消费者执行完毕后,切换回生产者继续生产,效率极高: def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c) # [PRODUCER] Producing 1... # [CONSUMER] Consuming 1... # [PRODUCER] Consumer return: 200 OK # [PRODUCER] Producing 2... # [CONSUMER] Consuming 2... # [PRODUCER] Consumer return: 200 OK # [PRODUCER] Producing 3... # [CONSUMER] Consuming 3... # [PRODUCER] Consumer return: 200 OK # [PRODUCER] Producing 4... # [CONSUMER] Consuming 4... # [PRODUCER] Consumer return: 200 OK # [PRODUCER] Producing 5... # [CONSUMER] Consuming 5... # [PRODUCER] Consumer return: 200 OK
false
19e32cd3149e716ad1449b5ecb461a1fcc30074d
nimbinatus/LPHW
/ex20.py
1,642
4.46875
4
# import argv function from sys module from sys import argv # set up argv script, input_file = argv # defines the function print_all, which prints a file passed in the function # call def print_all(f): print f.read() # defines a function rewind, which finds the beginning of a file using the # seek file object and sets the file's current position using absolute file # positioning def rewind(f): f.seek(0) # defines a function print_a_line, which prints a value passed in the function # call and then a line read from the file's current position, keeping the new # line character intact def print_a_line(line_count, f): print line_count, f.readline() # opens a file given in the initial argv and sets it to a current_file variable current_file = open(input_file) # prints a line print "First, let's print the whole file:\n" # calls the print_all function and passes current_file print_all(current_file) # prints a line print "Now, let's rewind, kind of like a tape." # calls the rewind function and passes current_file rewind(current_file) # prints a line print "Let's print three lines:" # names and sets the current_line variable current_line = 1 # calls the print_a_line function and passes current_line and current_file print_a_line(current_line, current_file) # resets the current_line variable (iterates) current_line += 1 # calls the print_a_line function and passes current_line and current_file print_a_line(current_line, current_file) # iterates the current_line variable current_line += 1 # calls the print_a_line function and passes current_line and current_file print_a_line(current_line, current_file)
true
c1a524d57adab1f93d3e7c7264e74e99238803f2
najibelkihel/python-crash-course
/Chapter 4 Working with Lists - Lessons/magicians.py
1,081
4.59375
5
players = ['magic', 'lebron', 'kobe'] # use of for LOOP to apply printing to each player within player variable. for player in players: print(player) # for LOOP has been defined, and each item from the 'players' loop has been # stored in a new variable called 'player'. # for every player in the players list # printout each name in the players list. # when naming the for LOOP, it's best to use a name that represents a single # item in the list. e.g. for player in players. for dog in dogs etc. for player in players: print('Dear ' + player.title() + ', you\'ve been invited to our dinner') # When creating a loop, any indented line under the loop is considered part # of the loop. Multiple operations can thus be executed with one loop. for player in players: print('Dear ' + player.title() + ', you\'ve been invited to our dinner') print('Looking forward to having you with us, ' + player.title() + '.') # if the next operation within the loop is NOT indented, it will only be # applied to the last item on the list (in the e.g. above: to Kobe only)
true
5f85b795aa9102b6cc0b2ccb8a3c4711004cad78
najibelkihel/python-crash-course
/Chapter 5 If Statements - Lessons/toppings.py
1,763
4.3125
4
# Chapter 5, 'Checking for inequality', p.78 requested_topping = 'mushrooms' if requested_topping != 'anchovies': print('Hold the anchovies!') # Above: the if statement is asking if requested_topping is NOT equal to # 'anchovies', then the string 'Hold the anchovies!' should be printed. # Because the requested_topping variable is set as 'mushrooms' (thus not # 'anchovies'), the string 'Hold the anchovies!' is printed. mo_number = 42 question = 'What was Mariano Rivera\'s jersey number?' print(question) answer = 24 if answer != 42: print('\nThis is not the correct answer. Please try again!') # Same as above but comparing answer to Rivera's number using the variables if answer != mo_number: print('\nThis is not the correct answer. Please try again!') else: print('\nWell done!') # Numerical comparisons: age = 18 if age >= 16: print('You can purchase that game.') else: print('You\'re too young to purchase that game.') # Checking multiple conditions using and. age = 19 country = ' Canada ' country = country.lower().strip() if (age >= 18) and (country == 'united states'): print('You are eligible to play in the League.') else: print('You are not eligible to play in the League.') # Checking if value is in list with 'in'. usernames = ['john', 'julie', 'emily', 'ian'] proposed_username = 'irene' if proposed_username in usernames: print('\nThis username is already taken.') else: print('\nThis username is availabe!') # Checking if value is NOT in list with 'not in'. banned_usernames = ['john17', 'julie8', '3mily', 'ian77'] login_username = 'irene17' if login_username not in banned_usernames: print('\nWelcome back to our forums!') else: print('\nYou have been banned from our forums.')
true
68554c29ec432067bca62a6c2913ce163e4c0d15
najibelkihel/python-crash-course
/Chapter 5 If Statements - Lessons/toppings2.py
1,770
4.4375
4
# Using if statements with lists, p.89 requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print('Adding ' + requested_topping + '!') print('\nFinished making your pizza!') # for requested_topping in requested_toppings: if requested_topping == 'green peppers': print('\nSorry we\'re out of green peppers right now.') else: print('\nAdding ' + requested_topping + '!') print('\nFinished making your pizza!') # Code above: ln.13 = these lines are inserted to inform that 'green peppers' # are not available should green peppers be a requested topping (which it is). requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print('\nAdding ' + requested_topping + '!') print('\nFinished making your pizza!') else: print('\nAre you sure you want a plain pizza?') # The code above checks first (ln.26) if the list is empty or not. If the list # contains at least one item, Python assumes the statement as True (triggering # the following operations ln.27-29). If list is empty, Python assumes the # statement as False and jumps to else statement ln.30. available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['french fries', 'mushrooms', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print('\nAdding ' + requested_topping + '.') # True else: print('\nSorry we don\'t have ' + requested_topping + '.') # False print('\nFinished making your pizza') # The code above checks that items in requested_toppings are part of # available_toppings.
true
9e736ad8cc2847d518cd7afd9b0d170345e89df8
najibelkihel/python-crash-course
/Chapter 8 Functions - Lessons/person.py
981
4.25
4
# Returning a dictionary p.144 def build_person(first_name, last_name, age=''): """return a dictionary of information about a person""" person = {'first': first_name, 'last': last_name, } if age: person['age'] = age return person athlete = build_person('lebron', 'james') print(athlete) # Code above: this function actually creates a dictionary based on the # input information at ln.14. # ln.14: even though we've defined a dictionary ln.6, it is only for the sake # of the function definition. We still have to define a dictionary on ln.14 to # store the information. # IMPORTANT you can not assign a method to (e.g. .title()) to person at ln.11 # because it is a dictionary. To be able to use a method, one has to define # the key-value pair to which the method will be applied (e.g. person['last']) # ln.9: we introduce that condition should the user add his/her age, then we'd # create another key-value pair with age.
true
a9700460ba4ae908e41039b424b0a9bd3c0635bb
najibelkihel/python-crash-course
/Chapter 8 Functions - Exercises/sandwiches.py
1,499
4.15625
4
# Exercises p.155 # 8-12 def make_sandwich(*items): """Creates a list of items to be included in a sandwich""" print("Here are the ingredients that you've selected for your sandwich:") for item in items: print("\t- " + item.title().strip()) make_sandwich('tomato', 'cucumber', 'mayonnaise', 'chicken') make_sandwich('tuna', 'tomato sauce', 'prawn', 'cucumber') # 8-13 def make_profile(first, last, **user_info): """Creates a profile that accepts user generated data and put it in a dictionary""" profile = {} profile['first name'] = first profile['last name'] = last for key, value in user_info.items(): profile[key] = value return profile build_profile = make_profile('kobe', 'bryant', place_of_birth='Philadelphia', team='los angeles lakers', draft_year=1996) print(build_profile) # 8-14 def build_car(manufacturer, model, **options): """Creates a profile for a car with user input for options stored in dictionary""" car_profile = {} car_profile['manufacturer'] = manufacturer car_profile['model'] = model for key, value in options.items(): car_profile[key] = value return car_profile make_car = build_car('nissan', 'gtr', year=2018, color='black') print(make_car) print("\nYou've picked a " + make_car['manufacturer'].title() + " " + make_car['model'].upper() + ", year " + str(make_car['year']) + ", color " + make_car['color'].title() + ".")
true
8813e1a302ddf207ab90febfe14525db900d7b87
devopstasks/PythonScripting
/5-Data Structures of Python/25-Dictionaries.py
1,161
4.1875
4
''' =================================== Print the method names of Dictionary: print(dir({})) python2: Dictionary is un-ordered python3: Dictionary is ordered =================================== my_dict={} print(my_dict,type(my_dict)) print(bool(my_dict)) ''' ''' my_dict={"fruit":"apple","animal":"tiger",3:"abc","hhh":8} print(my_dict) print(my_dict["animal"]) print(my_dict.get(3)) #print(my_dict["ppp"]) print(my_dict.get("ppp")) print(dir({})) print(my_dict) my_dict.clear() print(my_dict) ''' ''' my_dict={"fruit":"apple","animal":"tiger",3:"abc","hhh":8} my_dict["three"]=3 print(my_dict) my_dict["three"]=66 print(my_dict) print(my_dict.items()) print(my_dict.keys()) print(my_dict.values()) my_new_dict=my_dict print(id(my_dict),id(my_new_dict)) x=my_dict.copy() print(id(x)) ''' ''' my_dict={"fruit":"apple","animal":"tiger",3:"abc","hhh":8} print(my_dict) my_new_dict={"four":4} my_dict.update(my_new_dict) print(my_dict) my_dict.pop("hhh") print(my_dict) remove_item=my_dict.popitem() print(remove_item) print(my_dict) ''' ''' my_keys=['a','e','i','o','u'] new_dict=dict.fromkeys(my_keys) print(new_dict) new_dict['a']="hello" print(new_dict) '''
false
64d6a779e986580cf41e7efcf7b57e26c8041ed1
devopstasks/PythonScripting
/5-Data Structures of Python/24-Tuples.py
552
4.4375
4
''' =========================== Strings and Tuples are immutable Tuple operations: dir((2,3)) Print the method names of Tuples: print(dir(())) =========================== ''' my_empty=() my_tuple=(2,7,[4,9,3],5) ''' print(bool(my_empty)) print(bool(my_tuple)) print(my_tuple) print(my_tuple[1]) print(my_tuple[2]) print(my_tuple[2][1]) ''' ''' my_tuple[1]=10 ''' ''' print(my_tuple) print(my_tuple[:]) print(my_tuple[0:]) print(my_tuple[1:]) #print(dir((2,3))) ''' ''' x=5, print(x,type(x)) y=5,2,8 print(y,type(y)) z=5,2,8,"gj" print(z,type(z)) '''
false
33841596590431b3ef442ced977d4c755d95dc08
devopstasks/PythonScripting
/11-Loops - for and while loops with break, continue and pass/46-Practice-Read-a-path-and-check-if-given-path-is-a-file-or-a-directory.py
422
4.28125
4
''' ====================== Read a path and check if given path is a file or directory ======================= ''' import os path=input("Enter your path: ") if os.path.exists(path): print(f'Given path: {path} is a valid path') if os.path.isfile(path): print(" and it is a file path") else: print(" and it is a directory path") else: print(f'Given path: {path} is not existing on this host')
true
5491ddab91157c08bd1a3cd538ce271ab337681a
devopstasks/PythonScripting
/5-Data Structures of Python/23-Lists.py
1,217
4.40625
4
''' =================== Lists are mutable Strings are immutable Print the method names of Lists: print(dir([])) ================== my_list=[] my_list=[2,8,3,"python",7.2,] bool(empty_list)==>False bool(non_empty_list)==>True my_list=[2,8,3,"python",7.2,] print(my_list,type(my_list)) print(my_list[0]) print(my_list[3]) print(my_list[-1]) print(my_list[3][1]) print(my_list) print(my_list[:]) print(my_list[0:]) my_list[0]=25 print(my_list) ''' ''' my_list=[3,2,7,5,9,2,1,2] print(my_list) print(my_list.index(9)) #print(my_list.index(6)) print(my_list.count(2)) print(my_list.count(6)) my_list.clear() print(my_list) ''' ''' my_list=[3,2,7,5,9,2,1,2] my_new_list=my_list my_one_list=my_list.copy() print(id(my_list),id(my_new_list)) print(id(my_one_list)) ''' my_list=[3,2,7,5,9,2,1,2] print(my_list) my_list.append(40) print(my_list) my_list.insert(1,56) print(my_list) my_new_list=[55,66] my_list.append(50) print(my_list) my_list.append(my_new_list) print(my_list) my_list.extend(my_new_list) print(my_list) my_list.remove([55,66]) print(my_list) my_list.pop() print(my_list) my_list.pop(0) print(my_list) my_list.reverse() print(my_list) my_list.sort() print(my_list) my_list.sort(reverse=True) print(my_list)
false
8426de85b92caa2223c5d5087aa1807a39b1577d
devopstasks/PythonScripting
/7-Conditional statements/32-Introduction-to-conditional-statements-simple-if-condition.py
897
4.28125
4
''' ================================== if is called simple conditional statement. Used to control the execution of set of lines or block of code or one line if expression: statement1 statement2 ================================== ''' ''' import os t_w=os.get_terminal_size().columns given_str=input("Enter your string: ") user_cnf=input("Do you want to align your text: Say yes or no?") if user_cnf="yes": print(given_str.center(t_w).title()) print(given_str.ljust(t_w).title()) print(given_str.rjust(t_w).title()) ''' ''' user_str=input("Enter your string: ") user_cnf=input("Do you want to convert your text into lowercase: Say yes or no?") if user_cnf="yes": print(user_str.lower()) ''' ''' list_of_names=["Sam","Peter","John","Raghu"] your_name=input("Enter your name: ") if your_name in list_of_names: print("Congratulations!!Your name exists in our list.") '''
true
3a1e4dc2107c16d005b6e188b45ffbee48018c54
wangjun1998a/pythonWorkSpace
/2018-12-1/函数的参数.py
1,217
4.1875
4
# 定义函数的时候,我们把参数的名字和位置确定下来,函数的接口定义就完成了。 # 对于函数的调用者来说,只需要知道如何传递正确的参数,以及函数将返回什么样的值就够了, # 函数内部的复杂逻辑被封装起来,调用者无需了解。 # # Python的函数定义非常简单,但灵活度却非常大。除了正常定义的必选参数外, # 还可以使用默认参数、可变参数和关键字参数,使得函数定义出来的接口, # 不但能处理复杂的参数,还可以简化调用者的代码 # 我们先写一个计算x2的函数 def power(x): return x * x # 现在,如果我们要计算x3怎么办?可以再定义一个power3函数, # 但是如果要计算x4、x5……怎么办?我们不可能定义无限多个函数。 # # 你也许想到了,可以把power(x)修改为power(x, n),用来计算xn,说干就干: def powerN(x, n=2): # 默认参数就排上用场了。由于我们经常计算x2,所以,完全可以把第二个参数n的默认值设定为2 s = 1 while (n > 0): n = n - 1 s = s * x return s print(powerN(5), powerN(5, 3), power(5), sep='\n')
false
16f61816cb29366d110add2564d808c3c5a29fea
muthazhagu/simpleETL
/randomdates.py
2,622
4.25
4
from datetime import date import random def generate_random_dates(startyear = 1900, startmonth = 1, startday = 1, endyear = 2013, endmonth = 12, endday = 31, today = True, numberofdates = 1): """ Method returns a list of n dates between a specified start, and end date. n corresponds to the numberofdates named parameter. Dates are in the yyyy-mm-dd format. By default it returns one random date between 1900-01-01 and today's date. If today is set to False, it returns a date between 1900-01-01 and a specific end date. Returned dates are uniformly distributed between the start and end dates. Throws ValueError if date initialization is incorrect. """ try: newdatelist = [] if numberofdates < 1: numberofdates = 1 #always returns one date numberofdates = int(numberofdates) #prevents TypeError in case of fractional values startdate = date(startyear, startmonth, startday) startdateordinal = startdate.toordinal() if today: enddate = date.today() enddateordinal = enddate.toordinal() else: enddate = date(endyear, endmonth, endday) enddateordinal = enddate.toordinal() ## print "Start date, and ordinal:", startdate, startdateordinal ## print "End date, and ordinal:", enddate, enddateordinal ## print "Generating %s random dates" % numberofdates for i in range(numberofdates): newdateordinal = random.randrange(startdateordinal, enddateordinal) newdate = date.fromordinal(newdateordinal) newdatelist.append(newdate) print "Date generation completed!" return newdatelist except ValueError as e: print "Incorrect date component given." print "Start date: %s, %s, %s, End date: %s, %s, %s is not valid." % \ (startyear, startmonth, startday, endyear, endmonth, endday) ##Uncomment lines below for testing the above method. ##print generate_random_dates(numberofdates = 10) #must generate 10 dates between 1900-01-01, and today. ##print generate_random_dates(numberofdates = 0.5) #must generate 1 date between 1900-01-01, and today. ##print generate_random_dates(numberofdates = -1) #must generate 1 date between 1900-01-01, and today. ##print generate_random_dates(numberofdates = 10, today = False) #must generate 10 dates between 1900-01-01, and 2013-12-31. ##print generate_random_dates(numberofdates = 10, startday = 40) #ValueError exception must be handled.
true
701de8c100f4b6f5efd602d8d68ea154af834f1d
SRSJA18/assignment-1-JaedynH99
/Problem3/repeating_lyrics.py
1,092
4.3125
4
"""Assignment 1: Problem 3 Extension: Repeating Lyrics""" ''' Many songs use repetition. We can use variables to manage that repetition when printing out the lyrics. Here is the chorus for Rick Astley's 'Never Gonna Give You Up' Never gonna give you up Never gonna let you down Never gonna run around and desert you Never gonna make you cry Never gonna say goodbye Never gonna tell a lie and hurt you Here is a program that outputs that chorus: ''' # TODO Option 1: Choose a song or chorus and write the program to output the lyrics using variables root = "Are we" a = "out of the woods yet" b = "in the clear yet" print(root, a) print(root, a) print(root, a) print(root, "out of the woods") print(root, b) print(root, b) # TODO Option 2a: If you know about Python lists you could simplify the program above using a loop. # TODO Option 2b: If you completed 2a you may have noticed that all but one line has the form # 'Never gonna _____ you ____' with the second blank optional. Can you rewrite the program # using variables? How will you handled 'say goodbye'?
true
75b331ff1f7643e3ab7e3c6ce6a4fdc38d8c9c4d
ARaj771/Python-Data-Structure-Practice
/02_weekday_name/weekday_name.py
597
4.375
4
def weekday_name(day_of_week): """Return name of weekday. >>> weekday_name(1) 'Sunday' >>> weekday_name(7) 'Saturday' For days not between 1 and 7, return None >>> weekday_name(9) >>> weekday_name(0) """ weekday_dict = { 1:"Monday", 2:"Tuesday", 3:"Wednesday", 4:"Thursday", 5:"Friday", 6: "Saturday", 7: "Sunday" } if(day_of_week < 1 or day_of_week > 7): return None else: return weekday_dict[day_of_week]
true
63026172deae959ec9d952658c4cbb199aaff0a1
shaz13/PyScripts
/word_end_finder.py
414
4.4375
4
import re # Replace this with your custom dictionary of words file = open('Urdu_words.txt', 'r') text = file.read().lower() file.close() text = re.sub('[^a-z\ \']+', " ", text) words = list(text.split()) string = str(raw_input ("Enter the last ending letters: ")) def EndsWithWordFinder(string): for word in words: if word[-len(string):] == string: print word EndsWithWordFinder(string)
true
b52e609ba07fca225b3bc37f21e33efdaf593662
ivaylospasov/small-budget
/main.py
1,912
4.15625
4
#!/usr/bin/env python3 __author__ = 'ivaylo spasov' from getBudget import currentBudget, path def main(): endProgram = 'no' totalBudget = currentBudget while endProgram == 'no': print('Welcome to the Personal Budget Program') print('Menu Selections: ') print('1-Add an Expense: ') print('2-Add Revenue: ') print('3-Check Budget Balance: ') print('4-Save progress') print('5-Exit without saving') choice = int(input('enter your selection: ')) if choice == 1: totalBudget = addExpense(totalBudget) elif choice == 2: totalBudget = addRevenue(totalBudget) elif choice == 3: print('Your balance is {0}'.format(totalBudget)) elif choice == 4: saveBudget(totalBudget) print('Thanks for saving your progress') elif choice == 5: endProgram = 'yes' print('Thank you for using "Small budget" program, Goodbye') else: print('Invalid selection, please try again') def addExpense(totalBudget): expense = float(input('Enter your expense amount: $')) timesPerMonth = int(input('How many times per month: ')) totalExpense = expense * timesPerMonth if totalBudget - totalExpense >= 0: totalBudget = totalBudget - totalExpense print ('The expenses was accepted, your remaining budget is: ${0}'.format(totalBudget)) return totalBudget else: print ('The expenses was rejected because the budget exceeded.') return totalBudget def addRevenue(totalBudget): revenue = float(input('Enter new monthly income: $')) totalBudget = totalBudget + revenue print('your new budget is: ${0}'.format(totalBudget)) return totalBudget def saveBudget(totalBudget): with open(path, 'w') as f: f.write(str(totalBudget)) f.close() main()
true
aa721dbd6178cf057d6f22f4367cc3f3a66a6d66
AnderSon277/Calculadora
/calcu.py
1,442
4.34375
4
def menu(): print("\n") print(" CALCULADORA BASICA\n") print(" Que operacion desea efectuar: \n") print(" 1.- Suma") print(" 2.- Resta") print(" 3.- Multipliacion") print(" 4.- Division") print(" 5.- Salir") op = int(input("Seleccione su opcion: ")) return (op) def suma(n1,n2): R = n1 + n2 return(R) def resta(n1,n2): R = n1 - n2 return(R) def multiplicacion(n1,n2): R = n1 * n2 return(R) def division(n1,n2): R = n1 / n2 return(R) n = menu() while (n>0 and n < 6): if(n==1): num1 = float(input("Ingrese un numero: ")) num2 = float(input("Ingrese otro numero: ")) print("El resutado de la Suma es:") print(suma(num1,num2)) n = menu() elif(n==2): num1 = float(input("Ingrese un numero: ")) num2 = float(input("Ingrese otro numero: ")) print("El resutado de la Resta es:") print(resta(num1,num2)) n = menu() elif(n==3): num1 = float(input("Ingrese un numero: ")) num2 = float(input("Ingrese otro numero: ")) print("El resultado de la Multiplicacion es:") print(multiplicacion(num1,num2)) n = menu() elif(n==4): num1 = float(input("Ingrese un numero: ")) num2 = float(input("Ingrese otro numero: ")) if(num2 == 0): print("Error: no se puede divir un numero para cero") n = menu() else: print("El resultado de la Division es:") print(division(num1,num2)) n = menu() elif(n==5): print("Gracias por utilizar nuestra CALCULADORA BASICA :D ") n=-1
false
36a0a0504f648c29f9bbd4c4b111cf7935508891
prajakta401/UdemyTraining
/venv/Lect_23_Missing Data.py
1,536
4.28125
4
#Lecture 23 Missing Data import numpy as np from pandas import Series,DataFrame import pandas as pd data = Series(['one','two','np.nan','four']) data.isnull() # returns True is particular index is null. data.dropna()#drops the row which has NaN values dataframe = DataFrame([[1,2,3],[np.nan,5,6],[7,np.nan,9],[np.nan,np.nan,np.nan]]) print(dataframe)# data frame with several null values clean_dframe = dataframe.dropna()# any row with nulls will be dropped print(clean_dframe) x= dataframe.dropna(how= 'all')# drops only those rows which have all the values = Nulll print(x) y = dataframe.dropna(axis=1)#drops the column which has one or more NaN print(y) npn = np.nan # create a NaN variable dframe2 = DataFrame([[1,2,3,npn],[2,npn,5,6],[npn,7,npn,9],[1,npn,npn,npn]])# DF with many NaN print(dframe2) a= dframe2.dropna(thresh=3)# if we want data rows who have atleast 2 data points. Threshold print(a) c= dataframe.fillna(1)# fills the NaN with 1 in the dataframe ( temporary copy change) print(c) d= dframe2.fillna({0:'pop',1:'red',3:999})#fills column wise Nans with something else print(d) #permanatly filling NaN by something in a DataFrame dframe2.fillna(0,inplace=True) print(dframe2) #Lecture 24 Index Hierarchy from numpy.random import randn ser = Series(randn(6),index=[[1,1,1,2,2,2],['a','b','c','a','b','c']]) print(ser) print(ser.index) #check number of levels of index print(ser[1]) ser[:,'a']# reads all the inxes and the values who have internal index 'a' dframe= ser.unstack()# create DF from series print(dframe)
true
6ff74e53b090bde4f3a66a99c13552724e1f053e
prajakta401/UdemyTraining
/venv/Lecture15_DataFrames.py
1,877
4.125
4
#Lecture 15: Data FRames import numpy as np # array handling import pandas as pd from pandas import Series , DataFrame import webbrowser # grab/scrape NFL data from website website='http://en.wikipedia.org/wiki/NFL_win-loss_records' webbrowser.open(website) #opens the url in nnew browser window #copy few 10 rows and all columns on the website table on to the clipboard nfl_frame = pd.read_clipboard() # read those 10 rows and column headers print(nfl_frame) print(nfl_frame.columns.values)# read column names # print(nfl_frame.values)# read row values print(nfl_frame.Team)# read particular column eg: "Team" print(nfl_frame.GP) #print(nfl_frame['First NFL Season']) # read colum whihc has multiword name print(DataFrame(nfl_frame,columns=['Rank','Team','Won']))# fetch only specific columns. print(DataFrame(nfl_frame,columns=['Rank','Team','Won','Stadium']))# Stadium column does not exist , but dataframe creates new column on its own. # Retrieve rows for Data Frame print(nfl_frame.head())# read data set) print(nfl_frame.head(2))# read first 2 rows) print(nfl_frame.tail()) # read last row print(nfl_frame.tail(4)) # read last 4 rows # nfl_frame.ix[3]# read by index 3rd index nfl_frame['Stadium']= "Levis Stadium" print(nfl_frame) nfl_frame['Stadium']=np.arange(20) print(nfl_frame) print(len(nfl_frame.values)) #Adding series to a data Frame stadiums = Series(["Levis Stadium","At&T stadium"],index =[19,0])#fill 19th index by LEvis and )th index by At&t print(stadiums) nfl_frame['Stadium']= stadiums #assign stadium series to stadium column print(nfl_frame) del nfl_frame['Stadium'] #delete stadium column #add dictionary to Dataframe data = {'City':['SF','LA','NYC'],'Population':[83,38,84]} city_frame = DataFrame(data) print(city_frame) #lecture 16 Index Objects my_ser = Series([1,2,3,4],index=['A','B','C','D']) my_index = my_ser.index print(my_index)
true
0e0f221bd037f809f317a88589bc0ee4804326a4
deborabr21/Python
/PartI_Introduction_To_Programming/Assignment_2_Guess_a_number.py
668
4.15625
4
#Write a program with an infinite loop and a list of numbers. #Each time through the loop the program#should ask the user to guess a number or type q to quit. #If they type q the program should end. Otherwise it should tell them wether or not they successfully #guessed a number in the list or not. numbers = [1,3,5,7,9,11,15,18,21,23,34,35,38,41,43,47,49] n=0 while True: print("Type q to quit") answer = input("Guess a number between 1 a 50: ") if answer == "q": break if int(answer) in numbers: print("Number " + answer + " was found! Congrats!") break else: print("Number " + answer + " was not found!Try again!") continue n +=1
true
ac66422ab45692bd991bf4fcbac5480fce015094
Sahana012/Python-Code
/countwords.py
320
4.1875
4
introstring = input("Enter your introduction: ") wordcount = 1 charcount = 0 for i in introstring: charcount = charcount + 1 if(i == ' '): wordcount = wordcount + 1 print("Number of word(s) in the string: ") print(wordcount) print("Number of characters(s) in the string: ") print(charcount)
true
318407d0b315c828efdd0c8b171b2a3a1106abb8
Psingh12354/PythonNotes-Internshalla
/code/IF_ELSE.py
343
4.125
4
price=int(input("Enter the price : ")) quantity=int(input("Enter quantity : ")) amount=price*quantity if amount>1000: print("You got a discount of 10%") discount=amount*10/100 amount-=discount else: print("You got a discount of 5%") discount=amount*5/100 amount-=discount print("Total amount is : ",amount)
true
814e5f1bcf0948ad96ca6acf2fb8191ed4193284
matthewmckenna/advent2018
/aoc_utils.py
689
4.125
4
""" utility functions for Advent of Code 2018. """ from typing import Iterator, List def txt_to_numbers(fname: str) -> List[int]: """read `fname` and return a list of numbers""" with open(fname, 'rt') as f: data = [int(number) for number in f] return data def comma_separated_str_to_int_iterator(s: str) -> Iterator[int]: """turn a comma separated string of numbers into an iterable of ints""" for number in s.replace(',', '').split(): yield int(number) def read_strings_from_file(fname: str) -> Iterator[str]: """read a file and yield strings from it""" with open(fname, 'rt') as f: for line in f: yield line.strip()
true
fc1336851b836312139a08eca6860207c1439b75
kehkok/koodaus
/simple_tutorial_py/tut_01_factorial/factorial1.py
2,319
4.125
4
""" This module consists of basic factorial, exponential factorial and taylor series of sin functions """ import math def factorial(n): """Compute basic factorial function Parameters ---------- n : integer Specifies the number to be factorial Returns ------- Float value of the product for all n """ if n == 0: return 1.0 else: return float(n) * factorial(n-1) def exp_factorial(n): """Compute exponential of factorial Parameters ---------- n : integer Specifies the number to be exponentially factorial Returns ------- float value of the product for all n """ return [1.0/factorial(i) for i in range(n)] def sin_factorial(n): """Compute taylor series of sin for a list Parameters ---------- n : integer Specifies the number to be taylor of sin Returns ------- list of float values """ res = [] for i in range(n): if i % 2 == 1: res.append((-1)**((i-1)/2)/float(factorial(i))) else: res.append(0.0) return res def func_cos(x, n): """Estimate the value of cos(x) using a Taylor Series Parameters ---------- x : integer Specifies the number of x value of cos function n : integer Specifies the number to be taylor of sin Returns ------- Estimate of factorial of n for cox(x) value """ cos_approx = 0 for i in range(n): coef = (-1)**i num = x**(2*i) denom = math.factorial(2*i) cos_approx += coef * (num/denom) return cos_approx def benchmark(): """Benchmark function Returns ------- None """ sum_ef = sum(exp_factorial(500)) print("Sum of exponential factorial is {:.6f}.".format(sum_ef)) sum_sin = sum(sin_factorial(500)) print("Sum of sin factorial is {:.6f}.".format(sum_sin)) print("Estimated of cos(x) value is {:.3f}".format(func_cos(5, 3))) if __name__ == '__main__': """Main function """ print ("Start...") benchmark() print ("End...")
true
5503c5617b63695175b24478a2e9cba0d98156e6
felpssc/Python-Desafios
/AV1 - PYTHON/questao 02.py
689
4.125
4
for n in range(5): substantivo_singular = input('Informe um substantivo no singular: ') substantivo_plural = input('Informe um substantivo no plural: ') adjetivo = input('Informe um adjetivo: ') lugar = input('Informe um lugar: ') verbo = input('Informe um verbo (ex: voar): ') print(f'Era uma vez um(a) {substantivo_singular} que gostava de {verbo}') print('mas sempre que o fazia, começavam a reclamar,') print(f'suas {substantivo_plural} o ajudavam a continuar') print(f'porém sempre que o(a) {substantivo_singular} ficava {adjetivo}') print(f'ele ia para {lugar} chorar.') print(f'Mesmo com todos criticando ele não desistia de {verbo}.')
false
7dc6191710fd5cb5fb54414ee212c4bb3946a3cc
camirmas/ctci
/ctci/p1_8.py
1,940
4.125
4
""" Write an algorithm such that if an element in an NxN matrix is 0, its entire row and column are set to 0. """ # def zero_matrix(matrix: list): # "Naive, takes O(N^2) space and O(N^3) time" # zeroed = {} # for r, row in enumerate(matrix): # for c, value in enumerate(row): # if (r, c) not in zeroed and value == 0: # # row # for c2, _ in enumerate(row): # zeroed[(r, c2)] = True # row[c2] = 0 # # column # for r2, row2 in enumerate(matrix): # zeroed[(r2, c)] = True # row2[c] = 0 def zero_matrix(matrix: list): """Optimal, takes O(1) space and O(N^2) time.""" row_has_zero = False col_has_zero = False # Check if the first row has a zero for c in matrix[0]: if c == 0: row_has_zero = True break # Check if the first col has a zero for r in matrix: if r[0] == 0: col_has_zero = True break # Check for zeros in the rest of the array for r in range(1, len(matrix)): for c in range(1, len(matrix[0])): if c == 0: matrix[r][0] = 0 matrix[0][c] = 0 # Nullify rows based on values in first column for i in range(1, len(matrix)): if matrix[i][0] == 0: nullify_row(matrix, i) # Nullify columns based on values in first row for j in range(1, len(matrix)): if matrix[0][j] == 0: nullify_column(matrix, j) # Nullify first row if row_has_zero: nullify_row(matrix, 0) # Nullify first col if col_has_zero: nullify_column(matrix, 0) def nullify_column(matrix: list, col: int): for row in matrix: row[col] = 0 def nullify_row(matrix: list, row: int): for i in range(len(matrix)): matrix[row][i] = 0
true
9a0a8174bcb51364c9d4e49b642d27e3b01e3e94
claashk/python-startkladde
/pysk/utils/ascii.py
655
4.3125
4
# -*- coding: utf-8 -*- REPLACEMENTS={ "ä" : "ae", "Ä" : "Ae", "ö" : "oe", "Ö" : "Oe", "ü" : "ue", "Ü" : "Ue", "'" : "" } def toAscii(string): """Convert string to ASCII string Replaces all non-ASCII characters by suitable replacements Arguments: string: input string Return: string with all non-ASCII characters replaced """ retval= string for letter, replacement in REPLACEMENTS.iteritems(): retval= retval.replace(letter, replacement) return retval
true
07eed30ca73ba360e51a4baf2188cccc44ffa2f6
JayBee12/ITBadgePDT22021
/Example4.py
1,172
4.65625
5
# We use def to define the structure of a function, functions can be created to expect 'arguments' which are data we provide to the function to do something with # The examples below are 'pass by value' arguments in that the value is passed to the function rather than a reference or pointer to the variable itself #This function has no arguments and simply calls the print funtion to print some text to the console def noArguments(): print("The function with no arguments was called") #This function takes two variables adds them together and then prints them using the print function def hasArguments(a, b): print(a + b) # This function has a return value meaning that when the function is called it will 'return' whatever is specified, in this case it returns the sum of the # values of the two variables passed to it def hasReturns(a, b): return a + b #function call noArguments() # Function call with arguments hasArguments(6, 4) # What do think this function will do # hasArguments() # Function wtih return to variable x = hasReturns(3, 3) # Print returned data in variable print(x) # Print return value directly print(hasReturns(7, 7))
true
206e8cd5072d54300e968698cd903acdcce3e4d2
jiaoxiaoyou/study
/01-Python/15-test_python/答案/test_07.py
2,436
4.125
4
# @Author : 强小林 # @CreateDate : 2020/5/13 17:54 # @Description : # @UpdateAuthor : # @LastUpdateTime : # @UpdateDescription : """ python打卡第七天 1、利用random函数生成随机整数,从1-9取出来。然后输入一个数字,来猜: 如果大于,则打印大于随机数;小了,则打印小于随机数;如果相等,则打印等于随机数。 2、使用循环和条件语句完成剪刀石头布游戏,提示用户输入要出的拳 :石头(1)/剪刀(2)/布(3)/退出(4) 电脑随机出拳比较胜负,显示用户胜、负还是平局。运行如下图所示: """ # 第1题:可优化项:按需输入--利用正则 re.match(r'^\d$', num_me) # 方法1:猜一次 import random print("----------第一题:方法1----------") num = random.randint(1, 9) num_me = int(input("请输入一个数字(猜一猜):")) if num > num_me: print("对不起,您猜小了") elif num < num_me: print("对不起,您猜大了") else: print("恭喜您猜对了") # 方法2:循环猜,直至猜中 print("----------第一题:方法2----------") num = random.randint(1, 9) while True: num_me = int(input("请输入一个数字(猜一猜):")) if num > num_me: print("对不起,您猜小了") elif num < num_me: print("对不起,您猜大了") else: print("恭喜您猜对了") break # 第2题:可优化项:按需输入--利用正则 re.match(r'^[1-4]{1}$', num_me) # 规则梳理:石头>剪刀、剪刀>布、布>石头 # 规则梳理:1>2、2>3、3>1 print("----------第二题----------") print("------剪刀石头布游戏开始------\n请按下面提示出拳:\n石头【1】剪刀【2】布【3】退出【4】") rule = {1: "石头", 2: "剪刀", 3: "布", 4: "退出"} while True: robot = random.randint(1, 3) user = int(input("请输入你的选项:")) if (robot == 1 and user == 3) or (robot == 3 and user == 2) or (robot == 2 and user == 1): print("您的出拳为:{},电脑出拳为:{},您胜利了".format(rule[user], rule[robot])) elif robot == user: print("您的出拳为:{},电脑出拳为:{},平局".format(rule[user], rule[robot])) elif user == 4: print("游戏结束") break else: print("您的出拳为:{},电脑出拳为:{},您输了".format(rule[user], rule[robot]))
false
0b2627d91942607f1d199c5b30c3a86f81a1a39e
adarsh-tyagi/codes
/Coding_Problem_Solution_21.py
833
4.1875
4
# asked by Google # Given two singly linked lists that intersect at some point, find the intersecting node. # The lists are non-cyclical. # For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, # return the node with value 8. # In this example,assume nodes with the same value are the exact same node objects. # Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. def intersection(a,b): i=0 while a[i]!=b[i]: if a[i]==None: a=b elif b[i]==None: b=a else: i=i+1 return a[i] a=[int(x) for x in input("enter first list: ").split()] b=[int(x) for x in input("enter the second list: ").split()] a.append(None) b.append(None) print("intersection is: {0}".format(intersection(a,b)))
true
0385f450453320dd2ce5204afa4df1896a2c0e52
adarsh-tyagi/codes
/Coding_Problem_Solution_30.py
1,054
4.375
4
# asked by Facebook # Given a string of round, curly, and square open and closing brackets, # return whether the brackets are balanced (well-formed). # For example, given the string "([])[]({})", you should return true. # Given the string "([)]" or "((()", you should return false. input_string="([])[]{()}" def balanced(string): open_list=['(','[','{'] closed_list=[')',']','}'] dictionary={')':'(',']':'[','}':'{'} stack=[] for i in string: if i in open_list: stack.append(i) elif i in closed_list: if match(stack,i,dictionary): stack.pop() else: return False else: raise ValueError("invalid string") if not stack: return True else: return False def match(stack,i,dic): if not stack: return False else: if stack[-1]==dic[i]: return True else: return False print(balanced(input_string))
true
2f65b8ab45a01075a6bfd5d96f82fac776e1cb23
adarsh-tyagi/codes
/Coding_Problem_Solution_23.py
992
4.1875
4
# asked by Microsoft # Given a dictionary of words and a string made up of those words (no spaces), # return the original sentence in a list. If there is more than one possible reconstruction, return any of them. # If there is no possible reconstruction, then return null. # For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", # you should return ['the', 'quick', 'brown', 'fox']. # Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", # return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. string_list=[str(x) for x in input("enter the list of words: ").split()] string=input("enter the string: ") output_list=[] for i in range(len(string)): for j in range(i,len(string)+1): s=string[i:j] if s in string_list: output_list.append(s) break else: continue print(output_list)
true
246443dfb184b9d7536754b734117ab7880c15fd
adarsh-tyagi/codes
/Coding_Problem_Solution_16.py
492
4.3125
4
# asked by Google # From a given string return the first recurring character of the string. # for e.g. if string id "ABCDBA" then return "B" # if string is "ABCD" return None because no character is recurring. s=input("enter the string: ") def First_Rec_Char(s): char_list=[] for i in s: if i in char_list: return i else: char_list.append(i) return None print("first recurring character is {0}".format(First_Rec_Char(s)))
true
5b570168559708075d967909b9d7130ac454da75
emil45/computer-science-algorithms
/algorithmic-questions/majority_element.py
553
4.15625
4
from collections import defaultdict def majority_element(l): """ Given an array of size n, find the majority element. The majority element is the element that appears more than floor(n/2) times. You may assume that the array is non-empty and the majority element always exist in the array. """ a = defaultdict(int) majority_elem = 0 for i in l: a[i] += 1 if a[i] > len(l) / 2: majority_elem = i return majority_elem if __name__ == '__main__': print(majority_element([2, 1, 2]))
true
5dc0333d3f75da76eb9d828521f6385335e311bb
venkyms/python-workspace
/scripts/Tag-counter.py
621
4.3125
4
"""Write a function, `tag_count`, that takes as its argument a list of strings. It should return a count of how many of those strings are XML tags. You can tell if a string is an XML tag if it begins with a left angle bracket "<" and ends with a right angle bracket ">". """ def tag_count(html_list): count1 = 0 for element in html_list: if element[0] == '<' and element[-1] == '>': count1 += 1 return count1 # Test for the tag_count function: list1 = ['<greeting>', 'Hello World!', '</greeting>'] count = tag_count(list1) print("Expected result: 2, Actual result: {}".format(count))
true
88f8ee6fde8063fe4241094410a119c289207ab9
venkyms/python-workspace
/scripts/Median.py
698
4.125
4
def median(numbers): numbers.sort() #The sort method sorts a list directly, rather than returning a new sorted list middle_index = int(len(numbers)/2) if len(numbers) % 2 == 0: return (numbers[middle_index] + numbers[middle_index - 1]) / 2 else: return numbers[middle_index] test1 = median([1,2,3]) print("expected result: 2, actual result: {}".format(test1)) test2 = median([1,2,3,4]) print("expected result: 2.5, actual result: {}".format(test2)) test3 = median([53, 12, 65, 7, 420, 317, 88]) print("expected result: 65, actual result: {}".format(test3)) test4 = median([53, 12, 65, 7, 420, 317]) print("expected result: 65, actual result: {}".format(test4))
true
831487db53af4f9217a1f0a6e47ed45a184c003e
KimTanay7/py4e
/Excercise3_Conditional.py
698
4.21875
4
print ("**************************") print ("* Activity 3-Conditional *") print ("**************************") name = input("Name:") print ("Hello ",name, "!") print ("This program will print a grade relevant to your score") print (" Please enter score between 0.0 to 1.0") print ("--------------------------------") x= input ('Enter Score:') try: ival=float(x) or int(x) except: ival=-1 if ival > 0: grade=float(x) if grade < 0.6: print('F') elif grade < 0.7: print('D') elif grade < 0.8: print('C') elif grade < 0.9: print('B') elif grade <= 1.0: print('A') else: print('Invalid!') else: print('Invalid!')
true
611fdf2ab6ee60ea5d795455949c4be0bab5db63
Maryam-ask/Python_Tutorial
/File/Delete_a_File/delete_a_file.py
296
4.125
4
# Delete a file import os if os.path.exists("D:\Python_Home\Files\myfile_create.txt"): os.remove("D:\Python_Home\Files\myfile_create.txt") else: print("the file does not exist!") # delete a folder: os.rmdir("D:\Python_Home\Files\My new folder") # !!! You can only remove empty folders.
true
79029b3ed0e8129679df005edbf65bc1212887d6
Maryam-ask/Python_Tutorial
/Collections/Tuple/Tuples.py
1,223
4.5
4
tuple1 = ("apple", "banana", "cherry") print(tuple1) # ***************************************************************************** # Index numbers thistuple = ("apple", "banana", "cherry", "apple", "cherry") print("\n",thistuple) # ***************************************************************************** # Tuple Length: print("\nthistuple length is: ", len(thistuple)) # ***************************************************************************** # !!!! Create Tuple With One Item !!!! thistuple = ("apple",) # bayad entehaye an hatman comma bashad vaghti faghat yek meghdar darad print("first type: ", type(thistuple)) #NOT a tuple thistuple = ("apple") print("Second type:", type(thistuple)) # ***************************************************************************** # Tuple -Data types: tuple2 = ("apple", "banana", "cherry") tuple3 = (1, 5, 7, 9, 3) tuple4 = (True, False, False) # A tuple can contain different data types. tuple5 = ("abc", 34, True, 40, "male") # ***************************************************************************** # Tuple Constructor: tuple(): thistuple1 = tuple(("apple", "banana", "cherry")) # note the double round-brackets print("Tuple constructor: ", thistuple1)
false
382d56ce419ead7862cccbbf16b420da26c17d65
Maryam-ask/Python_Tutorial
/Function/Functions_Sololearn/Functional_Programming/Pure_functions.py
1,339
4.5625
5
""" Pure Functions: Functional programming seeks to use pure functions. Pure functions have no side effects, and return a value that depends only on their arguments. This is how functions in math work: for example, The cos(x) will, for the same value of x, always return the same result. Below are examples of pure and impure functions. """ # Pure Function: def pure_function(x, y): temp = x + 2 * y return temp / (2 * x + y) # iImpure Function: some_list = [] def impure(arg): some_list.append(arg) # The function above is not pure, because it changed the state of some_list. # ============================================================================================== """ Using pure functions has both advantages and disadvantages. Pure functions are: - easier to reason about and test. - more efficient. Once the function has been evaluated for an input, the result can be stored and referred to the next time the function of that input is needed, reducing the number of times the function is called. This is called memoization. - easier to run in parallel. The main disadvantage of using only pure functions is that they majorly complicate the otherwise simple task of I/O, since this appears to inherently require side effects. They can also be more difficult to write in some situations. """
true
01b6fc1147f53d6c3c9c0d7db16772ddc378f5ba
Maryam-ask/Python_Tutorial
/Collections/List/AccessListItems.py
1,168
4.40625
4
thislist = ["apple", "banana", "cherry"] print(thislist[1]) # ************************************************************ # Print the last item of the list thislist = ["apple", "banana", "cherry"] print(thislist[-1]) # ************************************************************ # Return the third, fourth, and fifth item. thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) # khaneye 2 niz dar an vojood darad. # ************************************************************ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4]) # az khoneye 0 ta 4 # ************************************************************ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:]) # ************************************************************ thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[-4:-1]) # ************************************************************ # Check if item Exists: thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")
false
7869e3b3f31dde7d7c1f7cff415a0dee1feb6b56
Maryam-ask/Python_Tutorial
/Exercises/__init__.py
465
4.1875
4
""" Sum of Consecutive Numbers: No one likes homework, but your math teacher has given you an assignment to find the sum of the first N numbers. Let’s save some time by creating a program to do the calculation for you! Take a number N as input and output the sum of all numbers from 1 to N (including N). Sample Input 100 Sample Output 5050 """ N = int(input()) #your code goes here all = list(range(1,N+1)) count = 0 for i in all: count += i print(count)
true
562c78f14b3483c4c1dcaeaf013f1412cc94bf88
Maryam-ask/Python_Tutorial
/Collections/Tuple/UpdateTuples.py
944
4.4375
4
# Change Tuple Values x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print("Change Tuple Values: ", x) # **************************************************************** # Add Items: thistuple1 = ("apple", "banana", "cherry") # Halate 1: z = list(thistuple1) z.append("orange") thistuple1 = tuple(z) print("Add Items: (Halate 1) ", thistuple1) # Halate 2: y = ("orange",) thistuple1 += y print("Add Items: (Halate 2) ", thistuple1) # **************************************************************** # Remove Items: thistuple2 = ("apple", "banana", "cherry") y = list(thistuple2) y.remove("apple") thistuple2 = tuple(y) print("Remove Items: (apple) ",thistuple2) # **************************************************************** # The del keyword can delete the tuple completely: thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) #this will raise an error because the tuple no longer exists
false
44cf49419a24a9838a0c42dfb1ef9478491cc7c8
Maryam-ask/Python_Tutorial
/Collections/Dictionary/Accessing_Items.py
1,044
4.25
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } # halate 1: x = thisdict["model"] print(x) # halate 2: estefade az methode get(): y = thisdict.get("model") print(y) # Get keys: # The keys() method will return a list of all the keys in the dictionary. key = thisdict.keys() print("List of keys are: ", key) # Get values: # The values() method will return a list of all the values in the dictionary. value = thisdict.values() print("list of values are: ", value) # Get items: # The items() method will return each item in a dictionary, as tuples in a list. items = thisdict.items() print("list of items are: ", items) # ************************************************************************ car = { "brand": "Ford", "model": "Mustang", "year": 1964 } carKeys = car.keys() print(carKeys) car["color"] = "White" print(carKeys) carValues = car.values() print(carValues) car["year"] = 2020 print(carValues) if "model" in car: print("yes, 'model' is one of the kes in the car dictionary.")
true
68329f8726017cbaac11286704ac41a23bc49740
Maryam-ask/Python_Tutorial
/Exercises/SearchEngine.py
581
4.28125
4
""" Search Engine: You’re working on a search engine. Watch your back Google! The given code takes a text and a word as input and passes them to a function called search(). The search() function should return "Word found" if the word is present in the text, or "Word not found", if it’s not. Sample Input "This is awesome" "awesome" Sample Output Word found """ def search(txt, wd): txtList = txt.split(" ") for x in txtList: if x == wd: return "Word found" return "Word not found" text = input() word = input() print(search(text, word))
true
823453c64a30e699e33631d62187948c115ddc64
Maryam-ask/Python_Tutorial
/Lambda/Lambda_SoloLearn/lambda_soloLearn.py
567
4.5625
5
def my_func(f, arg): return f(arg) my_func(lambda x: 2 * x * x, 5) # ******************************************* # function: def polynomial(x): return x ** 2 + 5 * x + 4 print(polynomial(-4)) # lambda: print((lambda x: x ** 2 + 5 * x + 4)(-4)) # ******************************************* # Lambda functions can be assigned to variables, and used like normal functions. double = lambda x: x * 2 print(double(7)) # ******************************************* # EXAMPLE: triple = lambda x: x * 3 add = lambda x, y: x + y print(add(triple(3), 4))
true
e29a4847b55c2cd7195dcf6cb55daf4acbcb5144
Maryam-ask/Python_Tutorial
/Boolean/BooleanPython.py
1,142
4.3125
4
# Boolean 2 meghdar ra barmigardanad -----> 1. True & 2. False # When you run a condition in an if statement, Python returns ----> True or False print(10 > 9) print(10 == 9) print(10 < 9) # ************************************************** print() a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") # ************************************************** # The bool() function allows you to evaluate any value, and give you True or False in return. print() # Evaluate a string and a number print(bool("Hello")) print(bool(15)) # ************************************************** print("Most Values are True") # The following will return True print(bool("abc")) print(bool(123)) print(bool(["apple", "cherry", "banana"])) # ************************************************** print() print("bool(False): " + bool(False)) print("bool(None): "+bool(None)) print("bool(0): "+bool(0)) print("bool(""): "+bool("")) print("bool(()): "+bool(())) print("bool([]): "+bool([])) print("bool({}): "+bool({})) # ************************************************** x = 200 print(isinstance(x,int))
true
f07f263f54ce47b98c5da02c53235b5ded4511af
alexandremerched/learning-python
/PythonExercicios/World 3/ex075.py
530
4.15625
4
numbers = int(input("Digite um número: ")), int(input("Digite outro número: ")), int( input("Digite outro número: ")), int(input("Digite o último número: ")) print( f"Você digitou os valores {numbers}\nO valor 9 apareceu {numbers.count(9)} vezes") if 3 in numbers: print(f"O valor 3 apareceu na {numbers.index(3)+1}° posição") else: print("O valor 3 não apareceu em nenhuma posição") print(f"Os valores pares digitados foram ", end='') for n in numbers: if n % 2 == 0: print(n, end=' ')
false
f43259151faa546e196e321fdb0387967a3cacda
alexandremerched/learning-python
/PythonExercicios/World 2/ex037.py
461
4.21875
4
num = int(input("Digite o número para ser convertido: ")) option = int(input("""Digite 1 para Binário. Digite 2 para Octal. Digite 3 para Hexadecimal. """)) if option == 1: print("O número em binário é igual a {}".format(bin(num)[2:])) elif option == 2: print("O número em octal é igual a {}".format(oct(num)[2:])) elif option == 3: print("O número em hexadecimal é igual a {}".format(hex(num)[2:])) else: print("Opção inválida.")
false
792055dda42ef02fc484ef3414846a44d576bffc
CAEL01/learningpython
/variables.py
1,235
4.28125
4
""" Learning to code Variables in Python (via Pirple.com) Using attributes such as Variables, Strings, Integers (positive numbers), Floats (decimals). These attributes define every value of what is to be printed on the computer screen: A text, a positive numeric value, and a decimal value. Using an artist with song and album as basis for learning variables. """ Artist = "Artist: Andy Grammer" Genre = "Genre: Pop" Song = "Song: I Found You" Album = "Album: Naive" Label = "Label: BigBeats Records" Release = "Release: 2019" Availability = "Availability: Spotify, YouTube Music, Deezer" """ I could just write the Integer itself in the three following definitions, however I chose to write everything as a string since I want to display the title of the integer as well. """ DurationInSeconds = "Duration in seconds: 138.6" DurationInMinutes = "Duration in minutes: 2.31" ListenerScore = "Listener rating: 4 out of 5" """ This is the code that will be printed (seen) on your screen - in the exact order as sorted/written below. """ print(Artist) print(Genre) print(Song) print(Album) print(Label) print(Release) print(Availability) print(DurationInSeconds) print(DurationInMinutes) print(ListenerScore) # Code written by Caroline Eliasson
true
0ef4536bf68225a6024c75e4ec831bab68c70910
joshuayun/python_edu
/week04/q04_baseball.py
1,102
4.125
4
""" 야구 게임 숫자 3개를 랜덤하게 생성 1~9 사의 수, 중복 X 3 9 4 사용자가 3개의 숫자를 입력하면 Strike : 숫자와 위치가 맞은 경우 Ball : 숫자만 맞은 경우 을 알려준다. 3 strike가 된 경우에만 맞았습니다. 게임을 종료 1. random 2. list 3. while문을 이용한 반복 4. 입력용 함수를 사용 """ # 랜덤하게 3개 숫자 뽑기 import random original_numbers = list(range(1,10)) numbers = random.sample(original_numbers, 3) while True: user_numbers = [] print("정답 숫자 3개를 입력하세요.") for _ in range(3): print("현재 입력된 수 ",user_numbers) number = input("숫자를 입력하세요 : ") user_numbers.append(int(number)) print("입력한 정답 ", user_numbers) strike,ball = 0,0 for index in range(3): if user_numbers[index] == numbers[index]: strike += 1 elif user_numbers[index] in numbers: ball += 1 print(f"{strike}S {ball}B") if strike == 3: print("정답입니다.") exit()
false
cfa15a47f62c7539d79c2b10db2abd7e97ee48e3
roorco/alphabetizer
/alphabetizer.py
854
4.53125
5
#!/usr/bin/env python2 #-*-coding:utf-8-*- # modificare per eliminare accenti def abcd(): print "\n-------------------" print "THE ALPHABETIZER 2014" print "by orobor" print "This is a very small program that sorts" print "the letter of your name in an alphabetical order." print "It is supposed to be a perfectly useless software" print "or a 'f-utility'. " print "It comes after Alighiero Boetti ideas" print "and it is distribuited under Creative Commons License." print "--------------------\n" print "Write here your name" name = raw_input('>') tupleList = [str(x.lower()) for x in name] tupleList.sort() #list[:] = [x[1] for x in tupleListn print "Your alphabetized name is:" #return [x[1] for x in tupleList] print ''.join(tupleList).replace(" ", "").capitalize() abcd()
true
078716f2ff82a6945ae80fd6353d7f72f30aba15
deep743/Python-Day-1-Project
/calculator.py
1,109
4.21875
4
while True: option = input("Enter add or subtract multiply divide percentage quit : ") if option == 'quit': break elif option == 'add': number1 = float(input("Enter first number: ")) number2 = float(input("Enter second number: ")) print(number1 + number2) elif option == 'subtract': number1 = float(input("Enter first number: ")) number2 = float(input("Enter second number: ")) print(number1 - number2) elif option == 'multiply': number1 = float(input("Enter first number: ")) number2 = float(input("Enter second number: ")) print(number1 * number2) elif option == 'divide': number1 = float(input("Enter first number: ")) number2 = float(input("Enter second number: ")) print(number1 / number2) elif option == 'percentage': number = float(input("Enter first number: ")) totalnumber = float(input("Enter total number: ")) p= ((number/100)*totalnumber) print("The percentage is= ",p,"%") else : print("Invalid Input") print("EXIT")
false
193d1d993358ab8addd8de6cca80abbabcb51b2e
natmayak/lesson_2
/if_age_hw_v.2.py
1,005
4.125
4
age = int(input("How old are you? ")) def ageist_function(age): if age <= 0: raise ValueError("You are in your parents' plans") elif 0 < age <= 6: print('Having fun at nursery') elif 6 < age <= 16: print('Wasting best years at school') elif 16 < age <= 21: print('Getting the best of alma mater') elif 21 < age < 60: print('Working hard most of their time (probably)') elif 60 <= age <= 65: print('Are you male of female?') gender = str(input()) if gender == 'male': print('Working hard most of their time (probably)') elif gender == 'female': print('Sharing wisdom with others') elif gender != 'female' or gender != 'male' or not gender: print("You are probably retired but it depends on gender") #else: #print("You are probably retired but it depends on gender") else: print('Sharing wisdom with others') ageist_function(age)
true
fa47988f2a8ac4c0b0abdb52ebb239c7e5503fb8
siriusgithub/dly
/easy/17/017/Should_I_say_this.py
348
4.15625
4
def triangle(height): line = '@' x= 1 if height == 0: print('Triangle of height 0 not valid!') while x <= height: print(line) line *= 2 x+=1 def reversetriangle(height): line = '@' x= height if height == 0: print('Triangle of height 0 not valid!') while x > 0: line = '@'*2**(x-1) print('{:>70}'.format(line)) x-=1
true
e213e5bea52460a93e747567b934984932d79800
Aaron-Bird/leetcode
/Python/101 Symmetric Tree.py
1,467
4.3125
4
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # 1 # / \ # 2 2 # / \ / \ # 3 4 4 3 # But the following [1,2,2,null,3,null,3] is not: # 1 # / \ # 2 2 # \ \ # 3 3 # Note: # Bonus points if you could solve it both recursively and iteratively. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True def callback(l, r): if l == r == None: return True elif l == None or r == None: return False elif l.val != r.val: return False else: return callback(l.left, r.right) and callback(l.right, r.left) return callback(root.left, root.right) # test class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None node = TreeNode(1) node.left = TreeNode(2) node.right = TreeNode(2) node.left.left = TreeNode(3) node.left.right = TreeNode(4) node.right.left = TreeNode(4) node.right.right = TreeNode(3) s = Solution() print(s.isSymmetric(node))
true
426b483ca5b06151e7d00bc317cecc8faa096147
Mega-Barrel/10-days-statistics
/interquartile_range.py
1,168
4.1875
4
''' Task The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3-Q1). Given an array, X, of N integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each x1 occurs at frequency fi. Then calculate and print S's interquartile range, rounded to a scale of 1 decimal place (i.e., 12.3 format). Input Format The first line contains an integer, n, denoting the number of elements in arrays X and F. The second line contains n space-separated integers describing the respective elements of array X. The third line contains n space-separated integers describing the respective elements of array F. Sample Input 6 6 12 8 10 20 16 5 4 3 2 1 5 Sample Output 9.0 ''' import statistics as st n = int(input()) data = list(map(int, input().split())) freq = list(map(int, input().split())) s = [] for i in range(n): s += [data[i]] * freq[i] N = sum(freq) s.sort() if n%2 != 0: q1 = st.median(s[:N//2]) q3 = st.median(s[N//2+1:]) else: q1 = st.median(s[:N//2]) q3 = st.median(s[N//2:]) ir = round(float(q3-q1), 1) print(ir)
true
df83ed57fddab1c66984ad0027cf12df22b4bd69
RenukaDeshmukh23/Learn-Python-the-Hard-Way-Excercises
/ex33.py
773
4.4375
4
i = 0 #intialise to 0 numbers = [] #empty list numbers while i<6: #while loop started print(f"At the top i is {i}") #print the value of i numbers.append(i) #append will add value of i to numbers list i=i+1 #increase the value of i print("Numbers now:",numbers) #print the contents of numbers list print(f"At the bottom i is {i}") #print the value of i after i+1 print("The numbers:") #after end of loop print the contents in numbers list for num in numbers: #start of for loop print(num) #print the values in list
true
61cd552cd7cf0cb8e816f6c6d9054bc6ad6fbccd
jcjcarter/Daily-1-Easy-Python
/Daily 1 Easy Python/Daily_1_Easy_Python.py
268
4.375
4
# User's name. name = input("What is your name? ") # User's age. age = input("How old are you? ") # User's username. username = input("What is your username? ") print('Your name is {0}, you are {1} years old, and your username is {2}.'.format(name, age, username))
true