blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a59f191825e2184c8cbc62493ed4add906ca11dc
Deepshikha15/pyPracticeProject
/Array_Geek/array_rotation.py
1,579
4.15625
4
def rotateleft(array_one,size,difference): for i in range(difference): temp_array = array_one[0] for j in range(size - 1): array_one[j] = array_one[j + 1] array_one[size - 1] = temp_array print(array_one[size-1]) def printArray(array_one, size): for i in range(size): print("% d"% array_one[i], end =" ") def rotate(arr, n): x = arr[n - 1] for i in range(n - 1, 0, -1): arr[i] = arr[i - 1] arr[0] = x def search(arr, l, h, key): if l > h: return -1 mid = (l + h) // 2 if arr[mid] == key: return mid if arr[l] <= arr[mid]: if key >= arr[l] and key <= arr[mid]: return search(arr, l, mid - 1, key) return search(arr, mid + 1, h, key) if key >= arr[mid] and key <= arr[h]: return search(arr, mid + 1, h, key) return search(arr, l, mid - 1, key) if __name__ == "__main__": array_one=[1,2,3,4,5,6] size=len(array_one) difference= 2 rotateleft(array_one,size,difference) # printArray(array_one,size) arr = [1, 2, 3, 4, 5] n = len(arr) print("Given array is") for i in range(0, n): print(arr[i], end=' ') rotate(arr, n) print("\nRotated array is") for i in range(0, n): print(arr[i], end=' ') arr = [5, 6, 7, 8, 9, 10, 1, 2, 3] key = 3 i = search(arr,0,len(arr)-1,key) if i != -1: print("\nthe index is %d"%i) else: print("No key found") minimumArray=[2,4,6] min = min(minimumArray) print(min)
false
f6a0fe6f8e59f9371e82fb82fabe4d96e3a007d5
OmarMWarraich/Assignments
/28-Octal_to_Decimal.py
307
4.53125
5
# Ai Assignment 27 - Convert an Octal Number to Decimal Number b = input("Input an Octal Number : ") for c in b: # Check if user input is really an Octal number if not (c in "01234567"): print(c) print("Please Enter a Valid Octal Number!") quit() print("Decimal is :", int(b, 8))
true
c5f140f0daf6101fab16366b98ec49579f622117
OmarMWarraich/Assignments
/29-Hexadecimal_to_Decimal.py
347
4.28125
4
# Ai Assignment 29 - Convert a Hexadecimal Number to Decimal Number b = input("Input an Hexadecimal Number : ") for c in b: # Check if user input is really an Hexadecimal number if not (c.upper() in "0123456789ABCDEF"): print(c) print("Please Enter a Valid Hexadecimal Number!") quit() print("Decimal is :", int(b, 16))
true
a62747ebdb6bdeb5b187ae6da91e1a4cfc965add
ordinary-developer/book_algorithms_s_dasgupta
/code/ch_0-PROLOGUE/0_2_exponential_fibonacci/main.py
279
4.125
4
def fibonacci(n): """ returns the n-th member of a fibonacci sequence (an exponential algorithm) """ if n == 0: return 0 elif n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) if __name__ == '__main__': print(fibonacci(3))
false
cd43aea6c705cc7f8f6475002f691e50f3b85c7f
FaideWW/perseus
/component/vec_test.py
2,474
4.28125
4
import math class Vector(list): """ basic list of ints with vector math functionality """ def __init__(self, lst = []): list.__init__(self, lst) while len(self) < 3: self.append(0) self.x = self[0] self.y = self[1] self.z = self[2] def __add__(self, other): newL = list(self) if (len(self) <= len(other)): l = len(self) else: l = len(other) for i in range(l): newL[i] += other[i] return newL def __sub__(self, other): newL = list(self) if (len(self) <= len(other)): l = len(self) else: l = len(other) for i in range(l): newL[i] -= other[i] return newL def __mul__(self, factor): """ multiply vector by a scalar factor """ ret = list(self) for x in range(len(ret)): ret[x] = ret[x] * float(factor) return ret def __div__ (self, factor): # should return floating point values ret = list(self) for x in range(len(ret)): ret[x] = ret[x] / float(factor) return ret def dot(self, other): d = 0 if (len(self) <= len(other)): l = len(self) for i in range(l): d += self[i] * other[i] return d def cross(self, other): """ equivalent of self X other """ a = list(self) b = list(other) while len(a) < 3: a.append(0) b.append(0) c = Vector([a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]) return c def rot(self, angle): """ rotate a 2d vector by specific angle about Z axis """ rad_angle = math.radians(angle) x = self[0] * math.cos(rad_angle) - self[1] * math.sin(rad_angle) y = self[0] * math.sin(rad_angle) + self[1] * math.cos(rad_angle) rotV = Vector([x,y]) return rotV def mag(self): """ returns magnitude of self """ magsq = 0.0 for axis in self: magsq += axis**2 magnitude = math.sqrt(magsq) return magnitude def normalize(self): """ return unit vector in the direction of self """ mag = self.mag() return self / mag def project(self, axis): """ return the 1d projection of a 2d vector onto an arbitrary axis """ unit_axis = axis.normalize() projection = self.dot(unit_axis) return projection def __str__(self): s = '[' for i in self: s += str(i) + ', ' s = s[:-2] + ']' return s v1 = Vector([2,2]) v2 = Vector([3,1]) v3 = Vector([2,0]) v4 = v2.rot(90) print v1 + v2, v2 - v1, v1 * 2, v2 / 4 print v1.normalize(), v2.normalize(), v3.normalize() print print v2.project(v3), v1.project(v2), v4.scalar_project(v2) print print v1.dot(v2) print v1.cross(v2) print v1.rot(180)
false
714e07a39555116cd10cfd83516c34be67d06391
Mellodica/RepC
/py/aulapy.py
1,609
4.15625
4
def divisaoFN(x, y): return x / y def somaFN(x, y): return x + y def multiFN(x, y): return x * y def subtracaoFN(x, y): return x - y numeros = [1, 2, 3, 4,] novos_numeros = numeros print("Novos Nmeros, Antes", novos_numeros) numeros[0] = 10 print("Novos Nmeros, Depois", novos_numeros) novos_numericos = [numero for numero in numeros] print("Novos Numericos lista comprehen...", novos_numericos) print("Ou") numerosFor = [] for numero in numeros: numerosFor.append(numero) print("Numeros em For", numerosFor) print() print() divisao = [numero / 2 for numero in numerosFor] multiplica = [numero * 2 for numero in numerosFor] subtra = [numero - 2 for numero in numerosFor] soma = [numero + 2 for numero in numerosFor] print("Com Funo") divisaoFM = [divisaoFN(numero, 2) for numero in numerosFor] multiplicaFM = [multiFN(numero, 2) for numero in numerosFor] subtraFM = [subtracaoFN(numero, 2) for numero in numerosFor] somaFM = [somaFN(numero, 2) for numero in numerosFor] print("Divisao", divisao) print("Multiplicacao", multiplica) print("Subtracao", subtra) print("Soma", soma) print("Com funcao") print("Divisao", divisaoFM) print("Multiplicacao", multiplicaFM) print("Subtracao", subtraFM) print("Soma", somaFM) #condicionais print("Condicionais") filtra = [numero for numero in somaFM if numero >= 5] print("Filtrado >= 5", filtra) print("---------------") print("Impar") impar = [numero for numero in somaFM if numero % 2 != 0] print(impar) print("Par") par = [numero for numero in somaFM if numero % 2 == 0] print(par)
false
eb423e1aa20fc4901426d23293726b3867ef5522
jasonljohn/mycode
/miniproject/calculator.py
1,882
4.21875
4
#!/usr/bin/env python3 ''' Author: Jason This program is a calculator which perform adds/subtracts/divides/multiplies. ''' flag = False # initialize flag to False as a switch to break out of while loop. # helper functions # addition def add(a, b): print(a + b) # subtraction def sub(a, b): print( a - b) # divide def div(a, b): print(a / b) # multipile def multi(a, b): print(a * b) # the main function def main(): '''the main program''' while(True and flag == False): try: print('Please enter the first operand.') ops1 = float(input(">").strip()) print('Please enter the second operand.') ops2 = float(input(">").strip()) print(''' Choose an operation you want: 1: add 2: subtract 3: divide 4: multipile 5: exit ''') ops3 = int(input('>').strip()) except: print("0_o something is wrong, please try again.") # call operation base on user input if ops3 == 1: add(ops1, ops2) elif ops3 == 2: sub(ops1,ops2) elif ops3 == 3: div(ops1,ops2) elif ops3 == 4: multi(ops1,ops2) elif ops3 == 5: exit() else: print('the option does not exist, please try again.') more() def more(): while True: print("would you like to do another operation? Y/N") try: option = input(">").strip().lower() except: print("0_o not an option, please try again.") more() if option == 'y': main() else: exit() # call the main function if __name__ == "__main__": main()
true
5fff356adb5e216432176010265d69b2381d68da
delfinachaganek/informatica.ucema
/tp2/ejercicio 3.py
584
4.15625
4
#Ej 3 # Escribí un programa que dado un número del 1 al 6, # ingresado por teclado, muestre cuál es el número que está # en la cara opuesta de un dado. Si el número es menor a 1 # y mayor a 6 se debe mostrar un mensaje indicando que es # incorrecto el número ingresado. numero= int(input ("insertar numero del 1 al 6")) if numero == 1: print ("6") elif numero == 2: print ("5") elif numero == 3: print ("4") elif numero == 6: print ("1") elif numero == 5: print ("2") elif numero == 3: print ("4") else: print("su numero ingresado es incorrecto")
false
0788a3d5b6333a4d3784463a6772c403fdd3d1b8
vellichor/learn_you_a_python
/010_scope/too_much_fun.py
1,597
4.6875
5
#!/usr/bin/env python3 # Here comes some evil Python magic! # Let's define a variable in the global scope. my_global_str = "Hey now, here we go now" # Now, let's define a function that can modify that scope. def make_a_mess(x): # first tell the interpreter that we want to look this up in the global scope global my_global_str # now we can assign to it as if it were ours. my_global_str = x print("Before making a mess...") print(my_global_str) make_a_mess("WHAT A DISASTER!!") print("After making a mess...") print(my_global_str) # since we modified the global scope directly, del can't save us! # our old value is gone forever. # now, let's make things worse. def outer_function(): outer_function_var = 0 print("This function's variable is {}".format(outer_function_var)) make_a_bigger_mess() make_a_bigger_mess() print("This function's variable is {}".format(outer_function_var)) make_a_bigger_mess() def other_outer_function(): outer_function_var = 1 print("This other function's variable is {}".format(outer_function_var)) make_a_bigger_mess() print("This other function's variable is {}".format(outer_function_var)) make_a_bigger_mess() make_a_bigger_mess() print("This other function's variable is {}".format(outer_function_var)) def make_a_bigger_mess(): nonlocal outer_function_var outer_function_var += 1 # every time this runs, we'll bump up the outer variable. outer_function() other_outer_function() # now what happens if we run this by itself? how will it know what to increment? # try uncommenting it and see! # make_a_bigger_mess()
true
09e0b18831eba6dddf1e9afa6d1abb9720584635
abhinav-gautam/python-programs
/Basics/geometry-points triangle.py
478
4.25
4
#24.geometry-points in a triangle? x=float(input("Enter the absissca : ")) y=float(input("Enter the ordinate : ")) if(x>200): print("The coordinate (",x,",",y,") is outside the triangle.") elif(y>100): print("The coordinate (",x,",",y,") is outside the triangle.") elif(0<x<200): if(0<y<100): print("The coordinate (",x,",",y,") is inside the triangle.") else: print("The coordinate (",x,",",y,") is outside the triangle.") print ("Developed by Abhinav Kumar Gautam")
false
088edf842fe12ae8d3b8953b2fd9d6237c2f6599
wusanpi825117918/study
/Day08/p_06继承.py
646
4.1875
4
''' 继承的实现 ''' # 定义一个父类 class Phone(object): def __init__(self): self.name = '电话' # 定义一个打电话的方法 def call(self,number): print(f'正在给 { number} 打电话') # 定义一个子类 class iPhone(Phone): # 添加一个拍照方法 def carmera(self): print('正在拍照') # 当发生继承后,子类会继承父类中的属性和方法,可以直接 使用 iphonex = iPhone() iphonex.call('13800138000') iphonex.carmera() print(iphonex.name) dgd = Phone() dgd.call('13800138000') print(dgd.name) # dgd.carmera()
false
9815336b6461bb062ae78f4f73eef1ff4d2fe524
wusanpi825117918/study
/Day04/p_12列表的排序和逆序.py
726
4.3125
4
''' 列表 的排序和逆序 ''' cl = [9,2,5,7,1,8,4,3,0,6] print(cl) # 排序 默认升序排序(从小到大) print(cl.sort()) print(cl) cl = [9,2,5,7,1,8,4,3,0,6] # 降序排序 (从大到小) cl.sort(reverse=True) print(cl) # 逆序 cl = [9,2,5,7,1,8,4,3,0,6] # 逆序是直接将原列表中的顺序进行逆转 cl.reverse() print(cl) # 实现列表逆序方法 def reverse_list(cl): # 定义一个空列表 ret_l = [] i = len(cl) - 1 while i >= 0: ret_l.append(cl[i]) # s += c i -= 1 return ret_l print(reverse_list(cl)) ''' l = [1,2,3,4,5] l[0] l[4] l = [5,2,3,4,1] l[1] l[3] l = [5,4,3,2,1] '''
false
289b8e8e5bfcd4f4d7620f65540ce11df6d35129
eapmartins/ds-algorithms
/src/recursion/reverse_string.py
440
4.59375
5
def reverse_string(input): """ Return reversed input string Examples: reverse_string("abc") returns "cba" Args: input(str): string to be reversed Returns: a string that is the reverse of input """ if len(input) == 1: return input[0] return input[-1] + reverse_string(input[:-1]) assert reverse_string("abcde") == "edcba" assert reverse_string("edson") == "nosde"
true
222618fe413f02bc8ff555d38c61a756eef9b359
andrewbeattycourseware/programmingandscripting
/messing/firstAndLastmonth.py
573
4.28125
4
from datetime import date import calendar delimiter = "." today = date.today() datesRange = calendar.monthrange(today.year,today.month) print ("last day of this month is {}".format(datesRange[1])) # I could create a date with the range[1] # d1 = today.strftime("%d.%m.%Y") # print("d1 =", d1) # but we just want the string fromDateString = "1" + delimiter + str(today.month) + delimiter + str(today.year) toDateString = str(datesRange[1]) + delimiter + str(today.month) + delimiter + str(today.year) print ("dates from {} to {} ".format(fromDateString,toDateString))
true
53e731c13fcf0148ce04c2e048416c2b7d208d7a
LuluwahA/100daysofcode
/Day 38.py
245
4.25
4
car =["ford","volvo","BMW"] for x in car: print(x) car =["ford","volvo","BMW"] car.append("honda") print(car) car =["ford","volvo","BMW"] car.pop(0) print(car) car =["ford","volvo","BMW"] car.remove("volvo") print(car)
false
c77d1ad9086e52c09311fdc19ba057a9e01875e6
nawang87/PythonCrashCourse
/31_return_statement/31_code.py
1,246
4.21875
4
#Return Statement #Return keyword used to give value back at the end of your functions, therefore, you could assign your function CALLS to variables and use their values later #Each Function in Python has to give some value back when it completes the execution #This is designed for assigning the call's of the function to a variable #And make some uses with this variable in the future #This case is going to return nothing, because we did not use return keyword def square_my_number(num): print(num ** 2) result = square_my_number(num=4) print(result) #So it is equvielant to this: def square_my_number(num): print(num ** 2) return None result = square_my_number(num=4) print(result) #But we could decide that we want to store within the result variable the value of 16 #To achieve this, we could write a code like that: def square_my_number(num): return num ** 2 result = square_my_number(num=4) print(result) #Important to remember, that return is a signal for being the last line that will #execute within a function, so something like this is pointless: def square_my_number(num): return num ** 2 print("One more line to print please") # UNREACHABLE CODE! result = square_my_number(num=4) print(result)
true
933ee0aa1f57b2f46df919d580eb7a9d32e68bab
nawang87/PythonCrashCourse
/18_dictionary_methods/18_code.py
637
4.4375
4
#Dictionary Methods #There are a lot of dictionary will do different manipulations for you with the dictionaries that you work with # keys() - Will collect all the keys # values() - Will collect all the values friend = { "name" : "Mike", "age" : 25, "is_male" : True, "weight" : 64.5 } print(friend.keys()) print(friend.values()) #Those lines will return you a type of variable #That it's name is dict_keys #To make it more friendly, we can convert it to a list: print(list(friend.keys())) print(list(friend.values())) #There are more useful methods that you can take a look in python official documentation
true
a73db8367e2ac5b3258f5af2a8a4746a95da939f
nawang87/PythonCrashCourse
/24_while_loops/24_code.py
678
4.4375
4
#While Loops #We can use While loops to run some bunch of code till a condition changes after a while #Example: budget = 1000 sandwich_price = 5 while budget > 0: #Budget is currently greater than 0, it will remain like that, until we actually do something to prevent this from running forever within the while loop. #Usually we use while loops, it is important to have atleast one line of code that will affect the provided condition after the while keyword, otherwise, we will end up with having a endless loop print("You bought a sandwich!") budget -= sandwich_price #As you can notice here, we have a line that AFFECTS the budget's value. print(budget)
true
b10591022b5652974afbc864b73469149aa02598
nawang87/PythonCrashCourse
/09_expressions/09_code.py
576
4.125
4
#Expressions #Expressions will allow us to define different situations on our program, that will give us back the value of True or False #Expressions usually are going to be described with at least one of the following operators # == Equal # != Not equal # > Greater than # < Less than # >= Greater than or equal to # <= Less than or equal to # There are some more keyworded operators that we will look what they do in the future print(5 == 5) #True print(5 != 5) #False print(5 > 5) #False print(5 < 5) #False print(5 >= 5) #True print(5 <= 5) #True
true
4e906ec117378f8e5a7b52254ec309bbf31cdbe5
cmotek/py_prac
/sevenfive.py
417
4.15625
4
def main(): weight = int(input("Please provide your weight in lbs:")) height = int(input("Please provide your height in inches:")) BMI = (weight * 720)/(height ** 2) if BMI < 19: print("Your BMI is too low and unhealthy!") if BMI >= 19 and BMI <= 25: print("Your BMI is in a healthy range!") if BMI > 25: print("Your BMI is too high and unhealthy!") main()
true
7bd858276f03f94c2f5c107c7a931aa5117b02ad
shahad1997/saudidevorg
/week1/Day1-CalculateYourAge.py
1,179
4.25
4
from datetime import date# using the libary get time function if __name__ == "__main__": print ("hi in python week 1\n find here calculator system for your age") #code for cout the age today = date.today() current_year=today.strftime("%Y")#to get the current month # print(current_year) current_month=today.strftime("%m")#to get the current month # print(current_month) current_day=today.strftime("%d")#to get the current month # print(current_day) print("Count your age") age_year=input("Please enter year:") age_month=input("Please enter month:") age_day=input("Please enter day:") my_age_Y=int(current_year)-int(age_year) count_month=abs(int(current_month)-int(age_month)) my_age_D=int(current_day)-int(age_day) if my_age_Y!=0: if count_month==0: my_age_M = 0 print(abs(my_age_Y),"Years,",abs(my_age_M),"Months, ",abs(my_age_D)," days 🎉🎆🎆🎉") else: my_age_M = 12 - count_month print(abs(my_age_Y)-1, "Years,", abs(my_age_M), "Months, ", abs(my_age_D), " days 🎉🎆🎆🎉") else: print("Wow you born this year")
false
252394e548e2e5e0683eb3cf400f51cf003c97a1
odewahn/kids_code_ipython_test
/scripts/play_with_turtles.py
387
4.28125
4
import turtle turtle.showturtle() turtle.turtlesize(1) colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] while True: for color in colors: turtle.color(color) turtle.stamp() turtle.forward(10) turtle.left(1) # add some colors # add something that isn't a color? # change forward # change left # does right work? # Remove while True:
true
c44993b00011cd980fa910d57a641a816177f0b6
Denjesd/new2
/Basic/Lesson 8/Lesson_8_main.py
2,487
4.34375
4
# Lesson 8 Task 1 from Lesson_8_modules import * ###--------------------MAIN--------------------### input('''\n ---------------Welcome to drawing machine---------------- ---------------Developed by Dolbnia Denis---------------- ---------------Size up you terminal window--------------- -----------------Press ENTER to continue-----------------''') triangle_height = int(input('Enter the height of triangle (height might be %2 = 1): ')) while triangle_height % 2 == 0 or triangle_height < 0: if triangle_height < 0: triangle_height = int(input('Your value is negative.\n' 'Try another value: 0 < value % 2 == 1:')) else: triangle_height = int(input('Your value is even.\n' 'Try another value: 0 < value % 2 == 1:')) command = input('Enter (UT) to draw the first triangle.').lower() actual_triangle = draw_upper_triangle(triangle_height) while command != 'q': print('Enter (LT) to draw the lower triangle.') print('Enter (PUT) to paint the upper triangle.') print('Enter (CUT) to clear the upper triangle.') print('Enter (PLT) to paint the lower triangle.') print('Enter (CLT) to clear the lower triangle.') print('Enter (HD) to draw horizontal diagonal.') print('Enter (VD) to draw vertical diagonal.') print('Enter (CHD) to clear horizontal diagonal.') print('Enter (CVD) to clear vertical diagonal.') print('Enter (Q) to close the program.') command = input().lower() if command == 'q': print('---------------Have a nice day, see you soon!---------------') input('----------Press ENTER to close the drawing machine.---------') break if command == 'lt': actual_triangle = draw_lower_triangle(actual_triangle, triangle_height) if command == 'put': paint_upper_triangle(actual_triangle,triangle_height) if command == 'plt': paint_lover_triangle(actual_triangle, triangle_height) if command == 'vd': draw_vertical_diagonal(actual_triangle, triangle_height) if command == 'hd': draw_horizontal_diagonal(actual_triangle) if command == 'cut': clear_upper_triangle(actual_triangle, triangle_height) if command == 'clt': clear_lower_triangle(actual_triangle, triangle_height) if command == 'cvd': clear_vertical_diagonal(actual_triangle, triangle_height) if command == 'chd': clear_horizontal_diagonal(actual_triangle)
true
7c92fddc37c8d63a15b843f2e1cbdec8b7446322
Denjesd/new2
/Basic/Lesson 3/Lesson_3_Task_3.py
971
4.28125
4
# Lesson 3 Task 3 input_value = '' counter = 0 values_sum = 0 min_value = '' max_value = '' even_counter = 0 odd_counter = 0 while input_value != 0: input_value = int(input(f'Enter the number (index = {counter}): ')) if input_value == 0: continue elif counter == 0: min_value = input_value max_value = input_value counter += 1 values_sum += input_value if input_value < min_value: min_value = input_value if input_value > max_value: max_value = input_value if input_value % 2 == 0: even_counter += 1 else: odd_counter += 1 print(f'\nThe number of inputs is {counter}.') print(f'The summ of values is {values_sum}.') print(f'An Average number is {values_sum / counter}.') print(f'The minimal value is {min_value}.') print(f'The maximal value is {max_value}.') print(f'The number of even numbers is {even_counter}.') print(f'The number of odd numbers is {odd_counter}.')
true
1e31333e3ecb8fdc1a048d98941d5e4121c5bbf2
LauraJaneStevenson/checkmate
/check-mate.py
1,214
4.21875
4
def check(king, queen): """Given a chessboard with one K and one Q, see if the K can attack the Q. This function is given coordinates for the king and queen on a chessboard. These coordinates are given as a letter A-H for the columns and 1-8 for the row, like "D6" and "B7": """ # dictionary to store the value of the columns columns = { 'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5, 'F' : 6, 'G' : 7, 'H' : 8 } # return true if king and queen are in the same row or column if king[0] == queen[0] or king[1] == queen[1]: return True # return true if the queen is diagonal to the king by checking if difference # between rows is = to difference between columns elif abs(int(king[1]) - int(queen[1])) == abs(columns[king[0]] - columns[queen[0]]): return True return False # positions to check print(check("D6", "H6")) print("\n") print(check("E6", "E4")) print("\n") print(check("B7", "D5")) print("\n") print(check("A1", "H8")) print("\n") print(check("A8", "H1")) print("\n") print(check("D6", "H7")) print("\n") print(check("E6", "F4")) print("\n")
true
5eeacae688f9f4a7f5a2963f696ad2e84611d112
Amayu1211/Program-in-Python
/index.py
1,138
4.4375
4
#Python Program to Display calendar. import calendar # Enter the month and year yy = int(input("Enter year: ")) mm = int(input("Enter month: ")) print(calendar.month(yy,mm)) #Simple Calculator by Making Functions def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice(1/2/3/4): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") #Python Program to Display the multiplication Table num = int(input(" Enter the number : ")) # using for loop to iterate multiplication 10 times print("Multiplication Table of : ") for i in range(1,11): print(num,'x',i,'=',num*i)
false
1fbefe7450776363707cbd76f0f22d17ad1cdfa9
davidozhang/hackerrank
/data_structures_domain/trie/no_prefix_set.py
758
4.125
4
#!/usr/bin/python import sys END = 'END' def add_word_to_trie(word, root): current = root for letter in word: if END in current: bad_set(word) if letter not in current: current[letter] = {} current = current[letter] if len(current.keys()) > 0: bad_set(word) current[END] = END return True def bad_set(word): print 'BAD SET' print word sys.exit(0) def main(): trie = {} s = set() for _ in xrange(input()): word = raw_input() if word in s: bad_set(word) s.add(word) add = add_word_to_trie(word, trie) if not add: bad_set(word) print 'GOOD SET' if __name__ == '__main__': main()
false
46213c9dca9ebb9100ed34e9a11b1fa11555165f
GabrielMartinsCarossi/Structured-programming-python
/NumerosPerfeitos.py
694
4.15625
4
#Gabriel M Carossi while True: n=int(input("Digite um número: ")) if n >= 0: #testa se o número é par. if n % 2 == 0: #1 e 2 já são divisores, a soma começa com 3. somaDivisores=3 for i in range (3, n-1): if n % i == 0: somaDivisores= somaDivisores + i if somaDivisores == n: print("O número é perfeito!\n") else: print("O número não é perfeito.\n") #números ímpares não são perfeitos. else: print("O número não é perfeito.\n") else: print("Número negativo!") break
false
1f7419d342142181cd231e68d26eeaaa1f88b7ea
dimitrisgiannak/Strategy_pattern-Sorting_algorythms-Python
/payMethods.py
1,500
4.125
4
from strategy import CashStrategy from strategy import Credit_or_Debit_CardStrategy from strategy import Money_or_Bank_TransferStrategy from menu import payment_menu #A dictionary with all available payment methods. #Each str number is a Strategy accepted_payment_methods = { "1" : Credit_or_Debit_CardStrategy , "2" : Money_or_Bank_TransferStrategy , "3" : CashStrategy , } def paymentMethod(): """ Function that helps the client pick the strategy he wants. In try except we check if the option he gave is valid. If not , respond with appropriate message. """ payment_menu() #Call's function to show the options of payment from menu.py while True: payment_list = ["1" , "2" , "3"] try: payment_method = int(input("Please choose: ")) payment_method = str(payment_method) if len(payment_method) != 1: #Choise is len == 1 always raise IndexError if payment_method not in payment_list: raise ValueError break except ValueError: print("You must give the appropriate number as shown in the table !") except IndexError: print("You must choose between the three payment methods. " "Your choice can't have more than one number !!") #We use the dictionary with our options and instantiate it using () at the end. return (accepted_payment_methods[payment_method])()
true
ce0709024bd11dd1b156073d12b95b2595d3e123
Awonkhrais/data-structures-and-algorithms
/python/code_challenges/insertion_sort/insertion_sort/insertion_sort.py
324
4.1875
4
def insertion_sort(array): for i in range(len(array)): j = i - 1 temp = array[i] while j >= 0 and temp < array[j]: array[j + 1] = array[j] j = j - 1 array[j + 1] = temp return array print([5,11,-3,30,66,9,110]) print(insertion_sort([5,11,-3,30,66,9,110]))
false
f885b1ef6a4c397bbc0609c823f7e619cdaf0423
olinkaz93/Algorithms
/Interview_Examples/Leetcode/328_OddEvenLinkedList.py
1,333
4.15625
4
""" Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4] """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None or head.next == None: return head odd_node = head even_node_head = head.next even_node = head.next while (odd_node != None and even_node != None and even_node.next != None): #node_after_odd = odd_node.next node_after_even = even_node.next odd_node.next = node_after_even even_node.next = node_after_even.next odd_node = odd_node.next even_node = even_node.next odd_node.next = even_node_head return head
true
97cf2ab4033f13cc8e5ac57ba99daca0cc33d525
olinkaz93/Algorithms
/Interview_Examples/TheCodingInterviewBootcamp_Algorithms_DataStructures/section11_printsteps.py
1,120
4.21875
4
#write a function that accepts a positive number N #the function should console log a step shape using # character #make sure the steps has spaces on the right side! """examples steps(2): '# ' '##' steps(3: '# ' '## ' '###' steps(4) '# ' '## ' '### ' '####' """ def steps(n): number_of_lines = n lenght_of_lines = n line = "" for index_of_line in range(0, number_of_lines, 1): number_of_hashes = index_of_line+1 hashes = number_of_hashes*"#" line = line + hashes while (len(line)<lenght_of_lines): line = line + " " print(line) line = "" def stepsVersion2(n): number_of_lines = n lenght_of_lines = n line = "" for index_of_line in range(0, number_of_lines, 1): number_of_hashes = index_of_line+1 hashes = number_of_hashes*"#" number_of_white_spaces = lenght_of_lines - number_of_hashes white_spaces = number_of_white_spaces*" " line = hashes + white_spaces print(line) line = "" if __name__ == "__main__": n = 4 #steps(n) stepsVersion2(20)
true
c1301c5a2bdba35c0240e9ccb502e627ad39d943
olinkaz93/Algorithms
/Interview_Examples/Leetcode/159_ LongestSubstringwithAtMostTwoDistinctCharacters.py
1,778
4.15625
4
""" Given a string s, return the length of the longest substring that contains at most two distinct characters. Example 1: Input: s = "eceba" Output: 3 Explanation: The substring is "ece" which its length is 3. Example 2: Input: s = "ccaabbb" Output: 5 Explanation: The substring is "aabbb" which its length is 5. Constraints: 1 <= s.length <= 104 s consists of English letters. https://www.youtube.com/watch?v=6tBEcczNMl8 """ def lengthOfLongestSubstringTwoDistinct(s): right_pointer = 0 left_pointer = 0 dictionary_of_characters = {} max_length = float('-inf') #we need to move the right pointer up to thew point where #the are AT most 2 different characters 1<char<=2 #we will move the left pointer as soon as there are more than #2 different chracters (means at least 3) #and then we will slide it just after that occurence + update #the length of the subbaray and update if necccesary the MAX for right_pointer in range(0, len(s), 1): current_length = right_pointer - left_pointer current_char = s[right_pointer] if current_char not in dictionary_of_characters: dictionary_of_characters[current_char] = 1 else: dictionary_of_characters[current_char] += 1 while (len(dictionary_of_characters.keys()) > 2): dictionary_of_characters[s[left_pointer]] -= 1 if dictionary_of_characters[s[left_pointer]] == 0: del dictionary_of_characters[s[left_pointer]] left_pointer += 1 if (current_length > max_length): max_length = current_length return (max_length) if __name__ == "__main__": string = "sssaaaassm" result = lengthOfLongestSubstringTwoDistinct(string) print(result)
true
05386d03efc08bc2f02369218f6c519073a843d6
olinkaz93/Algorithms
/Interview_Examples/Leetcode/14_LongestCommonPrefix.py
961
4.21875
4
""" Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. https://www.youtube.com/watch?v=K1ps6d7YCy4 """ def longestCommonPrefix(strs): if (len(strs)) == 0: return "" if (len(strs)) == 1: return len(strs[0]) first_prefix = strs[0] length_prefix = len(first_prefix) for word in strs: while word.startswith(first_prefix) != True: #while word.find(first_prefix) != 0: first_prefix = first_prefix[:-1] if (first_prefix) == "": return "" return first_prefix if __name__ == "__main__": strs = ["flower","flow","flight"] result = longestCommonPrefix(strs) print(result)
true
59742f3a9c2a5c46aa28939376c76e0f65c896d4
olinkaz93/Algorithms
/Interview_Examples/Leetcode/350_Intersection_Two_arrays.py
1,664
4.21875
4
""" Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] nums1 = [1,1,2,2] nums2 = [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Explanation: [9,4] is also accepted. nums1 = [4,5,9] nums2 = [4,4,8,9,9] https://www.youtube.com/watch?v=lKuK69-hMcc """ def findIntersection(list1, list2): if(len(list1) >= len(list2)): first_list = list1 second_list = list2 else: first_list = list2 second_list = list1 numbers_first_list_dictionary = {} #we create a hash map of our first list, which will store the number, as a key, and the occurency as a value for number in first_list: if number not in numbers_first_list_dictionary: numbers_first_list_dictionary[number] = 1 else: numbers_first_list_dictionary[number] += 1 print(numbers_first_list_dictionary) #having the list, we can loop over the second list, and compare if value, exists #if it so, we will add the common number to the result, and decrement the value of the occurent number in list1 result = [] for number in second_list: if number in numbers_first_list_dictionary and numbers_first_list_dictionary[number] > 0: result.append(number) numbers_first_list_dictionary[number] -= 1 print(result) if __name__ == "__main__": list_a = [1,2] list_b = [1,1] findIntersection(list_a, list_b)
true
1854721bbda64cf46312958d1d892a983c122b6f
olinkaz93/Algorithms
/Interview_Examples/Leetcode/424_LongestRepeatingCharacterReplacement.py
667
4.1875
4
""" You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. https://www.youtube.com/watch?v=7Q1uylXOatU """
true
e6ce02965f64ea50650e72ba661028a81b1b86b4
olinkaz93/Algorithms
/Interview_Examples/Leetcode/205_IsomorpicString.py
1,293
4.15625
4
""" Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true Constraints: 1 <= s.length <= 5 * 104 t.length == s.length s and t consist of any valid ascii character. """ def isIsomorphic(s, t): """ :type s: str :type t: str :rtype: bool """ dictionary_s = {} dictionary_t = {} for index, el in enumerate(s): if el not in dictionary_s: dictionary_s[el] = [index] else: dictionary_s[el].append(index) for index, el in enumerate(t): if el not in dictionary_t: dictionary_t[el] = [index] else: dictionary_t[el].append(index) for value in dictionary_t.values(): if value not in dictionary_s.values(): return False return True if __name__ == "__main__": print(isIsomorphic("aabb", "ccdd"))
true
19a1579f06113e69ec7838dabb1da24e7b806e02
olinkaz93/Algorithms
/Interview_Examples/Leetcode/54_SpiralMatrix.py
1,812
4.21875
4
""" Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 Accepted https://www.youtube.com/watch?v=BdQ2AkaTgOA https://www.youtube.com/watch?v=uYgoo8BdUAAv """ """ [[1,2,3], matrix = [4,5,6], [7,8,9]] """ def spiralMatrix(matrix): if len(matrix) == 0 or len(matrix[0]) == 0 or matrix == None: return [] rows = len(matrix) cols = len(matrix[0]) result = [] # each iteration we need to check the current size of inserted elements # so we will loop while len(result) < size_of_matrix top = 0 right = len(matrix[0]) - 1 bottom = len(matrix) - 1 left = 0 size_of_matrix = rows * cols # print(size_of_matrix) while (len(result) < size_of_matrix): if (len(result) < size_of_matrix): for i in range(left, right + 1, 1): result.append(matrix[top][i]) print(matrix[top][i]) top += 1 if (len(result) < size_of_matrix): for i in range(top, bottom + 1, 1): result.append(matrix[i][right]) right -= 1 if (len(result) < size_of_matrix): for i in range(right, left - 1, -1): result.append(matrix[bottom][i]) bottom -= 1 if (len(result) < size_of_matrix): for i in range(bottom, top - 1, -1): result.append(matrix[i][left]) left += 1 return result if __name__ == "__main__": print(spiralMatrix([[1,2,3],[4,5,6],[7,8,9]]))
true
7fe48586ca5de92d03c9d04b145358001d89fb7f
olinkaz93/Algorithms
/Interview_Examples/Leetcode/283_MoveZeros.py
1,323
4.25
4
"""Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] """ def moveZeroes(nums): # [0,1,0,3,12] # we can use two pointers, which will start at the same position # the pointer can count the number of 0's in the list # having this we can find the pointer where we can will put our zeros. # [0,1,0,3,12] # we can use two pointers, which will start at the same position # the pointer can count the number of 0's in the list # having this we can find the pointer where we can will put our zeros. zero_counter = 0 left_index = 0 for number in nums: if number == 0: zero_counter += 1 else: nums[left_index] = number left_index += 1 # print("zeros", zero_counter) if (zero_counter) == len(nums): return nums for i in range(-(zero_counter), 0, 1): nums[i] = 0 pointer = 0 while pointer < len(nums): print(pointer) pointer += 1 if __name__ == "__main__": list1 = [0,1,0,3,12] result = moveZeroes(list1) print(result)
true
740b7afdea85233129b436adba1280cfce25a980
Kyorkis/pythonalg
/lesson2/zadacha3.py
516
4.5
4
#Сформировать из введенного числа обратное по порядку входящих в него цифр # и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. chislo = input("Введите число:") if chislo.isdigit(): reverse = chislo[::-1] print(f'Перевернутое число: {reverse}') elif chislo.isdigit() == False: print("Вы ввели не число!!!")
false
864b3c1936c9f10e00d0e490954959457cf4fd43
milanvadher/python-mdv
/p6.py
480
4.1875
4
#list l=[1,2,3,4,5] #declaration of list print l #print as it is like [1,2,3,4,5] print len(l) #for print the list length print l[0] #print individual value in array print l[4] ''' l.append(6) #to enter the value in list at last l[3] = 13 #to enter the value at perticuler place l.insert(2,'abc') #insert value at 2 l.remove('abc') #remove perticuler value del l[0] #remove position print l.index('abc') #print position ''' #using for loop print array for i in l: print i
true
321a776ab107b7ccb57419740b9ab8525149deea
craigi0043/CTI110
/P5T1_KilometerConverterIsaiahCraig.py
511
4.53125
5
# Converts kilometers to miles # 9/26/2018 # CTI-110 P5T1_KilometerConverter # Isaiah Craig # # Set the conversion factor. conversion_factor = 0.6214 def main(): # Get the distance in kilometers. km = float(input('Enter the distance in kilometers:')) # Display the distance converted to miles show_miles(km) def show_miles(km): # Calculate miles miles = km * conversion_factor # Display the miles print(km, 'kilometers equals', miles, 'miles') main()
true
effd4ad0c3dc40d0435ffe2bcf867885706967c5
lukwlw/keywords_counter
/keywords/tools/wordcount.py
1,604
4.125
4
class WordCounter: """Class for counting occurrences of specified keywords in given text""" def __init__(self, text=None, keywords=None): """Construct a word counter text - text to analyse (defaults to '') keywords - words to search and count inside text, separated by commas (defaults to '') """ self._text = '' self._keywords = '' self.text = text self.keywords = keywords def count(self): """Count keywords in specified text Return dictionary of keywords with counted occurrences""" statistics = {} if len(self._text) > 0 and len(self._keywords) > 0: statistics = dict((kw.strip(), 0) for kw in self._keywords.split(',')) for s in statistics: statistics[s] = self._text.lower().count(s.lower()) return statistics @property def text(self): """Return the text intended to analyse""" return self._text @text.setter def text(self, text): """Set the text to analyse""" if isinstance(text, str): self._text = text else: self._text = '' @property def keywords(self): """Return the keywords intended to search inside the text""" return self._keywords @keywords.setter def keywords(self, keywords): """Set the keywords to search inside the text""" if isinstance(keywords, str): self._keywords = keywords else: self._keywords = ''
true
f9ea292527a2c96c7af6afcb5aba83e99f071c18
Louis-Gabriel-TM/computer_science
/4_classic_puzzles/4_1_with_arrays/most_frequent.py
1,332
4.125
4
""" Puzzle Wording ============== Find the most frequently occuring item in an item. If given an empty array, return None. Else, assume there is a unique value that appears most frequently. """ def most_frequent_item_with_counting_dictionary(array): max_count = -1 most_frequent_item = None counting_items = dict() for item in array: if item in counting_items: counting_items[item] += 1 else: counting_items[item] = 1 if counting_items[item] > max_count: max_count = counting_items[item] most_frequent_item = item return most_frequent_item def most_frequent_item_with_set_and_sorting(array): if array: items = set(array) counting_items = [] for item in items: counting_items.append((item, array.count(item))) counting_items.sort(key=lambda x: x[1], reverse=True) return (counting_items[0][0]) def most_frequent_item_with_counter(array): from collections import Counter counting_items = Counter(array) max_count = -1 most_frequent_item = None for key, count in counting_items.items(): if count > max_count: max_count = count most_frequent_item = key return most_frequent_item if __name__ == "__main__": pass
true
bd505c27989d2c99c908979a672ebfb7f77634a0
Louis-Gabriel-TM/computer_science
/4_classic_puzzles/4_4_with_modulo/fizzbuzz.py
960
4.1875
4
""" Puzzle Wording ============== Write a program that prints the numbers fom 1 to 100. But for multiples of 3 print 'Fizz' instead of the number and for multiples of 5 print 'Buzz'. For numbers which are multiples of both 3 and 5 print 'FizzBuzz'. """ def naive_fizzbuzz(): for n in range(1, 101): if n % 3 == 0 and n % 5 == 0: print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n) def alternative_fizzbuzz(): for n in range(1, 101): fizz = (n % 3 == 0) buzz = (n % 5 == 0) if fizz and buzz: print("FizzBuzz") elif fizz: print("Fizz") elif buzz: print("Buzz") else: print(n) def short_fizzbuzz(): for n in range(1, 101): print("Fizz" * (not n % 3) + "Buzz" * (not n % 5) or n) if __name__ == "__main__": pass
false
ab0972e4e3dd1ff9cddb66919e5b87cb87b808d0
1gn1z/Curso_Python_v2_05
/5.5_operaciones_flotantes.py
814
4.21875
4
# Números de punto flotante: pi = 3.1415 precio = 29.95 print('El valor de la variable pi es: %.2f' %pi) print('El valor de la variable precio es: %.2f' %precio) # El uso de %f imprime la información con 6 decimales en total. ''' Salida: El valor de la variable pi es: 3.141500 El valor de la variable precio es: 29.950000 ''' print(pi) print(precio) print() print('El tipo de dato para la variable pi es:', type(pi)) print('El tipo de dato para la variable precio es:', type(precio)) print() print('Operaciones aritméticas sobre números de punto flotante:') # Queremos representar la circunferencia completa de un circulo # Con Pi tenemos la mitad de dicha circunferencia: pi = pi*2 print('El nuevo valor de la variable pi es:', pi) total = precio * 5 print('El total de la compra es: %.2f' %total)
false
def54246491a3e6bad0a5f51543ffd58cc0a2bf9
locie/pySIP
/pysip/utils/misc.py
2,849
4.125
4
class Namespace(dict): """A namespace object that allows attributes to be accessed as dict keys. This class is a subclass of dict, so it can be used as a dict. It also allows attributes to be accessed as dict keys. For example:: >>> ns = Namespace() >>> ns['foo'] = 'bar' >>> ns.foo 'bar' >>> ns.foo = 'baz' >>> ns['foo'] 'baz' """ def __init__(self, *args, **kwargs): super(Namespace, self).__init__(*args, **kwargs) self.__dict__ = self def __repr__(self): return 'Namespace(%s)' % super(Namespace, self).__repr__() def __str__(self): return 'Namespace(%s)' % super(Namespace, self).__str__() def __getstate__(self): return self.__dict__ def __setstate__(self, state): self.__dict__ = state def __delattr__(self, name): if name in self: del self[name] else: raise AttributeError(name) def __dir__(self): return list(self.keys()) def copy(self): return Namespace(self) def update(self, *args, **kwargs): if len(args) > 1: raise TypeError('update expected at most 1 arguments, got %d' % len(args)) other = dict(*args, **kwargs) for key, value in other.items(): self[key] = value def setdefault(self, key, default=None): if key not in self: self[key] = default return self[key] def pop(self, key, *args): if len(args) > 1: raise TypeError('pop expected at most 2 arguments, got %d' % (len(args) + 1)) if key in self: value = self[key] del self[key] return value elif args: return args[0] else: raise KeyError(key) def popitem(self): try: key = next(iter(self)) except StopIteration: raise KeyError('popitem(): dictionary is empty') value = self[key] del self[key] return key, value def clear(self): for key in list(self.keys()): del self[key] def __reduce__(self): items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() inst_dict.pop('__dict__', None) inst_dict.pop('__weakref__', None) return (self.__class__, (items,), inst_dict) def __copy__(self): return self.__class__(self) def __deepcopy__(self, memo): import copy return self.__class__(copy.deepcopy(dict(self), memo)) def __eq__(self, other): if isinstance(other, Namespace): return dict(self) == dict(other) return dict(self) == other def __ne__(self, other): return not self == other
true
b75475075a8e29c0d9b9bc7dfec5d9c5da06a416
PASSINP/Python_3-Django
/Python_Aulas_3,6+/08_Input_do_usuario.py
717
4.28125
4
# Em diversas ocasiões, precisaremos pedir um input ao usuario. Para isso iremos # utilizar a função input(). Ela ira se omunicar com o usuario e ira extrair # as informações que precisamos. Nesse caso não da espaço depois do que você # escreve. Portanto de um espaço manualmente antes da segunda aspas. input("Qual o seu nome? ") # Podemos armazenar um input dentro de uma variavel. Um input sempre sera uma # string, mesmo que seja digitado um numero ou boolean. nome = input("Qual é o seu nome? ") print(nome) # Existe uma maneira de converter o tipo de dado. Coloque o tipo que você precisa # em forma de função e a funç~çao input dentro idade = int(input("Digite sua idade: ")) print(idade)
false
5543493d5f97a43c3134abc7ab925f9be58c781e
techsumita/LetsUpgrade-AI-ML
/Day4/D4_Final.py
2,905
4.21875
4
a = 1 + 2j b = 2 + 4j print('Arthimatics of complex No') print('Addition', a + b) print('Subtraction =', a - b) print('Multiplication =', a * b) print('Division =', a / b) #print('Division =', a % b) #Research on range() functions and its parameters. Create a markdown cell print("Python range() example") print("Get numbers from range 0 to 10") for i in range(10): print(i, end =" ") print("\n") for i in range(8): print(i, end = " ") print("\n") for i in range(2, 7): print(i, end =" ") print() # using range to print number # divisible by 3 for i in range(3, 10, 3): print(i, end = " ") print() for i in range(0, 10, 2): print(i, end =" ") print() for i in range(10, 2, -2): print(i, end =" ") print() element = range(10)[0] print("First element:", element) element = range(10)[-1] print("Last element:", element) element = range(10)[4] print("Fifth element:", element) #Consider two numbers. Perform their subtraction and if the result of subtraction is greater than #25, print their multiplication result else print their division result. num1 = 28 num2 = 100 print("Value of num1 and num2: ", num1,num2) temp = num1-num2 if (temp > 25): temp=num1*num2 print("Value of temp: ", temp) else: temp=num1/num2 print("Value of temp: ", temp) #Question 4: #Consider a list of 10 elements of integer values. If the number in the list is divisible by 2, print the #result as "square of that number minus 2". myList = [ 2,3,6,4,7,8,9,10,12,30 ] lengt=len(myList) #print (lengt) for i in range(lengt-1): if ((myList[i]) % 2) == 0: print("{0} is divisible by 2".format((myList[i]))) #templist[i]= ((myList[i])*2)-2) #print(templist) else: print("{0} is Odd".format((myList[i]))) # print(myList[i]) #Question 4: #Consider a list of 10 elements of integer values. If the number in the list is divisible by 2, print the #result as "square of that number minus 2". myList = [ 2,3,6,4,7,8,9,10,12,30 ] lengt=len(myList) #print (lengt) for i in range(lengt-1): if ((myList[i]) % 2) == 0: print("{0} is divisible by 2".format((myList[i]))) #print("square of ((myList[i]) * 2) - 2".format((myList[i])*2 -2)) print ( ((myList[i]) * 2) - 2) # else: # print("{0} is not divisible by 2".format((myList[i]))) # print(myList[i]) #Question 5: #Consider a list of 10 elements. Print all the elements in the list which are greater than 7 when that #number is divided 2. myList1 = [ 2,3,6,4,7,8,9,10,12,30 ] lengt1=len(myList1) #print (lengt1) for i in range(lengt1-1): if ((myList1[i]) % 2) == 0 and (myList1[i]) > 7: print("{0} is divisible by 2 and greater than 7".format((myList1[i]))) print (myList1[i]) # else: # print("{0} is not divisible by 2".format((myList[i]))) # print(myList[i])
false
505a4c281ee6d438a63d1082fa628f299844bfcc
pichardo13/wb7_homework_week_2
/most_common_word.py
1,529
4.1875
4
""" https://leetcode.com/problems/most-common-word/description/ Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique. Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase. Example: Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] Output: "ball" Explanation: "hit" occurs 3 times, but it is a banned word. "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball,"), and that "hit" isn't the answer even though it occurs more because it is banned. """ from collections import Counter import re def mostCommonWord(paragraph, banned): #step 1: get rid of all of punctuation and only select the words using re p = re.split(r'\W+', paragraph.lower()) #step 2: only select the words that are not in the list of banned words words = [w for w in p if w not in banned] #step 3: using counter count how many times the words appear, using most common return the most common word return Counter(words).most_common(1)[0][0] print(mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
true
7de1551b99b49d2a4e36d38424c3e7d6c268f12f
AbdullahNoori/SPD2.31-Testing-Architecture
/lab/refactoring-pep8/whitespace_naming_convention.py
683
4.125
4
# by Kami Bigdely # PEP8 - whitespaces and variable names. # This is a guess game. Guess what number the computer has chosen! import random lowerLimit=0 UPPER_limit= 100 randomNumber = random.randint (lowerLimit ,UPPER_limit ) print ('The computer has selected a number between 0 and 100. Use your supernatural superpowers to guess what the number is.') while True: UserGuess = int (input("Enter a number between 0 and 100 (including): ")) if UserGuess> randomNumber: print ("Guess a smaller number.") elif UserGuess <randomNumber: print ("Guess a larger number.") else: #UserGuess == randomNumber: print ("You Won!") break
true
f65f30564c12e8020d6fe2714b8bf0910c3a8656
RobertG247/classDAY
/whileloopexample.py
1,749
4.125
4
#def listprogram(): #nameList=[] # colorList=[] # exit=flase # while(exit==False): # nameList.append(input("what is your name?")) # colorList.append(input("waht is your favorite color?")) # decision=input("press Q to quit, all other input continues") #if decision=="q" or decision=="Q" # exit=True #length=len(nameList) #for a in range(0, length): # print(nameList[a],"favorite color is", colorList[a]) # main() #myTuple = (1,2,3) #myList = list (myTuple) #myList.append(4) #print (myList) #def main(): # getname = input("what is your name") # getcolor = input("what is your favorite color") # print(getname,getcolor) # entry = input("if you would like to quit please type Q?") # main() #def listprogram(): #nameList=[] #colorList=[] #exit=flase #while(exit==False): #nameList.append(input("what is your name?")) #colorList.append(input("waht is your favorite color?")) #decision=input("press Q to quit, all other input continues") #if decision=="q" or decision=="Q" #exit=True #length=len(nameList) #for a in range(0, length): #print(nameList[a],"favorite color is", colorList[a]) def main(): listprogram() def listprogram(): nameList = [] colorList = [] exit = False while (exit == False): nameList.append(input("what is your name?")) colorList.append(input("what is your favorite color?")) decision = input("press Q to quit, all other input continues") if decision == "q" or decision == "Q": exit = True length = len(nameList) for a in range(0, length): print(nameList[a], "favorite color is", colorList[a]) main()
true
96141c19873114594f5fcc74d6ec44215178b594
nariveli/python
/tkinter section/Bookstore app/backend.py
1,509
4.1875
4
import sqlite3 class Database: def __init__(self): self.conn=sqlite3.connect('/home/martin/Downloads/Python_projects/tkinter section/Bookstore app/books.db') self.cur=self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS bookstore (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)") self.conn.commit() def insert(self,title='', author='', year='', isbn=''): self.cur.execute("INSERT INTO bookstore VALUES (NULL, ?, ?, ?, ?)", (title, author, year, isbn)) self.conn.commit() def view(self): self.cur.execute("SELECT * FROM bookstore") rows=self.cur.fetchall() return rows def delete(self,id): self.cur.execute("DELETE FROM bookstore WHERE id=?", (id,)) self.conn.commit() def search(self,title='', author='', year='', isbn=''): self.cur.execute("SELECT * FROM bookstore WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn)) rows=self.cur.fetchall() return rows def update(self,id,title, author, year, isbn): self.cur.execute("UPDATE bookstore SET title=?, author=?, year=?, isbn=? WHERE id=?", (title, author, year, isbn, id)) self.conn.commit() def __del__(self): self.conn.close() #connect() #insert("The Lord of the Rings", "JRR Tolkien", 1980, 1234358534) #delete(6) #update(4,"Happy Potter", "JK Rowling", 1998, 1234) #print(view()) #print(search('JK Rowling'))
false
ca0f99b3376f0efd39c04162cd960255c2ce42c8
BasicProbability/BasicProbability.github.io
/Homework/Programming/2016-17/Assignment5/logarithms.py
1,623
4.3125
4
import math def log_add(a, b): '''Adds to numbers in their logarithmic transformtions. :param a: The first logarithmically transformed number. :param b: The second logarithmically transformed number. :return: The log-sum of the two numbers ''' if a == -float("inf"): return b elif b == -float("inf"): return a elif a > b: return a + math.log1p(math.exp(b-a)) else: return b + math.log1p(math.exp(a-b)) def log_add_list(list_of_numbers): '''Adds all the logarithmically transformed numbers in a list. :param list_of_numbers: A list of logarithmically transformed numbers. ''' result = -float("inf") for number in list_of_numbers: result = log_add(number, result) return result def log_subtract(a , b): '''Subtracts a logarithmically transformed number b from another such number a. :param a: The first logarithmically transformed number. :param b: The second logarithmically transformed number. :return: The log-difference between a and b ''' if a == -float("inf"): return b elif b == -float("inf"): return a elif a > b: return a + math.log1p(-math.exp(b - a)) else: return b + math.log1p(-math.exp(a-b)) def log_subtract_list(list_of_numbers): '''Subtracts all the logarithmically transformed numbers in a list from the first one. :param list_of_numbers: A list of logarithmically transformed numbers. ''' result = list[0] for number in list_of_numbers[1:]: result = log_subtract(result, number) return result
true
f1d594dbc13eb5d0e63c3ff51a0265cbc4b0e650
Moscdota2/Archivos
/python1/listas y tuplas/ejercicio8.py
235
4.25
4
word = input("Introduce una palabra: ") reversed_word = word word = list(word) reversed_word = list(reversed_word) reversed_word.reverse() if word == reversed_word: print("Es un palíndromo") else: print("No es un palíndromo")
false
3fd4a0fe629212592dcbe7aa3f301235db7cd978
AldrichYang/HelloPython2
/src/string/string.py
620
4.125
4
yh = ' yang heng learn python ' print yh.upper() print yh.lower() # returns a string with whitespace removed from the start and end print yh.strip() print yh.split() print yh.join(['want', 'tobe']) text = ("%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')) # 注意:同样的语法,使用(),[],{}的输出效果都不一样,使用()是正常的 # text = ["%d little pigs come out or I'll %s and %s and %s" % # (3, 'huff', 'puff', 'blow down')] # text = {"%d little pigs come out or I'll %s and %s and %s" % # (3, 'huff', 'puff', 'blow down')} print text
true
f1bba0880d89295e27500da201f82de1dba2917e
NodakSean/python-examples
/example-class.py
1,363
4.46875
4
""" A Trivial Python Class Example. Python 3.5 """ class Employee: """A trivial class example.""" _number_of_employees = 0 def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.employee_id = 0 Employee._number_of_employees += 1 @property def email_address(self): return "{}.{}@domain.com".format(self.first_name, self.last_name) @property def fullname(self): return "{} {}".format(self.first_name, self.last_name) @staticmethod def compare(employee_1, employee_2): return employee_1.employee_id > employee_2.employee_id @property def employee_count(self): return Employee._number_of_employees def __str__(self): return "Name:{} | Email: {} | ID: {}".format(self.fullname, self.email_address, self.employee_id) def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.first_name, self.last_name) print() a = Employee("John", "Smith") a.employee_id = 21 print("Employee Count: {}".format(a.employee_count)) print(a) print(repr(a)) print() b = Employee("Mike", "Gordon") b.employee_id = 42 print("Employee Count: {}".format(b.employee_count)) print(b) print(repr(b)) print() print("{} > {}: {}".format(a.employee_id, b.employee_id, a.compare(a, b)))
false
00bf00bd2740a71b9bb5fad596e3ffb8da19e009
2226171237/Algorithmpractice
/chapter02_stack_queue_hash/t2.4.py
1,612
4.125
4
#-*-coding=utf-8-*- ''' 如何根据入栈序列判断可能的出栈序列 输入两个整数序列,其中一个序列表示栈的push() 顺序,判断另一个序列有没有肯是对应的pop 顺序 ''' class LNode: def __init__(self, x, next=None): self._data = x self.next = next class MyStack: def __init__(self): self.head = None # 栈顶 self._length = 0 def is_empty(self): return self.head is None def push(self, x): if self.is_empty(): self.head = LNode(x) else: tmp = self.head self.head = LNode(x) self.head.next = tmp self._length += 1 def pop(self): if self.is_empty(): return None node = self.head self.head = self.head.next self._length -= 1 return node._data def top(self): if self.is_empty(): return None return self.head._data def length(self): return self._length def isPopSerial(push,pop): if push is None or pop is None: return False pushLen=len(push) popLen=len(pop) if pushLen!=popLen: return False S=MyStack() pop_index=0 push_index=0 while push_index<pushLen: S.push(push[push_index]) while not S.is_empty() and S.top()==pop[pop_index]: S.pop() pop_index+=1 push_index+=1 if S.is_empty() and pop_index==push_index: return True else: return False if __name__ == '__main__': print(isPopSerial([1,2,3,4,5],[5,3,4,2,1]))
false
c945b50b1fe13e3f0ef3798dc76b01bb20483914
emlbarnes/she_codes_python
/turtles/starter/reading.py
1,591
4.125
4
import csv from datetime import datetime def read_csv_file(file_name): output=[] with open(file_name) as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: # print(', '.join(row)) output.append(row) return output def convert_mmddyyyy_date(date): return datetime.strptime(date, '%m/%d/%Y') def get_month_name(date): return date.strftime('%B') def transform_daily_to_monthly(data): '''Transform the data from daily to monthly format. Args: data: a list of lists, where each sublist represents data for a specific day. Returns: a list of lists, where each sublist represents data for a whole month. ''' output=[] current_month = None month_data=[] for row in data: # print (row[0]) print() date = row[0] print(date) month = get_month_name(convert_mmddyyyy_date(date)) print(month) if current_month != month: print('New month!') current_month = month if month_data: output.append(month_data) month_data = [] month_data.append(row) return output if __name__ == "__main__": all_data = read_csv_file('data/2020_2021_turtle_data.csv')[1:] monthly_data = transform_daily_to_monthly(all_data) for item in monthly_data: print() print (item) # date = convert_mmddyyyy_date("6/7/2021") # print(get_month_name(date))
true
04325ace93bd02806663c4925ed1a7fbe40d3e56
Alyssb/CSC131-lab02
/csc131/lab02.py
1,649
4.5
4
def fact_recursive(n: int) -> int: """ Computes n! using recursion. :param n: The value whose factorial we seek :return: n! is returned; -1 is returned if n < 0. """ if n < 0: return -1 elif n == 0: return 1 else: return n*fact_recursive(n-1) # TODO: Implement me correctly using recursion return None def fact_iterative(n: int) -> int: """ Computes n! using recursion. :param n: The value whose factorial we seek :return: n! is returned; -1 is returned if n < 0. """ temp = 1 if n < 0: return -1 elif n == 0: return 1 else: for index in range(1,n+1): temp *= index # TODO: Implemented me correctly using iteration. return temp def fact(n: int, use_recursion=True) -> int: """ Factorial factory method that computes n! using recursion or iteration. :param n: The value for which we compute n! :param use_recursion: Flag that dictates technique for computation; True computes using recursion, False computes iteratively :return: n! is returned or -1 if n < 0. """ if use_recursion: return fact_recursive(n) else: return fact_iterative(n) def fib(n: int) -> int: """ Finds the nth fibonacci number using recursion. :param n: The Fibonacci number to compute; n > 0 :return: The nth Fibonacci number is returned; -1 is returned if n < 1 """ if n < 1: return -1 elif n == 1 or n == 2: return 1 else: return fib(n-1)+fib(n-2) # TODO: Implement me correctly using recursion return None
true
cd7a9e43db94f46df1d9d4d8d9da6beba435411c
RoshithR/Leetcode
/MostCommonWord.py
837
4.125
4
# Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. # It is guaranteed there is at least one word that is not banned, and that the answer is unique. # The words in paragraph are case-insensitive and the answer should be returned in lowercase. import collections, operator def mostCommonWord(paragraph, banned): processed_text = ''.join([c.lower() if c.isalnum() else ' ' for c in paragraph]) word_list = processed_text.split() word_count = collections.defaultdict(int) for word in word_list: if word not in banned: word_count[word]+=1 return max(word_count.items(), key=operator.itemgetter(1))[0] paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] print(mostCommonWord(paragraph, banned))
true
e0bfa8d3d01fcb319cb41b0b4c6fd81d664fe6a0
RoshithR/Leetcode
/CompareVersionNumbers.py
1,434
4.21875
4
# Given two version numbers, version1 and version2, compare them. # Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. # To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. # Return the following: # If version1 < version2, return -1. # If version1 > version2, return 1. # Otherwise, return 0. def compareVersionNumbers(version1,version2): nums1 = version1.split('.') nums2 = version2.split('.') n1 = len(nums1) n2 = len(nums2) for i in range(max(n1,n2)): i1 = int(nums1[i]) if n1>i else 0 i2 = int(nums2[i]) if n2>i else 0 if i1!=i2: return -1 if i1 < i2 else 1 return 0 version1 = "0.1" version2 = "1.1" print(compareVersionNumbers(version1,version2))
true
c054d4f8e8412d88be848bf147c4f44d2cefe351
viewer010/learn-python3
/advance/5_do_iter.py
2,729
4.25
4
#!/usr/bin/env python3 #coding=utf8 #迭代器:可以被next()函数调用并不断返回下一个值得对象称为迭代器 #生成器:在python中,一边循环一边计算的机制,称为生成器 #可迭代对象:可以直接作用于for循环对象统称为可迭代对象 # :可以使用isinstance()判断一个对象是否时Iterable对象 # :直接作用于for循环的数据类型有:(集合数据类型),list,tuple,dict,set,str等;(generator),包括生成器和带yield的generator function #把list,dict,str等Iterable变成Iterator,可以使用iter() #为啥list,dict,str等数据类型不是Iterator? #这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误 #可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是有惰性的,只需要在返回下一个数据时它才会计算 #Iterator甚至可以表示一个无限大的数据流,例如全体自然数。 #而使用list是永远不可能存储全体自然数的。 #python的for循环本质上都是通过不断调用next()函数实现的 from collections import Iterable,Iterator def g(): yield 1 yield 2 yield 3 print('Iterable?[1,2,3]:',isinstance([1,2,3],Iterable)) print('Iterable?\'abc\':',isinstance('abc',Iterable)) print('Iterable?123:',isinstance(123,Iterable)) print('Iterable?g():',isinstance(g(),Iterable)) print('Iterator?[1,2,3]:',isinstance([1,2,3],Iterator)) print('Iterator?iter([1,2,3]):',isinstance(iter([1,2,3]),Iterator)) print('Iterator?\'abc\':',isinstance('abc',Iterator)) print('Iterator?123:',isinstance(123,Iterator)) print('Iterator?g():',isinstance(g(),Iterator)) #iter list: print('for x in [1,2,3,4,5]:') for x in [1,2,3,4,5]: print(x) print('for x in iter([1,2,3,4,5]):') for x in iter([1,2,3,4,5]): print(x) print('next():') it=iter([1,2,3,4,5]) print(next(it)) print(next(it)) print(next(it)) print(next(it)) print(next(it)) # print(next(it)) StopIteration d={'a':1,'b':2,'c':3} #iter each key: print('iter key:',d) for k in d.keys(): print('key:',k) #iter each value: print('iter value:',d) for v in d.values(): print('value:',v) #iter both key and value: print('iter item:',d) for k,v in d.items(): print('item:',k,v) #iter list with index: print('iter enumerate([\'A\',\'B\',\'C\'])') for i,value in enumerate(['A','B','C']): print(i,value) #iter complex list: print('iter [(1,1),(2,4),(3,9)]') for x,y in [(1,1),(2,4),(3,9)]: print(x,y)
false
7b11e206604a510aed5a671d895715964d4f1c38
viewer010/learn-python3
/opp_basic/0_student.py
1,142
4.125
4
#!/usr/bin/env python3 #coding=utf8 class Student(object): def __init__(self,name,score): self.name=name self.score=score def print_score(self): print("%s: %s"%(self.name,self.score)) def grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson',59) lisa = Student('Lisa Simpson',87) print('bart.name=',bart.name) print('bart.score=',bart.score) bart.print_score() print('lisa.name',lisa.name) print('lisa.score=',lisa.score) lisa.print_score() print('grade of Bart:',bart.grade()) print('grade of Lisa:',lisa.grade()) #和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同: bart.age=8 print(bart.age) # print(lisa.age)#AttributeError # 可以直接在Student类的内部定义访问数据的函数,这样,就把“数据”给封装起来了 # 数据封装、继承和多态只是面向对象程序设计中最基础的3个概念
false
9c594d0723dd2056e887120e7f7e61b8af1fbadb
hpine19/Purple-cheesecakes
/problem1 copy.py
1,369
4.25
4
# prompt for user input #if n is greater than or equal to 0: #prompt user to input 5 positive intergers #find the maximum #minimum #average #print output n= int(raw_input("Enter in how many positive intergers you will be typing: ")) #prompts the user for input #n represents the number of intergers the user wants to input #list= [n1, n2, n3, n4, n5] counter= 0 list= [] #list of numbers the user input while counter < n: #while counter is less than the number the user input do the following i= float(raw_input("Enter in a positive number (they can be decimals): ")) #i represents the intergers the user inputs list.append(i) #holds and saves list of number the user input counter= counter+ 1 #if counter is eequal to counter plus 1 then stop the sequence #n1= float(raw_input("Enter in a positive interger: ")) #n2= float(raw_input("Enter in a positive interger: ")) #n3= float(raw_input("Enter in a positive interger: ")) #n4= float(raw_input("Enter in a positive interger: ")) #n5= float(raw_input("Enter in a positive interger: ")) print "The maximum number is", max(list) #prints out the maximum number that the user input print "The minimum number is", min(list) #prints out the minimum number that the user input print "The average is", sum(list) / len(list) #prints out the average of all the numbers numbers that the user input
true
8d0a77e7c3ce46ada15712ebd0b5b15e79f05cdf
jmilou/astronomy_utilities
/divide_night.py~
2,533
4.3125
4
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- """ Created on Thu Jul 26 15:27:18 2018 This script asks you to enter the date and then gives in output the time of sunset, sunrise, twilights, middle of the night as well as any fractions of the nights (multiple of 0.1night). The goal is to ease the task of the night astronomer when a visitor has only a fraction of the night by avoiding to make mistakes. It makes use of numpy and astral package, and is set up for Paranal only. @author: jmilli """ import numpy as np import astral, datetime paranal_astral = astral.Location(info=("Paranal", "Chile", -24.6268,-70.4045, "Etc/UTC",2648.0)) paranal_astral.solar_depression = "astronomical" # "civil" means 6 degrees below the horizon, is the default # value for computing dawn and dusk. "nautical" means 12 degrees # and "astronomical" means 18 degrees date_str = input('Enter the date (use the iso format 2018-10-13)or just press enter for today:\n') if date_str == '': day = datetime.date.today() else: try: day_array = date_str.split('-') day = datetime.date(int(day_array[0]),int(day_array[1]),int(day_array[2])) except: print("The date was not understood. We assume you mean today's date") day = datetime.date.today() print('The date of observation is set to {0:s}\n'.format(day.isoformat())) result_today = paranal_astral.sun(date=day) result_tomorrow = paranal_astral.sun(date=day + datetime.timedelta(1)) midnight = result_today['dusk']+(result_tomorrow['dawn']-result_today['dusk'])/2. print('Sunset : {0:s}'.format(result_today['sunset'].isoformat())) print('End of evening twilight : {0:s}'.format(result_today['dusk'].isoformat())) print('Middle of the night : {0:s}'.format(midnight.isoformat())) print('Start of morning twilight: {0:s}'.format(result_tomorrow['dawn'].isoformat())) print('Sun rise : {0:s}\n'.format(result_tomorrow['sunrise'].isoformat())) fractions_night = np.linspace(0.1,0.9,9) fractions_night = np.delete(fractions_night,4) description_fractions_night = ['{0:.1f}n'.format(frac) for frac in fractions_night] description_fractions_halfnight = ['{0:.1f}H{1:d}'.format(np.mod(2*frac,1),int(2*frac+1)) for frac in fractions_night] for i,description in enumerate(description_fractions_halfnight): t = result_today['dusk']+(result_tomorrow['dawn']-result_today['dusk'])*fractions_night[i] print('{0:s} = {1:s} : {2:s}'.format(description,description_fractions_night[i],t.isoformat()))
true
9a5733bec711d2edac7c53a22f8f08e0af89edc3
marciliojrr/PythonExercicios
/ex016.py
334
4.15625
4
# Ex 016 # Crie um programa que leia um número real qualquer pelo teclado # e mostre na tela a sua porção inteira. from math import trunc num = float(input('Digite um número real: ')) print('O número {} tem a parte inteira igual a {}.'.format(num, trunc(num))) # pode-se fazer o truncamento usando a função int(x)
false
3fb7869982e159dbd250a2d4665301d6a06d64ec
Samrat132/Printing_Format
/lab2/True or Flase.py
256
4.15625
4
# For given integer x, print ‘True’ if it is positive, print ‘False’ if it is negative and print ‘zero’ if it is 0. num=int(input('Enter the number:')) if (num >0): print('True') elif (num<0): print('False') else: print('Zero')
true
5f50d7859e87eb04c6f333e51edd3529a520a299
Samrat132/Printing_Format
/Lab4/nine.py
279
4.34375
4
#Write a program to find the factorial of a number num=-9 fac=1 if num < 0: print("Factorial doesn't exist for negative numbers") elif num == 0: print("Factorial of 0 is 1") else: for i in range(1,num+1): fac=fac*i print(f"Factorial of {num} is {fac}")
true
5d4a5d6966959880b4e7c855f1192a7c29d27584
Samrat132/Printing_Format
/Lab3/check.py
520
4.5
4
#Write a Python function that checks whether a passed string is palindrome or not. # Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. # Accept string from the user and display only those characters which are present at an even index. string=input('Enter the string: ') def palindrome(string): temp=string rev=string[::-1] if temp == rev: print('It is a palindrome') else: print('It is not a palindrome') palindrome(string)
true
f03d4d73dfb66b2be6123a485fc782bf52c66ada
jothamsl/Algorithms-n-Data-Structures
/Data structures/Array/array_rotation.py
714
4.5
4
""" Array Rotation -------------- Write a function "rotate(arr[], d, n)" that rotates arr[] of size n by d elements. E.g Given array [1, 2, 3, 4, 5, 6, 7], d = 2. Rotate by 2 => [3, 4, 5, 6, 7, 1, 2] """ from typing import List from copy import copy arr = [1, 2, 3, 4, 5, 6, 7] N = len(arr) D = 6 def rotate(arr: List[int], d: int, n: int) -> List[int]: """ Rotates Array by d """ temp = [arr.pop(0) for i in range(d)] # Pop first two array values for i in temp: arr.append(i) # Append popped items back into the list return arr if __name__ == "__main__": print("Initial Array: {}".format(arr)) print("Modified Array of shift {} : {}".format(D, rotate(arr, D, N)))
true
903035a6ee29c106f7036bc6b1c27c621b2b6504
kemingy/techie-delight
/src/clock_angle.py
548
4.1875
4
# Clock Angle Problem: Given time in hh:mm format, calculate the shorter angle # between hour and minute hand in an analog clock. import math def parse(time): assert ':' in time hour, minute = time.split(':') return int(hour), int(minute) def clock_angle(time): hour, minute = parse(time) degree_hour = hour * 360 / 12 + minute * 360 / 12 / 60 degree_minute = minute * 360 / 60 angle = int(math.fabs(degree_hour - degree_minute)) angle = angle if angle <= 180 else 360 - angle return angle
true
ed5340499fdfb66c91b67232a96321bfe48dd44b
rafaeljcunha/python
/basico/aula5.py
1,317
4.34375
4
""" Operadores Aritimeticos """ """ Assim como aprendemos na matemática, operadores têm uma certa precedência que pode ser alterada usando os parênteses (como descrito na aula anterior). Abaixo, segue uma lista mais precisa de quais operadores tem maior prioridade na hora de realizar contas mais complexas (de maior para menor precedência). ( n + n ) - Os parênteses têm a maior precedência, contas dentro deles são realizadas primeiro ** - Depois vem a exponenciação * / // % - Na sequência multiplicação, divisão, divisão inteira e módulo + - - Por fim, soma e subtração Contas com operadores de mesma precedência são realizadas da esquerda para a direita. Observação: existem muito mais operadores do que estes em Python e todos eles também têm precedência, você pode ver a lista completa em https://docs.python.org/3/reference/expressions.html#operator-precedence (sempre utilize a documentação oficial como reforço caso necessário). Caso tenha dúvidas, faça testes com números. Por exemplo, olhe para essa conta e tente decifrar como chegar no resultado: 2 + 5 * 3 ** 2 - (23.5 + 23.5) (o resultado é 0.0). """ print(2 + 5 * 3 ** 2 - (23.5 + 23.5)) """ (23.5 + 23.5) = 47 3 ** 2 = 9 5 * 9 = 45 2 + 45 = 47 47 - 47 = 0 """
false
9bce006edeb9f19d4e4be3ab6d05ab7c743603e7
ariannedee/intro-to-python
/Examples/example_12_lists.py
843
4.375
4
# Indexing and slicing new_list = [0, 1, 2, 3] print(new_list[1]) print(new_list[1:3]) print(new_list[:2]) print(new_list[2:]) print() # Adding, removing, and updating movies = ['Blindspoting', 'Black Panther', 'Annihilation'] movies[0] = 'Blindspotting' movies.append('Sorry to Bother You') # Adds item to end of list movies.insert(1, 'Won\'t You Be My Neighbour') # Adds item to list at index movies.remove('Annihilation') print(movies) # More list methods new_list.insert(1, True) # Lists can hold any type of data new_list.extend([1, 2, 3]) print(new_list) new_list.reverse() print(new_list) print(new_list.count(1)) # Remember, 1 == True new_list.sort() print(new_list) # Nested lists can be used for matrices matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix[1][0] = 1000 print(matrix)
true
4f178dff917a43db7f7c2c8df934092ec657c654
ariannedee/intro-to-python
/Problems/Solutions/problem_3_temperature_converter.py
286
4.15625
4
""" Given a temperature in Fahrenheit, return the temperature in Celsius """ # Ask for a temperature in Fahrenheit temp_in_f = float(input('Temp in F: ')) # Calculate it in Celsius temp_in_c = (temp_in_f - 32) * 5/9 # Tell the user what it is print('Temp in C: {}'.format(temp_in_c))
true
c405d545a6d027e726027331d411c1a47ade8658
etrzupek23/All-Python-Programming
/rps.py
1,775
4.4375
4
""" This program is a rock paper scissors game where the user will play against computer. User will select rock, paper or scissors. The computer will randomly select rock, paper or scissors. Rock beats scissor, paper beats rock, scissors beats paper. Written by the Wonderful, Amazing Introduction to Programming and Hardware class. November 12, 2019 """ from random import randint from time import sleep options = ["R","P","S"] loserSkSkSk = "sksks and I oops, you lose!!!! BOOOOOO" winnerOwO = "OwO You won! Yay! You're very lucky! Woohooo! Very cool thank you! " # function that decides winner def decidethewinner(userChoice, computerChoice): print("You selected %s. " % userChoice) print("The computer is selecting...") sleep(1) print("The computer selected: " + computerChoice) # determine index of userchoice userChoiceIndex = options.index(userChoice) computerChoiceIndex = options.index(computerChoice) # rules that determine a winner use if userChoiceIndex == computerChoiceIndex: print ("It's a tie!") elif userChoiceIndex == 0 and computerChoiceIndex == 2: print(winnerOwO) elif userChoiceIndex == 1 and computerChoiceIndex == 0: print(winnerOwO) elif userChoiceIndex == 2 and computerChoiceIndex == 1: print(winnerOwO) elif userChoiceIndex > 2: print ("--ERROR--") else: print (loserSkSkSk) # function that starts and plays the game def playRPS(): print ("Welcome to the game of Rock, Paper, Scissors by your favorite block 3 class introduction to computer science class! :P") userChoice = input("Choose R for rock, P for paper or S for scissors: ") sleep(1) userChoice = userChoice.upper() computerChoice = options[randint(0,len(options)-1)] decidethewinner(userChoice, computerChoice) playRPS()
true
fd978ef83d704658a49bedd923a2c50533355a82
riceh3/Tic-Tac-Toe-Segments-
/menu- instructions.py
865
4.21875
4
# Game Menu - Hannah print(" Tic Tac Toe") name = input("Hey whats your name?") #takes user name and asigns to player one print("Hi there, " + name + " have you played this game before") confirm = input("type yes or no") # Instruction Menu if confirm == "no": print ("Not to worry here are the instruction") print(" The Game will ask you to select a box on the grid, where you want to place your 'x' or '0'") print(" A guid of the grid will appear at the start of the game") print(" You will then enter your 'x' or '0', and it will place the mark") print("The aim of the game, is to get your mark to fill three boxes in a row") yes = "yes" for y in yes: if confirm == "yes": continue else: print("Lets Play") # Then instructions will only show if the user selects that they have not # - playerd the game before
true
37128e931074b939a2e004629a6b8170de4dc7f4
midquan/classwork
/classwork/cmps140/p0/buyLotsOfFruit.py
1,449
4.25
4
#!/usr/bin/env python3 """ Based off of: http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html To run this script, type: python3 buyLotsOfFruit.py Once you have correctly implemented the buyLotsOfFruit function, the script should produce the output: Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25 """ FRUIT_PRICES = { 'apples': 2.00, 'oranges': 1.50, 'pears': 1.75, 'limes': 0.75, 'strawberries': 1.00 } def buyLotsOfFruit(orderList): """ orderList: List of (fruit, weight) tuples Returns cost of order """ # *** Your Code Here *** cost = 0.0 # for fruit in orderList: # if(fruit[0] == 'apples'): # cost += 2.00 * fruit[1] # elif(fruit[0] == 'oranges'): # cost += 1.50 * fruit[1] # elif(fruit[0] == 'pears'): # cost += 1.75 * fruit[1] # elif(fruit[0] == 'limes'): # cost += .75 * fruit[1] # elif(fruit[0] == 'strawberries'): # cost += 1.00 * fruit[1] # else: # print("Invalid fruit entered") # return None for (fruit, quantity) in orderList: cost += FRUIT_PRICES[fruit] * quantity return cost def main(): orderList = [ ('apples', 2.0), ('pears', 3.0), ('limes', 4.0) ] print("Cost of %s is %s." % (orderList, buyLotsOfFruit(orderList))) if __name__ == '__main__': main()
true
dba50637df5523910d688cca395b177006ba590e
diwashchhetri/Python_Basics---Flow_Control
/Python - Flow Control/continue_break.py
583
4.3125
4
# The continue break statement # The break statement terminates the current loop and resumes the execution at the next statement (just like in C). aString = 'I Love Python Programming' print('The Full Statement: ', aString) for i in aString: if i == 'm': break print(i) print('\n') print('Finished.') # The continue statement in Python returns the control to the beginning of the while loop. var = 5 while var > 0: var = var - 1 if var == 2: continue print('Variable: ',var) print('\n') print('Finished')
true
4f7af9c35eacac879704404b9e09e91ad6216678
onatkaya/Hackerrank
/Python (Practise)/Find Angle MBC.py
554
4.15625
4
import math degree_sign= u'\N{DEGREE SIGN}' side_1 = int(input()) # side AB side_2 = int(input()) # side BC long_side = math.sqrt(pow(side_1,2) + pow(side_2,2)) # finding the long side of the triangle, side AC side_3 = long_side / 2 # side AM = MC = BM # finding the cosine (cos) value of our angle cos_val = (side_2) / (long_side) # finding the angle in radian using acos acos_val = math.acos(cos_val) # turning the radian value to angle format and printing it final_degree = round(math.degrees(acos_val)) print(str(final_degree) + degree_sign)
false
8651d64287fcb2976d1ac6f50c7939f80d68f515
Jay47k/scikit-image
/doc/examples/color_exposure/plot_rgb_to_hsv.py
2,360
4.25
4
""" ========== RGB to HSV ========== This example illustrates how RGB to HSV (Hue, Saturation, Value) conversion [1]_ can be used to facilitate segmentation processes. Usually, objects in images have distinct colors (hues) and luminosities, so that these features can be used to separate different areas of the image. In the RGB representation the hue and the luminosity are expressed as a linear combination of the R,G,B channels, whereas they correspond to single channels of the HSV image (the Hue and the Value channels). A simple segmentation of the image can then be effectively performed by a mere thresholding of the HSV channels. .. [1] https://en.wikipedia.org/wiki/HSL_and_HSV """ import matplotlib.pyplot as plt from skimage import data from skimage.color import rgb2hsv ############################################################################## # We first load the RGB image and extract the Hue and Value channels: rgb_img = data.coffee() hsv_img = rgb2hsv(rgb_img) hue_img = hsv_img[:, :, 0] value_img = hsv_img[:, :, 2] fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(8, 2)) ax0.imshow(rgb_img) ax0.set_title("RGB image") ax0.axis('off') ax1.imshow(hue_img, cmap='hsv') ax1.set_title("Hue channel") ax1.axis('off') ax2.imshow(value_img) ax2.set_title("Value channel") ax2.axis('off') fig.tight_layout() ############################################################################## # We then set a threshold on the Hue channel to separate the cup from the # background: hue_threshold = 0.04 binary_img = hue_img > hue_threshold fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(8, 3)) ax0.hist(hue_img.ravel(), 512) ax0.set_title("Histogram of the Hue channel with threshold") ax0.axvline(x=hue_threshold, color='r', linestyle='dashed', linewidth=2) ax0.set_xbound(0, 0.12) ax1.imshow(binary_img) ax1.set_title("Hue-thresholded image") ax1.axis('off') fig.tight_layout() ############################################################################## # We finally perform an additional thresholding on the Value channel to partly # remove the shadow of the cup: fig, ax0 = plt.subplots(figsize=(4, 3)) value_threshold = 0.10 binary_img = (hue_img > hue_threshold) | (value_img < value_threshold) ax0.imshow(binary_img) ax0.set_title("Hue and value thresholded image") ax0.axis('off') fig.tight_layout() plt.show()
true
680dd36055377a1285dbcddbc13388c0ead1bea1
shaik882/execrises
/exercise_13.py
838
4.15625
4
# Assume a suitable value for distance between two sites (in KMs). Write a Program to convert and print this distance # into meters, Feet, Inches and Centimeters import math print('This Program is to convert KM to meters, feets and centimeters') print('written by warlord') City1 = input("What is the name of the start city>>> ") City2 = input("What is the name of the destination city>>> ") x = int(input("Enter the distance in KM>>>")) print("The distance between", City1, "and", City2, "is", x, "KM") y = x * 1000 print("The distance between", City1, "and", City2, "is", y, "Meters") z = x * 3280 print("The distance between", City1, "and", City2, "is", z, "Feet") a = x * 39370 print("The distance between", City1, "and", City2, "is", a, "Inches") b = x * 100000 print("The distance between", City1, "and", City2, "is", b, "Inches")
true
8774b14884e7715e4679a1527fc5f482b2d48684
shaik882/execrises
/exercise_14.py
579
4.21875
4
# Assume a suitable value for temperature of a city in Fahrenheit degrees. Write a program to convert this # tempature into centigrade degrees and print both temperatures import math print("This program is to convert fahrenheit degrees to centigrade degress") print("Written by Warlord") City_Name = input("Enter the City Name >>>") Fahrenheit_Degrees = int(input("Enter the tempature>>>")) print("Current Tempature of", City_Name, "is", Fahrenheit_Degrees, "F") Centigrade_Degrees = Fahrenheit_Degrees - 32 print("Current Tempature of", City_Name, "is", Centigrade_Degrees, "C")
true
bfb02d182640b639a5d5dca6fddd63f181af9a48
Z-Gomes/python_bootcamp
/python_bootcamp/chapter_8/defining functions.py
752
4.34375
4
# a function is a block of code designed to do a specific job # use def at beginning of function to store a block of code to 'call' later def greet_user(): """Display a simple greeting message.""" # """ triple quotations contain docstrings, which describe the purpose of a function, and python searches for these """ print('Hello!') greet_user() # you can pass information into a function inside its () by defining what is inside the () def greet_user(username): """Display a simple greeting message, including a name""" print(f"Hello, {username.title()}, how are you?") greet_user('jesse') # each time you call the function greet_user, python expects you will input some value for username each time
true
dcaffbbd08b80760912a06eb2a4fe825a393dc10
Z-Gomes/python_bootcamp
/python_bootcamp/chapter_3/changing_lists.py
2,107
4.5625
5
#Lists can be modified up and down. To change an element, refer to the element in the list and tell python what you want the new value to be motorcyles = ['honda', 'suzuki', 'yamaha'] motorcyles motorcyles[0] = 'ducati' #this changes the 'honda' to become 'ducati' because it is in position 0 #you can add elements to a list by using the append() method motorcyles.append('honda') motorcyles motorcyles.append('bmw') motorcyles #you can add any new items into the middle of a list using the insert() method and specifying the index of the new element and the value of the new item motorcyles.insert(0,'ducati') motorcyles #you can remove an item from a list using the del statement, if you know the index of the item you want to remove del motorcyles[0] motorcyles #the pop() method allows you to remove the last item in a list but still work with that item after removing it #an example of use of pop() would be when you want to get the x and y position of a target that was shot down and removed from your list, and you want to add an explosion there motorcyles = ['honda','ducati','bmw'] popped_motorcyles=motorcyles.pop() motorcyles print(f"the last motorcyle I owned was a {popped_motorcyles.title()}.") #you can use pop() to remove any item from any position in the list by using its index inside the parentheses motorcyles=['honda','suzuki','bmw'] popped_motorcyles = motorcyles.pop(0) popped_motorcyles # deciding between the del statement and pop() is based on whether you don't need to use that deleted item for anything, then use del; if you need it or data tied to it, use pop() #if you don't know the index of the item you want to remove from your list, but do know what it's called, you can remove with the remove() method motorcyles=['honda','ducati','suzuki','bmw'] motorcyles.remove('ducati') motorcyles #you can also use remove() to work with a value or variable that's being removed from a list motorcyles=['honda','ducati','suzuki','bmw'] too_expensive = 'ducati' motorcyles.remove(too_expensive) motorcyles
true
cd37cf6a3542afcb1cc5dd3ea16d07fbb5062406
Z-Gomes/python_bootcamp
/python_bootcamp/chapter_6/nesting.py
2,051
4.5625
5
# you can store multiple dictionaries in a list or a list of items as a value, which is called nesting # multiple TVG team dictionaries made into a list TVG_1 = {'name': 'basement josh', 'game':'poker'} TVG_2 = {'name': 'xiaowei', 'game':'slots'} TVG_3 = {'name': 'jyoti','game': 'roulette'} TVG_team = [TVG_1, TVG_2, TVG_3] for person in TVG_team: print(person) # creating multiple dictionaries inside the list with code to generate them automatically # use range() to say how many new items to add FDS_team = [] for FDS_member in range(30): new_member = {'name':'cyborg Jay', 'game':'baccarat'} FDS_team.append(new_member) # show first 5 new team members for new_member in FDS_team: print(new_member) TVG_team.append(FDS_team) # show how many total new team members were added print(f"Total number of FDS team members: {len(FDS_team)}") # put a list inside a dictionary pizza = { 'crust':'thick', 'toppings':['mushrooms','pineapple','pepperoni'], } print(f"You ordered a {pizza['crust']}-crust pizza\nWith the following toppings:") for topping in pizza['toppings']: print(f"\t{topping.title()}") # you can nest a list inside a dictionary any time you want more than one value to be associated with a key favorite_foods = { 'basement josh':['pizza','hot dogs'], 'upstairs josh':['guacamole','burrito'], 'xiaowei':['barbecue','pasta'], 'jyoti':['chitlins','bloody rare steak'], 'zach':['dumplings','pasta'] } for name, foods in favorite_foods.items(): print(f"\n{name.title()}'s favorite foods are:") for food in foods: print(f"{food.title()}") # you can nest a dictionary inside another dictionary team = { 'jsauder':{ 'first':'basement', 'last':'josh', 'location':'his basement', }, 'jshankar':{ 'first':'jyoti', 'last':'shankar', 'location':'everywhere', }, } for name,info in team.items(): print(f"\n{info['first']} {info['last']}")
false
b1e248a551309d461daa9e06f0d71cd7939cb130
adrianjengel/IS211_Assignment4
/sort_compare.py
2,509
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """WK4 Assignment Part II - Using search and sort algorithms.""" import time import random def insertion_sort(a_list): """Insertion list sort function.""" start = time.time() for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position - 1] > current_value: a_list[position] = a_list[position - 1] position = position - 1 a_list[position] = current_value end = time.time() return end-start, a_list def gap_insertion_sort(a_list, start, gap): """Gap inserstion sort function.""" for i in range(start + gap, len(a_list), gap): current_value = a_list[i] position = i while position >= gap and a_list[position - gap] > current_value: a_list[position] = a_list[position - gap] position = position - gap a_list[position] = current_value def shell_sort(a_list): """Shell list sort function.""" start = time.time() sublist_count = len(a_list) // 2 while sublist_count > 0: for start_position in range(sublist_count): gap_insertion_sort(a_list, start_position, sublist_count) sublist_count = sublist_count // 2 end = time.time() return end-start, a_list def python_sort(a_list): """Builtin list sort function.""" start = time.time() a_list = a_list.sort() end = time.time() return end-start, a_list def random_list(length): """A random list generator.""" randlist = [] for item in range(length): randlist.append(random.randint(1,length)) return randlist def main(): """The main function that runs tests upon calling the program.""" test_numbers = [500,1000,10000] for items in test_numbers: counter = 100 result = [0,0,0] while counter > 0: randlist = random_list(items) result[0] += insertion_sort(randlist)[0] result[1] += shell_sort(randlist)[0] result[2] += python_sort(randlist)[0] counter -= 1 print "For the list of {}... ".format(items) print "Insertion Sort took %10.7f seconds to run, on average" % (result[0] / 100) print "Shell Sort " + "took %10.7f seconds to run, on average" % (result[1] / 100) print "Python Sort " + "took %10.7f seconds to run, on average" % (result[2] / 100) if __name__ == "__main__": main()
false
0d1c3fca908d6fa841e3719d21e6ccacfbc5c955
Pierre-siddall/CA2-programming-assessment
/CA2/ex2.py
1,268
4.21875
4
def email_addresses(first: list, last: list, domain: str = '@exeter.ac.uk') -> list: """ This function takes two list arguments first and last , and a string argument domain that has a default value of @exeter.ac.uk. The function then returns a list of suggested email addesses with the email addresses in the format of the first letter of the name in first followed by a full stop followed by the whole of the corresponding name from last, followed by the domain""" suggested_emails = [] # Here error checking is handled if type(first) != list or type(last) != list or type(domain) != str or domain[0] != '@': print('One or more parameters have been passed incorrectly. Firstly parse two lists then parse a string beginning with a @ sign') return None elif len(first) > len(last) or len(last) > len(first): print('Please make sure each list has a corresponding first and last name') return None for index in range(len(first)): # a string called new email is formed by concatenating the nesscary parts together new_email = first[index][0].lower()+'.'+last[index].lower()+domain suggested_emails.append(new_email) return suggested_emails
true
b2d0163df03a2534d0ee713947fd5cadfc451eaf
bsobocki/PythonCourseUWR
/LIST5-iterators-generators-list-comprehension/task2.py
1,962
4.125
4
import itertools as it def m_print(solutions): print('\n{ ', solutions[0]) for i in range(1, len(solutions)): print(solutions[i]) print('}\n') def is_correct(solution, a1, a2, a3): # generators b1 = (str(solution[elem]) for elem in a1) b2 = (str(solution[elem]) for elem in a2) b3 = (str(solution[elem]) for elem in a3) # create string and convert to int number1 = int(''.join(b1)) number2 = int(''.join(b2)) number3 = int(''.join(b3)) return number1 + number2 == number3 def cryptarithm(str1, str2, str3): a1, a2, a3 = list(str1), list(str2), list(str3) letters = list(set(str1 + str2 + str3)) digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] solutions = [] solutions += [str1+' + '+str2+' = '+str3] # permutations of digits with len = len(letters) for perm in it.permutations(digits, len(letters)): # we must create a new solution for each iteration # else we give to solutions a reference # to the one created solution at the beggining, # which may will be changed in next iterations solution = {} # letters are ordered in 'letters' variable, # so it is enough to connect i-th element from perm with i-th letter # to get a new permutation of both sets for i in range(0, len(letters)): solution[letters[i]] = perm[i] if is_correct(solution, a1, a2, a3): solutions += [solution] return solutions # A + B = C --> there are a lot solutions m_print(cryptarithm("A","B","C")) # e.g 12 + 14 = 26 # AB + AC = BD m_print(cryptarithm("AB", "AC", "BD")) # KIOTO + OSAKA = TOKIO -> one solution m_print(cryptarithm("KIOTO", "OSAKA", "TOKIO")) # AAA + AAA = CAA --> there's no solutions m_print(cryptarithm("AAA","AAA","CAA")) # MOM + DAD = KIDS --> there are a lot solutions m_print(cryptarithm("MOM","DAD","KIDS"))
true
5207f919953a0545b5a3573103db856f1dd376a3
sagordon-dev/russian-peasant-multiplication
/rpm.py
1,144
4.25
4
# rpm.py # This program uses the "Russian Peasant Multiplication" algorithm # to solve for multiplication through binary expansion. # (See rpm.md for a full explaination) # by: Scott Gordon import math import pandas as pd def main(): print('***** Russian Peasant Multiplication *****') def rpm(): print('Input two comma separated numbers (x, y): ') input_str = input('> ') inputs = input_str.split(',') n1, n2 = int(inputs[0]), int(inputs[1]) halving = [n1] while(min(halving) > 1): halving.append(math.floor(min(halving)/2)) doubling = [n2] while(len(doubling) < len(halving)): doubling.append(max(doubling) * 2) half_double = pd.DataFrame(zip(halving,doubling)) rpm_out = half_double.to_markdown() print('\n*** RPM Table ***') print(f'{rpm_out}\n') # requires tabulate to display output as md half_double = half_double.loc[half_double[0]%2 == 1,:] answer = sum(half_double.loc[:,1]) print(f'The solution to your problem is {answer}\n') rpm() if __name__=='__main__': main()
true
ff2b5bd25d3c450bfbcdbab67d3b94557586a01d
MrBiggles87/Python
/while2.py
288
4.59375
5
"""The below is a while loop that goes through values 1-20, the "IF" statement checks each value to see if its even/odd. IF the value is even, the value is printed, else the printed number is odd""" a=1 while a<=20: if a%2==0: print(a," Is Even") else: print(a," Is Odd") a+=1
true
93ff38c76d0a928063bd4c69845a9d27d2232c23
BhuvaneshAkash/RockPaperScissors
/main.py
1,125
4.3125
4
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' import random #user choice game_choice = [rock , paper , scissors] user_choice = int(input("choose 0 for rock for paper 1 for scissors 2 :")) print(game_choice[user_choice]) #opponent choice (coumpter's choice) computer_choice = random.randint(0,2) print(game_choice[computer_choice]) if user_choice>=3 or user_choice<0: print("You are typed an Wrong number\n \n YOU LOSE \n ") elif computer_choice ==0 and user_choice ==2: print("You Lose") elif user_choice==0 and computer_choice ==2: print("you win") elif user_choice == 0 and computer_choice ==1 : print("You win") elif computer_choice == 0 and user_choice == 1: print("you lose") elif user_choice ==1 and computer_choice == 2: print("you lose") elif computer_choice ==1 and user_choice ==2: print("you win") else : print("draw")
false
3128af99d0d0d777b1ecfde29b2c61ca51498fc5
hudefeng719/uband-python-s1
/homeworks/B21052/checkin08/day10-homework-1.py
1,287
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: caramel def homework2(): dictionary = {'abandon':'to give up to the control or influence of another person or agent', 'abase':'to lower in rank, office, prestige, or esteem', 'abash':'to destroy the self-possession or self-confidence of' } who = 'father' print 'One day, %s was reading an Englsih book while a dictionary with only three words was besides him.' % (who) print '%s found a unknown word, etiquette, then he looked it up in that dictionary.' % (who) if dictionary.has_key('etiquette'): print dictionary['etiqutte'] #没有这个单词则不执行此操作 else: print 'He did not found it in the dictionary.' # if not dictionary.has_key('etiquette'): 没有查到 # print 'He did not found it in the dictionary.' #撕毁了abandon这一页 del dictionary['abandon'] print "%s got angry, then he teared off that page with the word %s on." % (who,'abandon') if dictionary.has_key('abase'): print '%s found %s: %s' % (who, 'abase', dictionary['abase']) dictionary['abandon'] = 'to give up to the control or influence of another person or agent' print '%s felt happy and pasted back that page with the word %s on' % (who,'abandon') if __name__ == '__main__': homework2()
true
6894138838a649565cdda481cf22d8baa4166e08
hudefeng719/uband-python-s1
/homeworks/A10397/week1/Day06/day06-homework 1.py
669
4.125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: Tangxiaocu def main(): # 1 2 3 4 5 lst = ['大白菜', '空心菜', '花菜', '生姜', '小龙虾'] #列表 # 循环访问 for lst_item in lst: #遍历 print '老妈看到了 %s ' % (lst_item) # 记录下标 index = 0 for lst_item in lst: #遍历 print '老妈看到了 %s ' % (lst_item) print '当前第 %d 个' % (index) index = index + 1 # 迭代访问 for index, lst_item in enumerate(lst): print '老妈看到了 %s ' % (lst_item) print '当前第 %d 个' % (index) #取值 #长度 #加 #删除 #切片 if __name__ == '__main__': main()
false
45f9ae62c8975a768a0b58e2486f956287179c1b
hudefeng719/uband-python-s1
/homeworks/A13191/checkin01/day2-homework.py
1,933
4.25
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: Guoshushu # Day2 - 为了大家能够做好这一次的第一个作业 # 继续深化变量的练习 # # homework2 def main(): #01.int apple_number = 5 apple_price = 4.8 pie_number = 6 pie_price = 6.7 #02. * / apple_total_price = apple_number * apple_price pie_total_price = pie_number * pie_price #03. try to explain what's float print 'pie cost %d ' % (pie_total_price) print 'pie cost %g ' % (pie_total_price) print 'pie cost %0.2f ' % (pie_total_price) #04. ** number = 2**3 print 'number = %d' % (number) #05. what else? # 在 python简明教程中找到第 34 页,然后搞懂所有的符号~ # 每个符号在限免测试一下 除了 << >> ^ ~ 几个不用理解,之后会讲 # 不用理解优先级,只用记住一句:括号里面的最先计算 #如: print 'test: %d' % (1 != 2) print 'test: %d' % (1 >= 2) if 1: print 'goog' if 0: print 'xxx' if(2 != 2): print 'wweewe we w' #请开始你的表演 var1 = 1 var2 = 2 var3 = 3 var4 = 4 var5 = var1 + var2 var6 = var3 - var4 var7 = var1 * var3 var8 = var4 / var2 var9 = var4 // var3 var10 = 5 var11 = var10 % var3 print 'I am %d, %d, %d, %d, %d and %d, lol.' % (var5, var6, var7, var8, var9, var11) var12 = var9 << 1 var13 = var10 >> 3 var14 = 1 & 2 var15 = 1 | 2 var16 = 1 ^ 2 var17 = ~ 2 print 'I am %d, %d, %d, %d, %d and %d, hhhhhh.' % (var12, var13, var14, var15, var16, var17) if(2 < 3): print "I love python." else: print "I don't learn anymore." print "test a bunch of operators: %d, %d, %d, %d, %d" % (2 > 3, 2 <= 3, 2 >= 3, 2 == 3, 2 != 3) var18 = True var19 = False var20 = not var18 var21 = var18 and var19 var22 = var18 or var19 print 'Ich bin %d, %d und %d, hahaha.' % (var20, var21, var22) if __name__ == '__main__': main()
false
e2bbeaad540bc528dc085e7a9791d3842348f1be
monrasmu/Cracking-the-Coding-Interview
/Chapter 2/2-3.py
457
4.21875
4
# Implement an algorithm to delete a node; you are only # given access to that node from LinkedList import LinkedList def delete_middle_node(middle_node): # Replaces value at node with next middle_node.value = middle_node.next.value # Move us one forward middle_node.next = middle_node.next.next ll = LinkedList() ll.add_multiple([1, 2, 3, 4]) middle_node = ll.add(5) ll.add_multiple([7, 8, 9]) print(ll) delete_middle_node(middle_node) print(ll)
true
5fa567a63825043cec064a919dc2998f5f6d2460
CarlosAntonioITSZ/Curso-Python
/EstructurasDeControl/Exercise2.py
634
4.1875
4
#Exercise2 ''' Algorithm that asks for three numbers and the ordered examples (from highest to lowest); ''' #@CarlosAntonio print(" ") one=int(input("Enter a number: ")) two=int(input("Enter a number: ")) three=int(input("Enter a number: ")) print("") if one > two and one > three: if two > three: print(one, two, three) else: print(one, three, two) elif two > one and two > three: if one > three: print(two, one, three) else: print(two, three, one) elif three > one and three >two: if one > two: print(three, one, two) else: print (three, two, one) print(" ")
false
44e84ec2ac0497dcbfea9fe942b0b79f749352e4
CarlosAntonioITSZ/Curso-Python
/Funciones/Exercise3.py
664
4.28125
4
#Exercise1 ''' Create a “calculate MaxMin” function that receives a list with numerical values ​​and returns the maximum and minimum value. Create a program that asks for numbers by keyboard and displays the maximum and minimum, using the previous function. ''' #@CarlosAntonio list=[] for i in range(0,10): while True: try: element=int(input(f"Enter a number {i}: ")) list.append(element) break except: print("Enter a number") def calculateMaxMin(list): list.sort() print("Minimum: ",list[0]) print("Maximum: ",list[len(list)-1]) calculateMaxMin(list)
true
8605ac9dfec5afbcf903050ad50c4f6d460b3a55
CarlosAntonioITSZ/Curso-Python
/Listas/Exercise4.py
624
4.25
4
#Exercise4 ''' Design the algorithm corresponding to a program, which: Create a table (list with two dimensions) of 5x5 integers. Load the table with integer numerical values. Add all the elements of each row and all the elements of each column displaying the results on the screen. ''' #@CarlosAntonio list=[[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]] sumRow=0 sumColumn=0 for row in range(0,5): for column in range(0,5): sumRow+=list[row][column] sumColumn+=list[column][row] print("") print(list) print("") print(sumRow) print(sumColumn)
true
701022e3a0e8426db660feb878f2277114a9372f
CarlosAntonioITSZ/Curso-Python
/POO/Exercise1.py
1,400
4.25
4
#Exercise1 ''' We are going to create a class called Person. Its attributes are: name, age and ID. Build the following methods for the class: A constructor, where the data may be empty. The setters and getters for each of the attributes. You have to validate the data entries. show (): Shows the person's data. esMayorDeEdad (): Returns a logical value indicating if it is of legal age. ''' #@CarlosAntonio class Person(): def __init__(self,name,age,dni): self.__name=name self.__age=age self.__dni=dni def getName(self): return self.__name def setName(self,name): self.__name=name def getAge(self): return self.__age def setAge(self,age): self.__age=age def getDni(self): return self.__dni def setDni(self,dni): self.__dni=dni def show(self): print("----------------------------") print("Name: ",self.__name,"\nAge: ",self.__age,"\nDni: ",self.__dni) print("----------------------------") def isOlder(self): if self.__age>=18: return True else: return False p1=Person("Carlos",20,"AOJ12330CJAL") try: p1.setAge(g) except NameError: print("Try again") p1.show() print(p1.isOlder()) print("") p2=Person("Juan",16,"ASFDJ12330CJAL") p2.setAge(17) p2.show() print(p2.isOlder())
true