blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e513f09bf73469113daea7df461cb0a51265eb25
udoy382/PyCode
/udoy_022.py
1,111
4.53125
5
# Recursions: Recursive Vs iterative Approach #34 # n! = n * n-1 * n-2 * n-3......1 # n! = n * (n-1)! # recursive work method. """ 5 * factroial_recursive(4) 5 * 4 * factroial_recursive(3) 5 * 4 * 3 * factroial_recursive(2) 5 * 4 * 3 * 2 * factroial_recursive(1) 5 * 4 * 3 * 2 * 1 = 120 """ ''' def factroial_iterative(n): """ :param n: Integer :return: n*n-1 * n-2 * n-3......1 """ fac = 1 for i in range(n): fac = fac * (i+1) return fac def factroial_recursive(n): """ :param n: Integer :return: n*n-1 * n-2 * n-3......1 """ if n==1: return 1 else: return n * factroial_recursive(n-1) number = int(input("Enter the number\n")) print("Factorial Using Iterative Method:", factroial_iterative(number)) print("Factorial Using Recursive Method:", factroial_iterative(number)) ''' # Quiz... # fibonacci: 0 1 1 2 3 5 8 13 """ def fibonacci(n): if n==1: return 0 elif n==2: return 1 else: return fibonacci(n-1) + fibonacci(n-2) number = int(input("Enter the number\n")) print(fibonacci(number)) """
false
c8567acd9810d3eeba65797cf6818b1085183e96
udoy382/PyCode
/udoy_012.py
1,442
4.40625
4
# Operators In Python #21 # Operators in Python. # Arithmetic Operators # Assignnment Operators # Comparison Operators # Logical Operators # Indetity Operators # Itemsship Operators # Bitwaise Operators # Arithmetic Operators... # print("5 + 6 is ", 5 + 6) # print("5 - 6 is ", 5 - 6) # print("5 * 6 is ", 5 * 6) # print("5 ** 3 is ", 5 ** 3) # print("5 / 6 is ", 5 / 6) # print("5 % 3 is ", 5 % 3) # print("15 // 6 is ", 15 // 6) # Assignnment Operators... # x = 5 # print(x) # # x +=7 # # x /=7 # # x -=7 # # x %=7 # print(x) # search on google [Assignnment Operators] # Comparison Operators... i = 5 # print(i == 5) # print(i != 5) # print(i <= 5) # print(i >= 5) # print(i <= 5) # print(i and 5) # Logical Operators... a = True b = False # print(a and a) # True and True = True # print(a and b) # True and False = False # print(a or b) # True or False = True # Identity Operators... # print(a is b) # print(a is not b) # print(5 is not 7) # print(9 is 4) # print(5 is not 5) # Itemsship Operators... lst = [3, 3, 2, 45, 65, 76, 54, 65, 3, 98, 1, 2, 35] # print(32 in lst) # print(320 in lst) # print(320 not in lst) # Bitwaise Operators... # binary digit. # 0 - 00 # 1 - 01 # 2 - 10 # 3 - 11 # [0+0 = 0], [0+1 = 0], [00] = 0 # print(0 and 1) # [ | this meen or ] [0 or 0 = 0], [0 or 1 = 1], [01] = 1 # print(0 | 1) # [0 or 1 = 1], [0 or 1 = 1], [11] = 3 # print(0 | 3) # search on google [Bitwaise Operators]
false
56ab994254b3b1de4c46198dd4067152d1c0b8b9
udoy382/PyCode
/udoy_013.py
240
4.15625
4
# Short Hand If Else Notation In Python #22 a = int(input("enter a\n")) b = int(input("enter b\n")) # 1st # if a>b: print("A B se bada hai bhai") # 2nd # print("B A se bada hai bhai") if a<b else print("A B se bada hai bhai")
false
2d5b50af96b89121b11fb49eb6b8250ceae053b6
udoy382/PyCode
/udoy_017.py
729
4.28125
4
# Open(), Read(), & Readline() For Reading File #26 # open file using [f], then insert txt file name then insert momde. f = open("udoy_1.txt", "rt") # redlines function use for all lines shows without newline like this [\n]. print(f.readlines()) # redline function use for print one by one line. # print(f.readline()) # print(f.readline()) # print(f.readline()) # if im insert f.read(3), so print only 3 careture. # content = f.read() # print like this, it is a true way to print line by line txt. """ for line in f: print(line, end="") """ # print(content) # same line can't print. # content = f.read(36655) # print("2", content) # if im open file so mustly close file f.close()
true
74ea4821c76670d08cf6e30986ae55ac1e4c4518
endarli/SummerImmersionProjects
/DataAnalysis/DictAttac.py
974
4.3125
4
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dict.txt","r") print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password #NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords test_password = input("Type in a trial password: ") #Write logic to see if the password is in the dictionary file below here: isitin = False while test_password in f(read): isitin = True if isitin == True: print("Your password would not survive a dictionary attack! Be careful!") break if isitin == False: print("Yay, your password would survive a dictionary attack!") #another way for word in f: if word == test_password.split().lower(): print("Your passwword would not survive!") else: print("Your password would survive!")
true
0bc2775528c0ef07b9a04d7ac1647515de51e5a1
SmithWenge/pythonTest
/迭代0615/test1.py
298
4.34375
4
d = {'a': 1, 'b': 2, 'c': 3} #对于字典的迭代 默认迭代的是key,如果迭代value或者是key和value的话看下边的示例 for x in d: print(x) #迭代字典的value,用到values()函数 for x in d.values(): print(x) #迭代字典的key和value for x in d.items(): print(x)
false
d017edaa077234107b268ec1119a0e723a66670c
aalaapn/2200
/labs/example.py
669
4.28125
4
"""Examples illustrating the use of plt.subplots(). This function creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created. For very refined tuning of subplot creation, you can still use add_subplot() directly on a new figure. """ import matplotlib.pyplot as plt import numpy as np # Simple data to display in various forms t=np.arange(0,10) x = np.cos(2*np.pi*t) y = np.exp(t*(-.9))*np.cos(2*np.pi*t) plt.close('all') # Just a figure and one subplot f, (ax1, ax2) = plt.subplots(1,2,sharey=False) ax1.plot(t, y) ax2.plot(t,x) ax1.set_title('C.1.') ax2.set_title('C.2.') plt.show()
true
e3a1eb5b88a56cb532ef2a7e28e3cca31199a322
djmar33/python_work
/ex/ex7/mountain_poll.py
872
4.21875
4
#7.3.3使用用户输入来填充字典 #创建一个空字典,将存储用户、及喜欢那座山; responses = {} #创建一个标志; polling_active = True while polling_active: #获取用户名字; name = input("\nWhat is your name?") #获取用户喜欢的山; response = input("Whitch mountain would you like to climb someday?") #将信息写入列表里; responses[name] = response #询问用户是否还继续调查,如果否将退出调查; repeat = input("Would you like to let another person respond?(yes/no)") if repeat == 'no': #标志赋值为False,将退出循环; polling_active = False print("\n----Poll Results ----\n") #遍历字典,输出用户和用户喜欢的山; for name, response in responses.items(): print(name + " would like to climb " + response + ".")
false
23a50c165b0e8e54416040f0a950e2d216ec4f3e
djmar33/python_work
/ex/ex4/ex4.3.2.py
637
4.28125
4
#4.3.2 创建数字列表 number = list(range(1,5)) print(number) #指定步长,生成10以下的偶数列表 number = list(range(2,11,2)) print(number) #创建1~10的平方 #创建一个空列表,便于等下存储平方数结果; squares = [] #使用for循环,遍历1-11(就是1-10) for value in range(1,11): #求value的平方值,并且赋值给square square = value ** 2 #将每个计算平方的值square,添加到squares列表中 squares.append(square) #输出列表 print(squares) #更简洁计算1~10平方数 squares = [] for value in range(1,11): squares.append(value ** 2) print(squares)
false
785d72046704857c144cedd8149f87e2311392a7
djmar33/python_work
/ex/ex8/8.3.2-1.py
674
4.34375
4
#8.3.2-1让实参变成可选的 #将middle_name中间名指定一个默认值; def get_formatted_name(first_name, last_name, middle_name=''): """返回整洁的姓名""" #python中非空字符串解读为true,判断中间名是否为空,如果不是将把中间名字段加上; if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name #如果中间名为空,全名将不会包含中间名; else: full_name = first_name + ' ' + last_name #将full_name的值返回 return full_name.title() #将函数返回值复赋值给musician变量; musician = get_formatted_name('jimi', 'hendrix',) print(musician)
false
9eb793424de18c04bf93ef1d23d96a8a385d5423
BrunoLSA/DojoPuzzles
/analisando_a_conjectura_de_collatz.py
1,540
4.21875
4
""" Para definir uma seqüência a partir de um número inteiro o positivo, temos as seguintes regras: n → n/2 (n é par) n → 3n + 1 (n é ímpar) Usando a regra acima e iniciando com o número 13, geramos a seguinte seqüência: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Podemos ver que esta seqüência (iniciando em 13 e terminando em 1) contém 10 termos. Embora ainda não tenha sido provado (este problema é conhecido como Problema de Collatz), sabemos que com qualquer número que você começar, a seqüência resultante chega no número 1 em algum momento. Desenvolva um programa que descubra qual o número inicial entre 1 e 1 milhão que produz a maior seqüência. """ def next_(n): '''Return the next number for the sequence.''' return (3 * n + 1) if n % 2 else (n // 2) def seq(n): '''Generator to produce a complete sequence from n.''' yield n while n > 1: n = next_(n) yield n def count(iterable): '''Return how many elements has an iterable.''' return sum(1 for _ in iterable) def max_length(start=1, stop=1000001): '''Returns the number and length of the longest sequence.''' length, number = max((count(seq(n)), n) for n in range(start, stop)) return number, length # Tests assert next_(1) == 4 assert next_(2) == 1 assert next_(13) == 40 assert list(seq(13)) == [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] assert count(seq(13)) == 10 assert max_length(1, 14) == (9, 20) # number 9, length 20 print(max_length(start=1, stop=1000001))
false
57ab0785a8b8652b4d03bf7a61e4abc7a0058680
KaduMelo/pyqgis
/python/4_operators.py
704
4.375
4
x = 3 y = 3 # Python Arithmetic Operators # + Addition print(x + y) # - Subtraction print(x - y) # * Multiplication print(x * y) # / Division print(x / y) # % Modulus print(x % y) print(5 % 2) # ** Exponentiation x = 2 y = 5 print(x ** y) #same as 2*2*2*2*2 # // Floor division x = 24 y = 8 print(x // y) # Python Comparison Operators # Equal print(x == y) # Not Equal print(x != y) # Greater than print(x > y) # Less than print(x < y) # Greater than or equal to print(x >= y) # Less than or equal to print(x <= y) # Python Logical Operators # and print(x < 5 and x < 10) # and print(not(x < 5 and x < 10)) # Python Identity Operators # is print(x is y) # is not print(x is not y)
true
9444f0e0782b9b87450a5db1bd4f541ba8869480
KaduMelo/pyqgis
/python/9_if_else.py
303
4.21875
4
# Equals: a == b # Not Equals: a != b # Less than: a < b # Less than or equal to: a <= b # Greater than: a > b # Greater than or equal to: a >= b a = 33 b = 200 if b > a: print("b is greater than a") # Identation # a = 33 # b = 200 # if b > a: # print("b is greater than a") # you will get an error
false
61e1ea004d977d1f3f5eb4eb7b8715ba956d5178
ReneNyffenegger/about-python
/builtin-functions/enumerate/demo.py
237
4.15625
4
someList = ['foo', 'bar', 'baz'] enumeratedList = enumerate(someList) print (type(enumeratedList)) # <class 'enumerate'> for index, element in enumeratedList: print("{:d}: {:s}".format(index, element) ) # 0: foo # 1: bar # 2: baz
false
522536e07d1059201373bb10c040b50b2c1e7b6a
ReneNyffenegger/about-python
/standard-library/json/script.py
475
4.1875
4
import json # # Reading json data from a string # d = json.loads (''' { "foo":{ "42":"forty-two", "8" :"eight" }, "bar":[ {"key":"1"}, {"key":"2"}, {"key":"3"}, {"key":"4"} ] } ''') print(d['foo']['42']) # forty-two # ------------------------------- # # Reading json data from a file # json_file=open('file.json') f=json.load(json_file) print(f[2][1]) # Yes print(f[3]['foo']) # word
false
77c594af91c708cde916cbe4b5ee27326cd6f19d
santospat-ti/Python_ExEstruturaSequencial
/lojatintas.py
669
4.125
4
#Faça um programa para uma loja de tintas. # O programa deverá pedir o tamanho em metros # quadrados da área a ser pintada. Considere que a # cobertura da tinta é de 1 litro para cada 3 metros # quadrados e que a tinta é vendida em latas de # 18 litros, que custam R$ 80,00. # Informe ao usuário a quantidades de latas de tinta # a serem compradas e o preço total. print('='*3, 'Loja de Tintas', '=' * 3) a = int(input('Valor em metros da área: ')) litros = a / 3 preço = 80.0 capacidadeL = 18 latas = litros / capacidadeL total = latas * preço print(f'Serão {latas:.2f} latas de tinta.') print(f'E o valor será de R$ {total:.2f}.')
false
bdb2d706571e73da4e03bb112579b6dbc5c2c865
jmartin103/CaesarCipher
/CaesarCipher2.py
2,955
4.5625
5
# This is a program to find the key for an encrypted text file, based on the most common letters. This is used to find the key # for the file, and then use the key to decrypt the file, and then write the decrypted text to an output file. from collections import Counter # Used to count the number of occurrences of each letter import string letters = string.ascii_lowercase # Array to store lowercase letters specChars = string.punctuation # Special characters # Find key for decryption def findKey(cipher): mostCommonIndex = 4 # Index of the most common letter 'e' distDict = findLetterDist(cipher) # Find the letter distribution for cipher text commLetter = sorted(distDict, key = distDict.get, reverse = True) # Sort by most common letter key = letters.find(commLetter[0].lower()) - mostCommonIndex # Find key based on most common letter in file return key # Find the letter distribution for the cipher text def findLetterDist(cipher): distDict = {} # Create empty dictionary for cipher distribution for letter in cipher: # Read through cipher text if letter in specChars or letter == ' ': # Letter is either a special character or a space continue if letter not in distDict: # Letter is not in distribution dictionary distDict[letter] = 1 else: distDict[letter] += 1 return distDict # Main method def main(): f_input = input('File Name: ') # Prompt user for input file text = open(f_input, 'r').read().lower().strip() # Open input file and convert each letter to lowercase outText = open('decrypted_caesar.txt', 'w') # Output file where plaintext will be written textLen = int(len(text)) # Get length of input text file # Read through input file, and count the occurrences of each letter with open(f_input, 'r') as f: distDict = Counter(letter for line in f for letter in line.lower() if letter in letters) print(distDict) # Print letter frequencies key = findKey(text) # Key of text print("Key: " + str(key)) # Print key plain = "" # This string will hold the plaintext # Read through input file for i in range(textLen): if text[i].isalpha(): # Symbol is a letter i = letters.find(text[i]) # Map letter in file to letter in array j = (i - key) % 26 # Subtract the key from the index of the letter, and use modulo 26 else: # Symbol is not a letter plain += text[i] # Append symbol to plaintext string continue decrypted = letters[j] # Decrypted letter plain += decrypted # Append decrypted letter to plaintext print(plain) # Plaintext # Write decrypted plaintext to output file with outText as f: f.write(plain) main() # Call main method
true
f30f7e53ef640cd2cb52d05c220db9521617e39c
AndrewKirklandWright/Learn_Python
/Ex810.py
654
4.3125
4
"""Exercise 8.10. A string slice can take a third index that specifies the “step size;” that is, the number of spaces between successive characters. A step size of 2 means every other character; 3 means every third, etc. >>> fruit = 'banana' >>> fruit[0:5:2] 'bnn' A step size of -1 goes through the word backwards, so the slice [::-1] generates a reversed string. Use this idiom to write a one-line version of is_palindrome from Exercise 6.6.""" def is_pal(word) : if word == word[::-1] : print("Yes, this is a palendrome.") else : print("No,this is not a palendrome.") word = input("Enter the word: ") is_pal(word)
true
8f24903333883d4324114f57a3f26bc519699a6d
zizzberg/pands-problem-set
/solution-4.py
435
4.21875
4
#step one if current value of n is positive divide it by 2 - if it is odd - #multiply by 3 and add 1 - if 1 end program n = int(input("Input a positive integer: ")) #while loops repeat code but don't run n time - only until a condition is met while n != 1: print(n) if n % 2 == 0: #even n = n / 2 else: n = n * 3 n = n + 1 print("1") # prints 1 at the end outside of loop to end program.
true
8f54776b4bb7ca618633d25488fe61059deac651
Steven-Wright1/Python-Educational-Codes
/if-elif statements.py
467
4.4375
4
# read three numbers number1 = int(input("Enter the first number: ")) number2 = int(input("Enter the second number: ")) number3 = int(input("Enter the third number: ")) # We temporarily assume that the first number # is the largest one. # We will verify this soon. largest_number = number1 if number2 > number1: largest_number = number2 elif number3 > largest_number: largest_number = number3 print("The largest number is", largest_number, end="\n")
true
03db6bbb60d35fea7ae560f0485d2c87493fcee4
Steven-Wright1/Python-Educational-Codes
/DictionariesAdvanced.py
684
4.46875
4
#In a real dictionary, you look up a word and find a meaning #In a python dictionary (or map), you look up a key, and find a value Eg_Dictionary = {"pi":3.14 , 25:"The square of 5" , "Vitthal":"A name"} # Value Lookup print("The value for key, pi, is", Eg_Dictionary["pi"]) print(Eg_Dictionary.keys()) print(Eg_Dictionary.values()) print(len(Eg_Dictionary.keys())) # CHECK IF KEYS ARE IN THE DICTIONARY. IF SO, REMOVE Key_to_Delete = input("Please enter the key you would like to remove ") if Key_to_Delete in Eg_Dictionary: Eg_Dictionary.pop(Key_to_Delete) print("The key-value pair for", Key_to_Delete, "has been removed") print(Eg_Dictionary)
true
3ddd9f6646bc78248740d348b86397a6b2cbcdef
NaNdalal-dev/pyrepo
/boolean_algebra/Associative_law.py
1,497
4.125
4
''' Associative law: A+(B+C)=(A+B)+c A.(B.C)=(A.B).c ''' print('Program to prove Associative law ') A=int(input('Enter the boolean value for A(1/0):')) if(A==0 or A==1): B=int(input('Enter the boolean value for B(1/0):')) if(B==0 or B==1): C=int(input('Enter the boolean value for C(1/0):')) if(C==0 or C==1): print('\npress 1 to prove A+(B+C)=(A+B)+c operation') print('press 2 to prove A.(B.C)=(A.B).c operation') exp=int(input('My choice :')) if(exp==1 or exp==2): print('\nValue of A:',A) print('Value of B:',B) print('Value of C:',C) if((A==1 or B==1 or A==0 or B==0 or C==1 or C==0)and exp==1): print('\nA+(B+C) =',(A or(B or C))) print('(A+B)+C =',((A or B) or C)) if((A or(B or C))==((A or B) or C)): print('A+(B+C)==(A+B)+C') print('Therefore Associative law satisfied') else: print('A+(B+C)!=(A+B)+C') print('Therefore Associative law not satisfied') elif((A==1 or B==1 or A==0 or B==0 or C==1 or C==0)and exp==2): print('\nA.(B.C) =',(A and(B and C))) print('(A.B).C =',((A and B) and C)) if((A and(B and C))==((A and B) and C)): print('A.(B.C)==(A.B).C') print('Therefore Associative law is satisfied') else: print('A.(B.C)!=(A.B).C') print('Therefore Associative law not satisfied') else: print('Invalid choice for operation') else: print(C,' is invalid option') else: print(B,' is invalid option') else: print(A,' is invalid option')
false
cb9825acfd2c335fd104893b1374bb3fb1e0844c
tomki1/mergesort-insertionsort
/insertsort.py
1,248
4.25
4
# insertsort.py # name: Kimberly Tom # CS325 Homework 1 # insertSort with help from https://www.geeksforgeeks.org/insertion-sort/ #open a file for reading and open a file for writing data_file = open("data.txt", "r") insert_file = open("insert.txt", "w") def insertSort(integer_array): # for each number in the array for y in range(1, len(integer_array)): key = integer_array[y] # while the element is greater than the key, move one position forward x = y - 1 while x >= 0 and key < integer_array[x]: integer_array[x + 1] = integer_array[x] x = x - 1 integer_array[x + 1] = key # for each line in the data file # with help from https://stackoverflow.com/questions/3122121/python-how-to-read-and-split-a-line-to-several-integers for line in data_file: one_line = list(map(int, line.split())) # read from the second integer to the end of the line array = one_line[1:] insertSort(array) # for each number character in the array, write to merge file for number in array: insert_file.write(str(number) + " ") # create a new line for next array insert_file.write("\n") data_file.close() insert_file.close()
true
a01e91603d048dc49c95c320a4ddad031da219c1
Hannibal404/data-structure-and-algorithms
/Arrays/maxHourGlass.py
1,469
4.125
4
# This python3 script accepts a nxn two dimensional matrix # and calculates the maximum hourglass sum possible from it. ''' Example: In this 6x6 Matrix: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 1 1 2 The pattern: 1 1 1 0 1 0 1 1 1 makes 1 hour glass. And the sum of this hour glass is: 1 + 1 + 1 + 1 + 1 + 1 + 1 = 7 Similarly we need to find sum of all hourglasses in the Matrix And print the maximum sum. ''' #Taking rank of the matrix from user n = int(input()) l = [] #Converting each string of row values into list and appending it to The #main two dimensional list 'l' for i in range(n): il = list(map(int, input().split())) l.append(il) #This will store our expected result finalSum = 0 #Creating a 3x3 grid index to iterate over the two dimensional list And #calculate sum of the hourglasses. #-2 is added to make sure not to index beyond the actual list range. for r1 in range(n-2): r2 = r1+1 r3 = r2+1 for c1 in range(n-2): #to store sum of all hourglasses res = 0 c2 = c1+1 c3 = c2+1 res = l[r1][c1] + l[r1][c2] + l[r1][c3] + l[r2][c2] + l[r3][c1] + l[r3][c2] + l[r3][c3] #Maybe the first element is -ve, therefore need to store it no matter what. if r1 == 0 and c1 == 0: finalSum = res #will always store the maximum result if res > finalSum: finalSum = res #print the maximum hourglass sum. print(finalSum)
true
186eb5bf60d983e8dd86c1fb60c7ea3c950fea4d
MikkelBoisen/OddName_SandBox
/OddNamePt2.py
477
4.125
4
""" write a program that asks the user for their name and has error-checking to make sure it's not blank. Then print every second letter in the name. Hint: use a for loop, the range function, and the length of the name. """ def main(): name = get_name() name_1 = name[1::2] print(name_1) def get_name(): name = input("Enter your name") if not name: print("You did not enter a name") else: print("Hello", name) return name main()
true
1d769e62ab0d359b49e02ec01d02686d7380aa86
bfss/ss-python-code
/18-读取与写入/reader.py
268
4.1875
4
# 逐行读取 with open('file.txt') as file_object: for line in file_object: print(line) # 将文件的每一行存入列表 with open("file.txt") as file_object: lines = file_object.readlines() print(type(lines)) for line in lines: print(line)
false
34816e3830572070815a4f70bca69871ab8f4fb8
Fravieror/Python
/try_catch.py
810
4.15625
4
# File error # with open("a_file.txt") as file: try: file = open("a_file.txt") a_dictionary = {"key": "value"} value = a_dictionary["non_existent_key"] except FileNotFoundError: # Create file from scratch file = open("a_file.txt", "w") file.write("Something") # error_message catch the name of variable that cause the error except KeyError as error_message: print(f"The key {error_message} error getting ") # else is executed when does not exists exception else: content = file.read() print(content) finally: file.close() # Kinds of errors # # Key error # a_dictionary = {"key": "value"} # value = a_dictionary["non_existent_key"] # # # IndexError # fruit_list = ["Apple", "Banana", "Pear"] # fruit = fruit_list[3] # # # Type error # text = "abc" # print(text + 5)
true
f700ec6aa376b0c8bb0ca3573843a822deed2008
gammernut/examples_for_gavin
/example_3_data_types.py
1,205
4.125
4
# examples for gavin # strings , ints , floats and other data types # Python has multiple Data Types: # # Integers/int are whole numbers ie. 1 , 2 , 3 so on # # Floating-Point Numbers/float basically a int with with a decimal point ie 1.3 , 1.5 , 2.8 , 3.1 so on # # String/str Strings are sequences of character data ie. text between 'hello world' "hello world" # # Boolean may have one of two values, True or False ie 'good' in 'this is a great example' returns false # Boolean cont. 'good' not in 'this is a great example' returns true # # Complex Numbers Complex numbers are specified as <real part>+<imaginary part>j ie. 2+3j # str_1 = 'hello ' str_2 = 'world' int_1 = 1 int_2 = 2 print(str_1+str_2) # adding two strings together is called string concatenation print(int_1+int_2) print(str_1+int_1) # errors out because you cant combine a str and int # The str() function changes the specified value into a string converted_int_1 = str(int_1) # we take the converted variable int_1 and store it in a new variable to work with later # The int() function changes the specified value into an integer print(str_1+converted_int_1) # now it works since the converted_int_1 is a string
true
bd5538f144e4beff66c97f558275899b64119634
KlwntSingh/inwk-python
/lab2/task10.py
433
4.28125
4
def check_fermat(a, b, c, n): if n <= 2: print "give n greater than 2" return leftSide=a**n + b**n rightSide=c**n if a > 0 and b > 0 and c > 0 and leftSide != rightSide: print("No, that doesn't work") else: print("Holy smokes, Fermat was wrong!") a=int(raw_input("First number i.e a ")) b=int(raw_input("Second number i.e b ")) c=int(raw_input("third number i.e c ")) n=int(raw_input("n ")) check_fermat(a,b,c,n)
true
e3705e5d2a86f16b7d00ebaa83cd36f0d03aac7c
KlwntSingh/inwk-python
/lab2/task11.py
231
4.21875
4
def is_triangle(a, b, c): if a + b >= c and b + c >= a and c + a >= b: print "Yes" else: print("No") a=int(raw_input("First side: ")) b=int(raw_input("Second side: ")) c=int(raw_input("Third side: ")) is_triangle(a, b, c)
false
9ecbd36f8882e44edd90a870151fd529eda944e0
RafaelMarinheiro/CS5220-MatMul
/lecture/lec01plot.py
1,498
4.125
4
import matplotlib.pyplot as plt import numpy as np def make_speedup_plot(n, rmax, tc, tt): """Plots speedup for student counting exercise. Plots the speedup for counting a class of students in parallel by rows (assuming each row has equal student counts) vs just counting the students. Args: n: Number of students in the class rmax: Maximum number of rows to consider tc: Time to count one student tt: Time to add a row count into a tally """ r = np.arange(1,rmax+1) ts = n*tc tp = ts/r + r*tt speedup = ts/tp plt.plot(r, speedup) plt.xlabel('Number of rows') plt.ylabel('Speedup') def make_speedup_file(fname, n, rmax, tc, tt): """Plots speedup for student counting exercise. This is exactly like make_speedup_plot, but instead of generating a plot directly, we generate a data file to be read by pgfplots. Args: fname: Output file name n: Number of students in the class rmax: Maximum number of rows to consider tc: Time to count one student tt: Time to add a row count into a tally """ ts = n*tc with open(fname, 'w') as f: for r in range(1,rmax+1): tp = ts/r + r*tt f.write('%d %g\n' % (r, ts/tp)) if __name__ == "__main__": n = 100 rmax = 12 tc = 0.5 tt = 3 make_speedup_file('lec01plot.dat', n, rmax, tc, tt) make_speedup_plot(n, rmax, tc, tt) plt.savefig('lec01plot.pdf')
true
eeae3dfac1c156a1c374cb0596517bde7d2471ae
bluerain109/Python_Tutorials
/Comments and Break.py
1,227
4.4375
4
#break and continue can be put inside of a loop magicNumber = 25 #Find the magic number game (goes through 100 to see if our number is the magic number) for n in range(101): if n is magicNumber: print(n, "is the magic number!") #this makes the current number n display as the magic number if it is the magic number #break stops the loop once the number or solution is found break else: print(n) #We just reviewed a decision inside of a loop #for adding notes that the computer will not execute, use hashtag for a single line, use 3 double or single quotes ''' this is a comment #this is also a comment #to concatenate a string, you add strings together print("Duck" + "Cat") #to print a number along with a string, you have to use a comma to separate them print("bucky",9) ''' #if you take a number and divide it by 4 and what you have left is 0, the (%) modulus sign is the remainder (if something is left after an uneven division) ''' 12%4 ''' #this would be 0 because there is nothing left in decimal format as 3 goes into 12 #you can work on both sides of anything ''' for n in range(101): if n%4 is 0: print(n, "is a multiple of 4!") else: print(n) '''
true
350e4ecd35179f173aed3da8e61a2dd41ae60f0b
bluerain109/Python_Tutorials
/Sets.py
409
4.21875
4
#a set is a collection of items like a list, except it cannot have any duplicates curly brackets are used groceries = {'cereal', 'milk','starcrunch','beer','duct tape','lotion','beer'} print(groceries) #because of no allowed duplicates in a set, beer will not appear twice if 'milk' in groceries: print('you already have milk! No more is needed at the moment.') else: print('You are out of milk.') #
true
f879d36eed6e41458c105abea43527e7dac0178c
carinasauter/D09
/presidents.py
2,453
4.375
4
#!/usr/bin/env python3 # Exercise: Presidents # Write a program to: # (1) Load the data from presidents.txt into a dictionary. # (2) Print the years the greatest and least number of presidents were alive. # (between 1732 and 2016 (inclusive)) # Ex. # 'least = 2015' # 'John Doe' # 'most = 2015' # 'John Doe, Jane Doe, John Adams, and Jane Adams' # Bonus: Confirm there are no ties. If there is a tie print like so: # Ex. # 'least = 1900, 2013-2015' # 'John Doe (1900)' # 'Jane Doe (2013-2015)' # 'most = 1900-1934, 2013' # 'John Doe, Jane Doe, John Adams, and Jane Adams (1900-1933)' # 'Sally Doe, Billy Doe, Mary Doe, and Cary Doe (1934)' # 'Alice Doe, Bob Doe, Zane Doe, and Yi Do (2013)' ############################################################################## # Imports # Body def get_dict_of_pres(): dictionary_of_presidents = {} with open("presidents.txt", "r") as doc: text = doc.readlines() for line in text: line = line.strip().split(",") dictionary_of_presidents[line[0]] = (line[1], line[2]) return dictionary_of_presidents def earliest_year_of_birth(d): min = 2016 for president in d: if min > int(d[president][0]): min = int(d[president][0]) return min def new_dict_of_pres(d): new_dict_of_pres = {} for x in range(earliest_year_of_birth(get_dict_of_pres()), 2017): number_of_presidents_alive = 0 alives = [] for president in d: if x >= int(d[president][0]): try: if x <= int((d[president][1])): number_of_presidents_alive += 1 alives.append(president) except: if (d[president][1]) == "None": number_of_presidents_alive += 1 alives.append(president) new_dict_of_pres[x] = (number_of_presidents_alive, alives) print(new_dict_of_pres) return new_dict_of_pres #print ("{}: {} alive ".format(x, number_of_presidents_alive) + str(alives)) ############################################################################## def main(): # CALL YOUR FUNCTION BELOW new_dict = new_dict_of_pres(get_dict_of_pres()) sorted(new_dict, key=) # no idea how to sort this by the first value of the tuple value pair in # the dictionary now :( ### if __name__ == '__main__': main()
true
917a149f97dd6484cd345c96f1c82c8130a58bd2
haegray/Python-and-Java-Files
/cashregister.py
679
4.28125
4
#cashregister.py #This program is designed to calculate and display sales price which is #list price plus a 5.3% sales tax. def cashregister(): print("Please input the list price of the item you would like to purchase.") listPrice=eval(input("price: ")) salesPrice= (listPrice + (.053 * listPrice)) print("The total cost is", salesPrice) cashregister() #IOP: #Please input the list price of the item you would like to purchase. #price: 1.50 #The total cost is 1.5795 #>>> ================================ RESTART ================================ #>> #Please input the list price of the item you would like to purchase. #price: .99 #The total cost is 1.04247
true
9ea360a4d2d43d3a32f457ce24a96fefe2d1100e
jvindas-ust/Python
/Arrays.py
434
4.34375
4
#Changing several elements in the Array-List [FromIndex:QuantityOfElements]: l5 = [2, "tres", True, ["uno", 10], 6] l5[0:2] = [4, 3] print (l5) #Modify several elements in the Array-List with just one data [FromIndex:QuantityOfElements]: l6 = [2, "tres", True, ["uno", 10], 6] l6[0:2] = [5] print (l6) #Get data from an array with negative index: l6 = [2, "tres", True, ["uno", 10], 6] l7 = l6[-1] l8 = l6[-2] print (l7) print (l8)
true
f5db01e43fed9b19497b5bc0dfd87431bc6e02e1
azrazra0628/python_practice
/1日1件/リスト/リスト(配列)に要素を追加するappend, extend, insert.py
2,872
4.125
4
## リスト(配列)に要素を追加するappend, extend, insert # list型のリスト(配列)に要素を追加したり別のリストを結合したりするには、 # リストのメソッドappend(), extend(), insert()を使う。 # そのほか、+演算子やスライスで位置を指定して代入する方法もある。 #1. 末尾に要素を追加: append() # リストのメソッドappend()で、末尾(最後)に要素を追加できる。 #%% l = list(range(3)) print(l) # [0, 1, 2] print(l.append(100)) # None print(l) # [0, 1, 2, 100] # リストもひとつの要素として追加される。結合はされない。 #%% l.append([1,2,3]) print(l) # [0, 1, 2, 100, [1, 2, 3]] #2. 末尾に別のリストやタプルを結合(連結): extend() # リストのメソッドextend()で、 # 末尾(最後)に別のリストやタプルを結合できる。 # すべての要素が元のリストの末尾に追加される。 #%% l = list(range(3)) print(l) # [0, 1, 2] l.extend([100, 101, 102]) print(l) # [0, 1, 2, 100, 101, 102] l.extend((-1, -2, -3)) print(l) # [0, 1, 2, 100, 101, 102, -1, -2, -3] # 文字列は各文字(要素)が一文字ずつ追加されるので注意。 #%% l.extend('new') print(l) # [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w'] # +演算子の場合は新たなリストが返される。 # +=で既存のリストに追加することもできる。 #%% l += (5,6,7) print(l) # #3. 指定位置に要素を追加(挿入): insert() # リストのメソッドinsert()で、指定した位置に要素を追加(挿入)できる。 # 第一引数に位置、第二引数に挿入する要素を指定する。 # 先頭(最初)は0。負の値の場合、-1が末尾(最後)の一つ前となる。 #%% l = list(range(3)) print(l) l.insert(0, 100) print(l) # [100, 0, 1, 2] l.insert(-1, 200) print(l) # [100, 0, 1, 200, 2] # append()と同じく、リストもひとつの要素として追加される。結合はされない。 #%% l.insert(0,[1, 2, 3]) print(l) # [[1, 2, 3], 100, 0, 1, 200, 2] #4. 指定位置に別のリストやタプルを追加(挿入): スライスを使う # スライスで範囲を指定して # 別のリストやタプルを代入すると、すべての要素が追加(挿入)される。 #%% l = list(range(3)) print(l) # [0, 1, 2] l[1:1] = [100, 200, 300] print(l) # [0, 100, 200, 300, 1, 2] # 元の要素を置換することもできる。指定した範囲の要素がすべて置き換えられる #%% l = list(range(3)) print(l) # [0, 1, 2] l[1:2] = [100, 200, 300] print(l) # [0, 100, 200, 300, 2] # まとめ # ①要素の追加には、append(),insert(),extend()メソッドを使用する # ②append()とinsert()はリストの追加は1つの要素として扱われる為、注意が必要
false
579db91ceddd799c2e7373c2dcefdc02627f006f
Oskaryeeto69/Miniraknare
/Miniräknare.py
2,313
4.1875
4
def add(x, y): # hittade detta på google för att göra det lättare att skriva return x + y # hittade detta på google för att göra det lättare att skriva def subtract(x, y): # hittade detta på google för att göra det lättare att skriva return x - y def multiply(x, y): # hittade detta på google för att göra det lättare att skriva return x * y räknetyp = str(input('Tjabba å välkommen till den goa miniräknarn (klicka enter för att gå vidare)')) # välkomnar dig till miniräknaren print('Välj ett räknesätt.') # frågar vilket räknesätt du vill använda eller om du vill avsluta print('1. Räkna med addition') # säger att 1 är addition print('2. Räkna med subtraktion') # säger att 2 är subtraktion print('3. Räkna med multiplikation') # säger att 3 är multiplikation print('4. För att avsluta') # säger att 4 avslutar programmet while True: val = input('Välj vilket räknesätt du vill använda eller om du vill avsluta (1 , 2, 3, 4) ') # ber dig välja räknesätt if val in('1', '2', '3', '4'): # säger att om valet är if val == '1': num1 = float(input("Vad är första nummret: ")) # frågar vad första nummret är num2 = float(input("Vad är andra nummret: ")) # frågar vad andra nummret är print ('Summan av', num1, '+', num2, '=', add (num1, num2)) # printar svaret av de två talen du skrev elif val == '2': num1 = float(input("Vad är första nummret: ")) # frågar vad första nummret är num2 = float(input("Vad är andra nummeret: ")) # frågar vad andra nummret är print ('Differensen av', num1, '-', num2, '=', subtract (num1, num2)) # printar differensen av de två talen du skrev elif val == '3': num1 = float(input("Vad är första nummret: ")) # frågar vad första nummret är num2 = float(input("Vad är andra nummeret: ")) # frågar vad andra nummret är print ('Produkten av', num1, '*', num2, '=', multiply (num1, num2)) # printar produkten av de två talen u skrev elif val == '4': print('Vad tråkigt att du inte ville räkna nå mer :(') # Detta printas när du klickar 4, när du avslutar alltså break else: print("helt fel tänkt där")
false
48ab31f3b7e4af27eb724a28ddf9a8203c813092
jurikolo/la-intro-to-python
/oop/classes.py
550
4.25
4
print("Docs: https://docs.python.org/3/tutorial/classes.html#classes") class Car: """ Docstring describing the class """ def __init__(self, color, transmission): """ Docstring describing the method """ self.color = color self.transmission = transmission def description(self): """ Describes the Car object :return: """ print(f"Car has {self.color} color and {self.transmission} speeds") jk_car = Car("red", [1, 2, 3, 4, 5, 6]) jk_car.description()
true
4102794e661b1fa27bcda77b6b0bce53c8d39e78
adeckert23/python-problems
/algorithms/binary_search.py
492
4.3125
4
def binary_search(sorted_list, target): ''' Function to binary search a sorted list of ints for a target int. Returns index of the target if found in list, otherwise returns False. ''' l = 0 r = len(sorted_list) while l <= r: mid = (l+r) // 2 if sorted_list[mid] == target: return mid else: if sorted_list[mid] > target: r = mid - 1 else: l = mid + 1 return False
true
6087f2390bfdb50cc83927a15b6d0e188fada5a4
Ishkhan2002/ENGS110-2021-Homeworks
/GradedHomework1.py
760
4.125
4
def Is_Prime(Number): Check = 0 i = 2 while(i <= Number//2): if(Number % i == 0): Check = Check + 1 break i = i + 1 if(Check == 0 and Number != 1): print("%d is a prime number" %Number) return Number else: print("%d is not a prime number"%Number) return False def main(): Number = int(input("Please enter your number:")) Is_Prime(Number) F1 = 0 F2 = 1 F3 = 0 Sum = 0 while F3 + F1 < Number: F3 = F1 + F2 Sum = Sum +F3 F1 = F2 F2 = F3 if(1 <= Sum): OverallSum = bin(Sum + 1)[2 : ] print("Overall Sum is %s " %OverallSum) else: print("The input is not correct") main()
true
f598e6b3c1b2dd6ee97f75f7b2225593ef59b09e
mvillaloboz/learnPython
/ex3.py
960
4.625
5
# display that we are about to count chickens print "I will now count my chickens:" # displaying our Hens, then Roosters print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 # display the fact that we are about the count the eggs print "Now I will count the eggs:" # calculate the amount of eggs print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # display the formula that we are about to check print "Is it true that 3 + 2 < 5 - 7?" # calculate our formula print 3 + 2 < 5 - 7 # providing the elements of our formula broken down print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 # display the statement regarding what we learned about our formula print "Oh, that's why it's False." # display that we are going to try some more less than and greater than statements print "How about some more." # calculate these different statements print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
f947d431d899051a22acecbb6be3964485276555
ashwinitangade/PythonProgramming
/PythonAss1/7.py
954
4.3125
4
#Create a list with at least 10 elements having integer values in it;
       Print all elements
       Perform slicing operations
       Perform repetition with * operator
       Perform concatenation with other list. myList = ['one', 2, 3.14, [1,'two',(2017,2018)], ('python', 'hello')] print('the elements in list are',myList) print('\niterating through the elements in list') for item in myList: print(item) #slicing print('\nThe first item in list is: ',myList[0]) print('\nThe elements at start index 1, step 0 and endindex 5 are: ',myList[1:5]) print('\nThe elements at start index -2, step -1 and endindex 2 are: ',myList[-2:-5:-1]) #repetition myList2 = ['^']*3 print('\nthe new list with items repeated [\'^\'] 3 times is:',myList2) #concatenation myList3 = ['Hello', 'I', 'love', 'Python', 'programming'] newList = myList2 + myList3 print('\nThe concatenation of string myList2 and myList3 is:',newList)
true
4dfa6d6dc22d7a6a828eb5179b233d1b2e4d1c91
ashwinitangade/PythonProgramming
/PythonAss1/1.py
713
4.25
4
#Write a program to Add, Subtract, Multiply, and Divide 2 numbers def myadd(x, y): return x + y def mysub(x, y): return x - y def mymul(x, y): return x * y def mydivide(x, y): return x / y num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: ")) print("Enter which operation would you like to perform?") op = input("Enter any of these char for specific operation +,-,*,/: ") result = 0 if op == '+': result = myadd(num1,num2) elif op == '-': result = mysub(num1,num2) elif op == '*': result = mymul(num1,num2) elif op == '/': result = mydivide(num1,num2) else: print("Input character is not recognized!") print(num1, op , num2, ":", result)
true
f466ebbbb9ce58328f860c0bea23d659fcc7540d
nrepesh/Richter-Coin-Blockchain-
/Assignments/assignment3.py
1,332
4.125
4
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. persons = [{ 'name':'Batman', 'age':21, 'hobby': 'MMA' }, { 'name': 'Spiderman', 'age': 19, 'hobby': 'Slinghshot' }, { 'name':'Superman', 'age':65, 'hobby': 'Fly' } ] # 2) Use a list comprehension to convert this list of persons into a list of names (of the persons). names = [x['name'] for x in persons] print(names) # 3) Use a list comprehension to check whether all persons are older than 20. ages_older =all([a['age'] > 20 for a in persons]) print(ages_older) # 4) Copy the person list such that you can safely edit the name of the first person (without changing the original list). copied_persons = [x.copy() for x in persons] #[:] wont deep copt it copied_persons[0]['name'] = 'Joker' print(copied_persons) print(persons) # 5) Unpack the persons of the original list into different variables and output these variables. name = '' age = '' hobby = '' for each in persons: for (k,v) in each.items(): if k == 'name': name = name + ' ' + v elif k == 'age': age = age + ' ' + str(v) else: hobby = hobby + ' ' +v print('Names:{}, Ages:{}, Hobbies:{}'.format(name,age,hobby))
true
b6e1cd53a50ef29f26ce7746961821c2b7d0d489
LIAOTINGFENG/jc538239
/prac_01/prac_01/menu.py
444
4.15625
4
userName=str(input("Enter name: ")) print("(H)ello"+'\n'+"(G)oodbye"+'\n'+"(Q)uit"+'\n') menuChoice=str.upper(input()) while not(menuChoice=="Q" ): if menuChoice=="H": print(f'Hello {userName}') elif menuChoice=="G": print(f'Goodbye {userName}') else: print("Invalid choice") print("(H)ello" + '\n' + "(G)oodbye" + '\n' + "(Q)uit" + '\n') menuChoose = str.upper(input()) print("Finished")
false
374191152187785a1bd06c2cf2dd9d1735b3a63c
ymanzi/42bootcamp_machine_learning
/module06/ex10/minmax.py
538
4.1875
4
import numpy as np def minmax(x): """Computes the normalized version of a non-empty numpy.ndarray using the min-max standardization. Args: x: has to be an numpy.ndarray, a vector. Returns: x' as a numpy.ndarray. None if x is a non-empty numpy.ndarray. Raises: This function shouldn't raise any Exception. """ array_min = min(x) array_max = max(x) diff_max_min = array_max - array_min f = lambda x: (x - array_min) / diff_max_min return np.array(list(map(f, x))) X = np.array([2, 14, -13, 5, 12, 4, -19]) print(minmax(X))
true
d0b2d74d0e6ce10cd17770161733a573911fcb48
ymanzi/42bootcamp_machine_learning
/module07/ex10/polynomial_model.py
832
4.15625
4
import numpy as np def add_polynomial_features(x: np.ndarray, power: int) -> np.ndarray: """ Add polynomial features to vector x by raising its values up to the power given in argument. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. power: has to be an int, the power up to which the components of vector x are going to be raised. Returns: The matrix of polynomial features as a numpy.ndarray, of dimension m * n, containg he polynomial feature values for all training examples. None if x is an empty numpy.ndarray. Raises: This function should not raise any Exception. """ if x.size == 0: return None copy_x = x for nb in range(2, power + 1): x = np.column_stack((x, copy_x ** nb)) return x x = np.arange(1,6).reshape(-1, 1) print(add_polynomial_features(x, 6))
true
fb3601858d0bca2fbdf45a95166716a8c21da6d4
Lemesg3/PythonFundamentos
/Funções/funções.py
495
4.3125
4
# Criando funções usando outras funções # Funções com número variável de argumentos def printVarInfo( arg1, *vartuple ): # Imprimindo o valor do primeiro argumento print("O parâmetro passado foi: ", arg1) # Imprimindo o valor do segundo argumento for item in vartuple: print("O parâmetro passado foi: ", item) return; # Fazendo chamada à função usando apenas 1 argumento printVarInfo(10) printVarInfo('Chocolate', 'Morango', 'Banana')
false
b6040a20c5b5ed027d882919e87606ffc64dce04
cppignite/python
/RPS/completed/RockPaperScissors.py
836
4.1875
4
user1_answer = input("Player 1, do you want to choose rock, paper or scissors?") user2_answer = input("Player 2, do you want to choose rock, paper or scissors?") if user1_answer == user2_answer: print("It's a tie! The scores weren't changed.") elif user1_answer == 'rock': if user2_answer == 'scissors': print("Player 1 wins this round!") else: print("Player 2 wins this round!") elif user1_answer == 'scissors': if user2_answer == 'paper': print("Player 1 win this round!") else: print("Player 2 wins this round!") elif user1_answer == 'paper': if user2_answer == 'rock': print("Player 1 wins this round!") else: print("Player 2 win this round!") else: print("Invalid input! You have not entered rock, paper or scissors, try again.")
true
dd03a11993a8f427edcb7e2893837ae874a5c13a
nikhilraghunathan/ICT-Full-Stack-Developer
/python/day2/inheritance.py
314
4.53125
5
#inheritance #defining class vehicle class Vehicle: type="Sedan" YoM=2000 mileage=14 #create new class Bus by inheriting class Vehicle class Bus(Vehicle): type = "Coach" YoM=2005 Mileage=6 #creating new object myBus of the new class myBus = Bus() print(myBus.type,myBus.YoM,myBus.Mileage)
true
0faf1f58b090fda2f5baa9b7b7b46362988f3b1d
standrewscollege2018/2019-year-13-classwork-A-Load-Of-c0de
/option_menu2.py
1,176
4.4375
4
# this program demonstrates how to create an option menu that tells the user which person has been selected from tkinter import * root = Tk() root.geometry('300x200') def update_label(): """ This function gets the entry field text and displays it in a label. """ label_var.set(selected_name.get() + " has been selected") # we need a list of items to display in the option menu names = ["Angus", "Toby", "Liam", "Des"] # Set up the option menu # Start by defining a variable to hold whatever is selected selected_name = StringVar() # set the initial value selected_name.set(names[0]) # Add the option menu. We need to set location, name of variabel holding selection, name of list name_menu = OptionMenu(root,selected_name, *names).grid() # a button that calls the update_label function update_button = Button(root, text="Select and press", command=update_label).grid() # label that displays what is selected by user # label_var is initially empty/No student selected so what the user chose isn' displayed until button is hit label_var = StringVar() label_var.set("No student selected") label = Label(root, textvariable=label_var).grid() root.mainloop()
true
6a138e76a852cdcd98a659a4f643c6ed35a9bc6e
standrewscollege2018/2019-year-13-classwork-A-Load-Of-c0de
/pythonrefresher.py
1,564
4.53125
5
# print() is a function print("Hello world") print(25) # variables don't have a dollar sign! # when naming we use snake_case, so no uppercase letter or symbols other than under underscore first_name = "John" last_name = "Smith" # we can print variables or even text and variables print(first_name) print("Hello", first_name) # using format() is a more elegant way of combining text and variables print("Hello {} {}".format(first_name, last_name)) # To get user input we use rhe input() function. Input should be assigned to a variable. city_of_birth = input("Where were you born {}?".format(first_name)) print("Wow! I too was born in {}!".format(city_of_birth)) # when we are expecting non-string input, we "cast" our input as a specific data type year_of_birth = int(input("What year were you born in?")) age = 2019 - year_of_birth print("That makes you appriximately {} years old".format(age)) # Lists are a way of storing more than one piece of data my_list = ["Bananas", 25, True, "Golf"] # the index of an item reers to its location in the list. It starts at zero (0). # when retrieving data from a list we pull it out by its index print(my_list[0]) # lists are mutable, meaning we can edit them after they are set # to add data to a list, we use either insert() or append() my_list.append("Table") print(my_list) my_list.insert(1, "Rinay") # go update a list item, just overwrite it my_list[1] = "Shannon" print(my_list) # to delete from a list del my_list[4] print(my_list) add = input("What is your name?") my_list.append(add) print(my_list)
true
21960188861544faff2dbc0f6aa8d4492823bbdc
henrypj/HackerRank
/Implementation/UtopianTree.py
1,036
4.28125
4
#!/bin/python3 import sys # The Utopian Tree goes through 2 cycles of growth every year. Each spring, # it doubles in height. Each summer, its height increases by 1 meter. # Laura plants a Utopian Tree sapling with a height of 1 meter at the onset # of spring. How tall will her tree be after growth cycles? # # Input Format # # The first line contains an integer, T, the number of test cases. # T subsequent lines each contain an integer, N, denoting the number of cycles # for that test case. # # Constraints # # 1 <= T <= 10 # 0 <= N <= 60 # # Output Format # # For each test case, print the height of the Utopian Tree after cycles. # Each height must be printed on a new line. t = int(input().strip()) for a0 in range(t): n = int(input().strip()) Height = 1 if n == 0: print(Height) else: for i in range(n): if i % 2 == 0: # even so double Height *= 2 else: # odd, so add 1m Height += 1 print(Height)
true
11acb550b246406213b52313c558342ae1374c77
henrypj/HackerRank
/Strings/CaesarCypher.py
2,356
4.34375
4
#!/bin/python3 import sys """ # Description # Difficulty: Easy # # Julius Caesar protected his confidential information by encrypting it in a # cipher. Caesar's cipher rotated every letter in a string by a fixed number, K, # making it unreadable by his enemies. Given a string, S, and a number, K, encrypt # S and print the resulting string. # # Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. # # Input Format # # The first line contains an integer, N, which is the length of the unencrypted # string. # The second line contains the unencrypted string, S. # The third line contains the integer encryption key, K, which is the number of # letters to rotate. # # Constraints # # 1 <= N <= 100 # 0 <= K <= 100 # S is a valid ASCII string and doesn't contain any spaces. # # Output Format # # For each test case, print the encoded string. # # Example 0 # # Given Input: # 11 # middle-Outz # 2 # # Output: # okffng-Qwvb # # Explanation: # Test Case 0 # Each unencrypted letter is replaced with the letter occurring K spaces after # it when listed alphabetically. Think of the alphabet as being both case- # sensitive and circular; if K rotates past the end of the alphabet, it loops # back to the beginning (i.e.: the letter after z is a, and the letter after Z # is A). # # Selected Examples: # m (ASCII 109) becomes o (ASCII 111). # i (ASCII 105) becomes k (ASCII 107). # - remains the same, as symbols are not encoded. # O (ASCII 79) becomes Q (ASCII 81). # z (ASCII 122) becomes b (ASCII 98); because z is the last letter of the # alphabet, a (ASCII 97) is the next letter after it in lower-case rotation. # # Solution: # """ import string n = int(input().strip()) s = input().strip() k = int(input().strip()) cypher = [] for i in range(n): if s[i] in string.ascii_lowercase: pos = string.ascii_lowercase.index(s[i]) if pos + k > 25: idx = (pos + k) % 26 else: idx = pos + k cypher.append(string.ascii_lowercase[idx]) elif s[i] in string.ascii_uppercase: pos = string.ascii_uppercase.index(s[i]) if pos + k > 25: idx = (pos + k) % 26 else: idx = pos + k cypher.append(string.ascii_uppercase[idx]) else: cypher.append(s[i]) print(''.join(cypher))
true
7ce5db7508aa1711d4da349f918c6c7c3bbbc3d9
uniqstha/PYTHON
/questions of day3/Q3.py
304
4.34375
4
#Given the integer N - the number of minutes that is passed since midnight - # how many hours and minutes are displayed on the 24h digital clock? N=int(input('Enter the no. of minutes that passed since midnight')) hr= N//60 min=N%60 print(f'{hr} hours and {min} minutes is displayed in the 24 hr clock')
true
c2105d51c4f4b6683fa9b5b438f60c387b96e272
uniqstha/PYTHON
/questions of day6/Q4.py
203
4.21875
4
#Write a Python program that print hello world 10 times. #Use for loop and while loop for i in range(10): print('Hello World') using while loop i=1 while i<=10: print ('Hello World') i=i+1
true
a0fc394751c76be6a3ea65cedfa86add43873ac0
uniqstha/PYTHON
/Functions.py
507
4.125
4
#Function in python example def add(): print('Function of add start') a = int(input('Enter first number')) b = int(input('Enter second number')) c = a + b print(f'The sum of {a} and {b} is {c}') print('Function of add ends') add() def sub(): print('Function of sub start') a = int(input('Enter first number')) b = int(input('Enter second number')) c = a - b print(f'The sub of {a} and {b} is {c}') print('Function of sub ends') sub() print('program end')
false
c121ca9fb9e58ea47a7c06d769e9fe5b6b3af32b
uniqstha/PYTHON
/questions of day2/Q5.py
233
4.4375
4
#Check whether the user input number is even or odd and display it to user. a=int(input("Enter a number")) check=a%2 if check==0: print("The given number is even") else: print('The given number is odd') print ('program end')
true
6cba118aa6688920ff839d2e74a0db88e30eff60
harkaranbrar7/30-Day-LeetCoding-Challenge
/Week 2/backspace_String_Compare.py
1,951
4.15625
4
''' Backspace String Compare Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c". Example 4: Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b". Note: 1 <= S.length <= 200 1 <= T.length <= 200 S and T only contain lowercase letters and '#' characters. Follow up: Can you solve it in O(N) time and O(1) space? ''' class Solution1: def backspaceCompare(self, S: str, T: str) -> bool: def sim(S): ans = '' for c in S: if c == '#': if len(ans) > 0: ans = ans[:-1] else: ans += c return ans return sim(S) == sim(T) class Solution2: def backspaceCompare(self, S: str, T: str) -> bool: stackS, stackT = [], [] for s in S: if s != "#": stackS.append(s) elif stackS: stackS.pop() for t in T: if t != "#": stackT.append(t) elif stackT: stackT.pop() return stackS == stackT class Solution3: def backspaceCompare(self, S: str, T: str) -> bool: ans_S = "" ans_T = "" for s in S: if s == '#': if ans_S: ans_S = ans_S[:-1] else: ans_S += s for t in T: if t == '#': if ans_T: ans_T = ans_T[:-1] else: ans_T += t return ans_S == ans_T test = Solution3() print(test.backspaceCompare("a##c","#a#c"))
true
cdf29bed6603ff19d733b244a4b6c6400afc1c5c
SandhyaKamisetty/CSPP-1
/cspp1-assignments/m6/p1/p3/p3/digit_product.py
451
4.21875
4
''' Given a number int_input, find the product of all the digits example: input: 123 output: 6 ''' def main(): ''' @author : SandhyaKamisetty Given a number int_input, find the product of all the digits Read any number from the input, store it in variable int_input. ''' n_s = 123 temp = 1 i = 0 while i < n_s: temp = temp*i i = i+1 print(temp) if __name__ == "__main__": main()
true
ea9df7d7b6e29216bea2c1f7124196332795be4d
SandhyaKamisetty/CSPP-1
/cspp1-practice/m3/iterate_even_reverse.py
207
4.59375
5
''' @author : SandhyaKamisetty The program prints even reverse using while loop ''' print('Hello!') i = 10 while i >= 2: print(i) i = i-2 print('Hello!') for A in range(10, 0, -2): print(A)
false
f36349d332dcd1e88b1a54371069a21c179f736c
SandhyaKamisetty/CSPP-1
/cspp1-assignments/m11/p2/p2/assignment2.py
1,301
4.125
4
''' #Exercise: Assignment-2 #Implement the updateHand function. Make sure this function has no side effects: i.e., it must not mutate the hand passed in. Before pasting your function definition here, be sure you've passed the appropriate tests in test_ps4a.py. ''' import copy def updatehand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... <-- Remove this comment when you code this function temp_hand = copy.deepcopy(hand) for key in word: temp_hand[key] = temp_hand[key] - 1 return temp_hand def main(): ''' @author : SandhyaKamisetty ''' num_n = input() adict = {} for i in range(int(num_n)): del i data = input() len_n = data.split() adict[len_n[0]] = int(len_n[1]) data1 = input() print(updatehand(adict, data1)) if __name__ == "__main__": main()
true
7bdfade4f03a5fffd236413dceae16a026ede50e
chemxy/MazeRunnerAI
/versions/1.1/src/Map.py
1,121
4.21875
4
from Node import Node from Object import Object, Food, Wall class Map: def __init__(self, nodeList=None): if nodeList == None: nodeList = [] self.nodeList = nodeList """ * this method returns a list of nodes in a map. """ def nodes(self): return self.nodeList """ * this method adds a new node to the map. * parameter(s): - newNode: a new node. """ def addNode(self, newNode): if newNode not in self.nodeList: self.nodeList.append(newNode) """ * this method prints the information of the map (i.e. print each node in the node list). * parameter(s): none. """ def __str__(self): response = "" for node in self.nodeList: response += "node: " + str(node) return response """ * this method """ def findPath(self, curNode, endNode): return None """ graph and find path https://www.python-course.eu/graphs_python.php https://www.python-course.eu/networkx.php https://www.python.org/doc/essays/graphs/ """
true
016ef0782abed9f6e4273294b967b22deb5ab6d7
hu820/python_proj
/data_type/list.py
1,241
4.5
4
# list [] xs = [3, 1, 2] # Create a list print(xs, xs[2]) # Prints "[3, 1, 2] 2" print(xs[-1]) # Negative indices count from the end of the list; prints "2" xs[2] = 'foo' # Lists can contain elements of different types print(xs) # Prints "[3, 1, 'foo']" xs.append('bar') # Add a new element to the end of the list print(xs) # Prints "[3, 1, 'foo', 'bar']" x = xs.pop() # Remove and return the last element of the list print(x, xs) # Prints "bar [3, 1, 'foo']" nums = list(range(5)) # range is a built-in function that creates a list of integers print(nums) # Prints "[0, 1, 2, 3, 4]" print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]" print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]" print(nums[:]) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]" print(nums[:-1]) # Slice indices can be negative; prints "[0, 1, 2, 3]" nums[2:4] = list(range(9, 18, 1)) # Assign a new sublist to a slice print(nums) for data in nums: print(data) for idx, data in enumerate(nums): print('%d:%d' % (idx, data)) # 带条件初始化 seq = [x * 5 for x in nums if x % 2 == 0] print(seq)
true
cb999c7c63e0d785280842f361c15958e7829a73
Divya171/EDUYEAR-PYTHON-20
/Day_8.py
833
4.28125
4
# coding: utf-8 # In[10]: # 1. Take a number from user and check whether it is prime or not. Use paramters to send the number to the function #eg. Enter a nnumber 3 # 3 is prime def prime(num): found = False if num > 1: for i in range(2,num): if num%i == 0: found = True break if found: print(num, "is not a prime number") else: print(num,"is a prime number") num = int(input("Enter a number of your choice")) prime(num) # In[9]: #2. Write a function to print n factorial # Take n value as user input and pass as a parameter #E.g Enter a number 5 # 120 def factorial(num): fact = 1 while num>0: fact=fact*num num-=1 print(fact) num = int(input("Enter the number of your choice")) factorial(num)
true
51461ac41288cb9e41e374f5638b34efccce829e
prith25/daily_programming
/Daily Coding/python/union_count.py
438
4.15625
4
#Find the union of two arrays and print the number elements in the resultant array a = [] print("Enter the length of both arrays: ") len1 = int(input()) len2 = int(input()) print("Enter the first array: ") for i in range(len1): temp = int(input()) a.append(temp) print("Enter the second array: ") for i in range(len2): temp = int(input()) if temp not in a: a.append(temp) print(f"Length of the union is {len(a)}")
true
2ec8379629a586ada705f187f8db041f4c78ec10
lin344902118/Algorithms
/python/bubbleSort.py
509
4.125
4
# -*- encoding:utf-8 -*- """ author: nick date: 2019/6/1 """ import random def bubble_sort(arr: list): for i in range(len(arr)-1): for j in range(i+1, len(arr)): if arr[i] > arr[j]: arr[i], arr[j] = arr[j], arr[i] return arr def main(): nums = [i for i in range(100)] for i in range(5): arr = [] for i in range(10): arr.append(random.choice(nums)) print(bubble_sort(arr)) if __name__ == '__main__': main()
false
f868c9a38fb78f4546739d63ba1824c8e3012e31
luceva/GUIProjects
/gameRandomizer.py
1,448
4.1875
4
''' Ante Lucev Feb, 5, 2020 At the beginning of many board games a random person must be chosen to go first. This program should allow the user to enter a list of names in a box, separated by newlines, press a ‘Pick Player’ button, and a random name is displayed. Every time the button is clicked a different name is chosen. It should never pick the same name twice in succession. ''' from tkinter import * import random master = Tk() master.minsize(width=750, height=150) master.configure(background="orangered") previous = "" def names(): global previous string_name = names_box.get() list_name = string_name.split() name = random.choice(list_name) while(name == previous): name = random.choice(list_name) previous = name label1 = Label(master, text="Result:", font=('Calibri', 15), width=20, background="orangered") label1.grid(column=0, row=2,sticky=E,pady=20) result = Label(master, text=name, font=('Calibri', 15), width=20, background="orangered") result.grid(column=1, row=2) label1 = Label(master, text="Enter a list of names:", font=('Calibri', 15), width=20, background="orangered") label1.grid(column=0, row=0,columnspan=2,sticky=W,padx=10,pady=15) names_box = Entry(master, font=('Calibri', 15), width=50) names_box.grid(column=0, row=1,padx=10) submit = Button(master, text="Pick Player", command=names, font=('Courier New', 10), width=20) submit.grid(column=1,row=1) mainloop()
true
cfabe8c068bea1d178949d9b59b8b307eaae4ab5
saanvitirumala/python-beginner
/ananthsir-python-class/day-7.py
1,756
4.25
4
student_list = ["Komali", "Navin & Navya","Udeepth", "Akshar","Adityamithran", "Adityamithram"] # Index starts from 0 long_name_list = [student_list[0]] #intialize for student_name in student_list : # visit all names if len(student_name) == len(long_name_list[0]) and student_name != long_name_list[0] : long_name_list.append(student_name) # Add to existing long names list elif len(student_name) > len(long_name_list[0]) : long_name_list.clear() # clear/forget all long names long_name_list.append(student_name) # This is the new long name add it for student_name in long_name_list : print(student_name) short_name_list = [student_list[0]] #intialize for student_name in student_list : # visit all names if len(student_name) == len(short_name_list[0]) and student_name != short_name_list[0] : short_name_list.append(student_name) # Add to existing long names list elif len(student_name) < len(short_name_list[0]) : short_name_list.clear() # clear/forget all long names short_name_list.append(student_name) # This is the new long name add it print("---Lengthiest--") for student_name in long_name_list : print(student_name) print("--Shortest--") for student_name in short_name_list : print(student_name) student_list = ["Komali", "Navin & Navya","Udeepth", "Akshar","Adityamithran"] # Index starts from 0 print("---- Before sorting--") for student_name in student_list : print(student_name) #Sort in descending sorted_student_list = sorted(student_list, key=len, reverse=True) for student_name in sorted_student_list : if len(student_name) !=len(sorted_student_list[0]) : # Break if student name length is difrent break loop break print(student_name)
false
76589de696c885a6c043bdef0367d73aca8ddcf3
Hari-krishna-tech/Leetcode-questions-and-Answer-in-python
/a8-leetcode_question.py
911
4.25
4
""" Longest Substring Without Repeating Characters ------------------------------ Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. ------------- """ def length_of_longest_sub_string(s): a_pointer = 0 b_pointer = 0 max_len = 0 set_string = set() while b_pointer < len(s): if s[b_pointer] not in set_string: set_string.add(s[b_pointer]) max_len = max(max_len,len(set_string)) print(max_len) b_pointer += 1 else: set_string.remove(s[a_pointer]) a_pointer += 1 print(set_string) return max_len print(length_of_longest_sub_string("abcabcbb"))
true
4816ea3dcd9301ec1f000e1f8c99c41168dc4a7c
lollek/scripts-and-stuff
/language-testing/rot13/rot13.py
729
4.125
4
#! /usr/bin/env python3 from sys import argv, stdin def rot13(sentence): new_sentence = "" for letter in sentence: if 'a' <= letter.lower() <= 'm': new_sentence += chr(ord(letter) + 13) elif 'n' <= letter.lower() <= 'z': new_sentence += chr(ord(letter) - 13) else: new_sentence += letter print(new_sentence, end="") # No arguments means a pipe: if len(argv) == 1: for line in stdin: rot13(line) # Otherwise we'll rot13 the arguments: else: rot13(" ".join(argv[1:]+["\n"])) """ TAIL INFO: Name ROT13 Language: Python3 State: Done Rot13 a string Example: ./rot13.py hello world Example2: echo "hello world" | ./rot13.py """
false
7705fdd739657eb84fd2fe14ee12e7d41215b418
lollek/scripts-and-stuff
/language-testing/guess_number/guess_number.py
723
4.15625
4
#! /usr/bin/env python3 from random import randint print("Guess-a-number game!", "I am thinking of a number between 1 and 100", "What's your guess?", sep="\n") target = randint(1, 100) number = 0 current = 0 while 1: number += 1 current = int(input("Guess %d: " % number)) if current == target: print("Correct! You won!") break elif number == 5: print("Haha, I won! The number was %d" % target) break elif current < target: print("Too low! Guess again!") elif current > target: print("Too high! Guess again!") """ Name: Guess Number Language: Python3 State: Done Play guess-a-number game Example ./guess_number.py """
true
9f63ab23c78e825c567d7670107178d707d63bf2
DaviMoreira58/PythonExc
/aula010.py
2,849
4.21875
4
# CONDIÇOES SIMPLES E COMPOSTAS ''' ╔════ Exemplo: Controlando um carro com um unico caminho ║ carro.siga() ║ carro.esquerda() ║ carro.siga() ║ carro.direita() ║ carro.siga() ║ carro.direita() ║ carro.siga() ║ carro.esquerda() ║ carro.siga() ║ carro.pare() ║ ▼ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ╔══════ Exemplo: Controlando um carro com duas possilidades ║ iremos utilizar a funçao se e senão ╚═══════════════════════════╗ ▼ ╔ carro.esquerda() ▓ ◄ carro.siga() ► ▓ ╗ carro.direita() ║ carro.siga() ║ carro.siga() ║ carro.direita() ║ carro.esquerda() ║ carro.siga() ║ carro.siga() ║ carro.direita() ║ carro.esquerda() ║ carro.esquerda() ║ carro.siga() ║ carro.siga() ║ carro.pare() ║ carro.direita() ║ ║ carro.siga() ║ ╚══════════ ► ▓ carro.pare() ▓ ◄╝ ║ ║ ▼ carro.siga() se carro.esquerda() carro.siga() carro.direita() carro.siga() carro.direita() identação carro.esquerda() carro.siga() carro.direita() carro.siga() senão carro.siga() carro.esquerda() carro.siga() carro.esquerda() carro.siga() carro.pare() #ESTRUTURA CONDICIONAL se carro.esquerda() ► if carro.esquerda(): bloco_V_ ► bloco True senão ► else: bloco_F_ ► bloco False tempo = int(input('Quantos anos tem seu carro? ')) if tempo <=3: print('carro novo') else: print('carro velho') print('--FIM--') # outra maneira tempo = int(input('Quantos anos tem seu carro? ')) print('carro novo' if tempo<=3 else'carro velho') print('--FIM--') ''' ''' # EXERCICIOS AULA nome = str(input('Qual é o seu nome? ')) if nome == 'Davi': print('Que nome lindo que você tem!') else: print('Seu nome é tão normal!') print('Bom dia, {}!'.format(nome)) n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) m = (n1 + n1)/2 print('A sua média foi {:.1f}'.format(m)) if m >= 6.0: print('sua média foi boa, parabens por fazer o minimo') else: print('Sua média foi um lixo igual você! Parabens!!') # print('PARABENS' if m >= 6 else 'ESTUDE MAIS!') #IF simplificado '''
false
8efe12225728ebbbf6ad88a17f43b271dc824d17
DaviMoreira58/PythonExc
/exc074.py
847
4.15625
4
# Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. # Depois disso, mostre a listagem de números gerados e também indique o menor e o maior # valor que estão na tupla. """from random import randint n0 = randint(0,10) n1 = randint(0,10) n2 = randint(0,10) n3 = randint(0,10) n4 = randint(0,10) numeros = (n0, n1, n2, n3, n4) print(f'Os valores sorteados foram: {numeros}') print(f'O maior valor sorteado foi {max(numeros)}') print(f'O menor valor sorteado foi {min(numeros)}')""" # Meu jeito from random import randint numeros = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) print('Os valores sorteados foram: ', end='') for n in numeros: print(f'{n} ', end='') print(f'\nO maior valor sorteado foi {max(numeros)}') print(f'O menor valor sorteado foi {min(numeros)}')
false
563fefb44dffc0568145c45941e01de9b9e1fcae
DaviMoreira58/PythonExc
/exc028.py
903
4.28125
4
# Escreva um programa que faça o computador "pensar" em um numero inteiro entre 0 e 5 # e peça para o usuario tentar descobrir qual foi u numero escoljido pelo computador , # o programa devera escrever na tela se o usuario venceu ou perdeu ''' import random n = int(input('Qual o numero? ')) r = random.randint(0, 5) if n == r: print('Acertou mizeravi!') else: print('errooooou!!') print(r)''' from random import randint from time import sleep computador = randint(0, 5) print('\033[31m-=-\033[m' * 20) print('Vou pensar em um numero de 0 a 5. Tente adivinhar...') print('\033[31m-=-\033[m' * 20) jogador = int(input('Em que numero eu pensei? ')) print('\033[32mProcessando...\033[m') sleep(2) if jogador == computador: print('\033[35;1mParabens! Voce conseguiu me vencer!\033[m') else: print('\033[4;35mGanhei! Eu pensei no numero {} e não no {}\033[m'.format(computador, jogador))
false
1051f16f149b6523e14951fc3b8282b928ea22e4
DaviMoreira58/PythonExc
/exc086.py
972
4.46875
4
# Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores # lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta. """matriz = [[], [], []] for c in range(0, 3): matriz[0].append(int(input(f'Digite um valor para [0]{[c]}: '))) for c in range(0, 3): matriz[1].append(int(input(f'Digite um valor para [1]{[c]}: '))) for c in range(0, 3): matriz[2].append(int(input(f'Digite um valor para [2]{[c]}: '))) print(f'[{matriz[0][0]:^5}] [{matriz[0][1]:^5}] [{matriz[0][2]:^5}]') print(f'[{matriz[1][0]:^5}] [{matriz[1][1]:^5}] [{matriz[1][2]:^5}]') print(f'[{matriz[2][0]:^5}] [{matriz[2][1]:^5}] [{matriz[2][2]:^5}]')""" # Meu matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: ')) print('-=' * 30) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') print()
false
3be2b4376efa4fe8e5cb7f389edeb7898c50196c
DaviMoreira58/PythonExc
/exc016.py
747
4.25
4
#crie um programa que leia um numero real qualquer pelo teclado e sua posição inteira #Exp: #Digite um numero: 6.127 #O numero 6.127 tem a parte inteira 6. # MEU JEITO '''from math import trunc n1 = float(input('digite um numero: ')) n2 = trunc(n1) print('O numero {} tem a parte inteira {}. '.format(n1, n2))''' '''import math num = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, math.trunc(num))) print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, trunc(num))) # caso importe apenas a função trunc''' #Sem o uso da biblioteca num = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, int(num)))
false
b2534c0dd1e27e896cf5e4d92d44a9010e3a18b2
Arshdeep-kapoor/Python
/chapter08-ques06.py
261
4.1875
4
input=input("enter a string to count number of letters") def countLetters(s): c=0 for i in range(0,len(input)): if input[i].isalpha(): c+=1 return c print(countLetters(input), "is total number of letters in the",input)
true
670f9b0d64910eda911dbd4befa3b1146ccbf59e
Arshdeep-kapoor/Python
/chapter5-ques54.py
513
4.3125
4
# Program to draw Turtle: plot the square function import math import turtle turtle.pendown() turtle.goto(0,0) turtle.pensize(3) turtle.forward(400) turtle.right(180) turtle.forward(800) turtle.right(180) turtle.forward(400) turtle.right(90) turtle.forward(250) turtle.right(180) turtle.forward(500) turtle.right(180) turtle.forward(250) turtle.color("RED") turtle.penup() turtle.goto(-16,256) turtle.pendown() for x in range(-16,17): y = x * x turtle.goto(x,y) turtle.done()
false
70da0dc8276415c05cd0093bc639e5f39e1c0a86
andiazfar/laptop_price_ML
/laptop_price_ML.py
1,938
4.25
4
# ML Test on Prices of Laptops using scikit-learn import pandas as pd from sklearn.tree import DecisionTreeRegressor print("Initiliazing path to read data...") laptop_data_path = "laptops.csv" print("Reading csv files using pandas. Encoding used: \"ISO-8859-1\"") print("Encoding is used so that we are able to read the CSV file, due to how the read_csv handles the input file.") # For more info, please refer to the link below: # https://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas-with-python laptop_data = pd.read_csv(laptop_data_path, encoding = "ISO-8859-1") print("Finished reading csv file...\n") print("Printing the first 5 data for viewing...") data_head = laptop_data.head() print(data_head) print("\n") print("Printing the available columns in the data...") cols = laptop_data.columns print(cols) print("Let's drop the missing values from our data.") laptop_data = laptop_data.dropna(axis=0) print("Then, we will pick a Prediction Target. In this case, we will pick the price.") y = laptop_data.Price_euros print("After that, we will pick the Features that we want that will help to weigh in, in the selection process.") # You need to be careful on what features you are expecting. Normally, they can only extract numbers. I am sure there is a way to if we can numerize the brand to make it more ML-friendly data. laptop_features = ['Inches', 'Ram', 'Weight'] X = laptop_data[laptop_features] print("Let's see what the Feature is all about by using the describe function.") X.describe() print("And let's see what's in there for a little bit") print(X.head()) print ("Now, we create our model for the Machine Learning") laptop_ml = DecisionTreeRegressor(random_state=1) print("Next, we fit the model using X and y") laptop_ml.fit(X,y) print("Making predictions for the following 5 laptops:") print(X.head()) print("The predictions are") print(laptop_ml.predict(X.head()))
true
53fb879ba6a192d2583142c1983e287aaa95a703
ivangeorgiev97/python-exercises
/classes-objects.py
959
4.1875
4
# Classes and Objects class MainClass: hobby = "football" def introduce_me(self): "Hi, my name is Ivan" class MyClass(MainClass): def __init__(self, name, country): self.name = name self.country = country def __str__(self): return "Name: {}, Country: {}, Hobby: {}".format(self.name, self.country, MyClass.hobby) def __len__(self): return self.name def __del__(self): print("object is finally removed!") def introduce_me(self): print(f'My name is {self.name} and I am from {self.country} and hey my hobby is {MyClass.hobby}') myObject = MyClass("Ivan", "Bulgaria") myObject.introduce_me() myObject.name = "Stoyan" myObject.introduce_me() print(myObject) class Animal: def __init__(objhere, name): objhere.name = name def say_name(againreferncehere): print ("Hey " + againreferncehere.name) a3 = Animal("Onqotnovagodina") a3.say_name()
false
70b0dbebbb01b9a1e9bd9af0555a4ef13124b081
AbCreativeAmid/Point_of_sale
/__init__.py
1,277
4.1875
4
from product_operations import * """this is the main file of poject it takes show the menu to the user and handle the user request""" def request_for_input(): """show menu to the user and ask user for input and validate the input""" #select menu option:// this function returns the option user select print("\n") print("1:Add Product"+" "*7+"2:Add to existent products"+" "*2+"3:Bye Product"+" "*7+"4:Delete Product"+" "*4+"5:Exit Product"+" "*6) print("\n") operation = input("Select one of above!_ ") try: operation = eval(operation) return operation except: print("Enter a number!_ ") return 0 input("Hello welcome to Point of Sale Programm!_ (press Enter!) ") input("You can Add, Buy or delete the products through this program! please press Enter for Menu Display!_ ") input("Select from the following menue what want to do!_ (press Enter!) ") #it iterate the process until the user does not end the program while True: op = request_for_input() if op ==1: add_product() if op ==2: add_to_existent_products() elif op ==3: buy_product() elif op ==4: delete_product() elif op == 5: break print("thanks for using! bye have a good time! ")
true
4970f84fc5abc7a802c95e74efb5d4775cec1021
djaustin/python-learning
/3-lists/names.py
2,235
4.8125
5
names = ['adam', 'brandon', 'carl', 2] # Accessing elements notice the method of accessing the final element of the list print(names[0]) print(names[1]) print(names[-1]) # Iterate over all list elements using for-in syntax for name in names: print("Hello " + str(name).title() + "!") motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) # Editing an element of a list is done by accessing the position and assigning a new value to it # Lists are mutable motorcycles[1] = 'ducati' print(motorcycles) # Adding to a list motorcycles.append("triumph") motorcycles.insert(1, "harley") motorcycles # Delete an element by index del motorcycles[0] guest_list = ['Hawking', 'Fry', 'Einstein'] for guest in guest_list: print(f"Hello {guest}, would you like to come to dinner?") print(f"Unfortunately, {guest_list[1]} cannot make it tonight.") guest_list[1] = "Attenborough" for guest in guest_list: print(f"Hello {guest}, would you like to come to dinner?") print(f"Hello {guest_list[0]}, {guest_list[1]}, {guest_list[2]}. I have been able to secure a larger tablet so we will be expanding our group") guest_list.insert(0, 'Obama') guest_list.insert(1, 'Kennedy') guest_list.append('Mathers') for guest in guest_list: print(f"Hello {guest}, would you like to come to dinner?") print("I am now only able to seat two guests, sorry!") for i in range(len(guest_list)-2, 0, -1): print(f"Hi {guest_list.pop(i)}, I'm really sorry but you're off the list!") print(guest_list) for guest in guest_list: print(f"Good news, {guest}! you're still on for dinner!") del guest_list[0] del guest_list[0] print(motorcycles) print(sorted(motorcycles)) print(motorcycles) print(motorcycles.sort()) print(motorcycles) print(guest) squares = [value**2 for value in (range(1,11))] squares # Slicing a list numbers = list(range(0,11)) numbers numbers[0:3] numbers[:3] numbers[3:] numbers[3:5] for number in numbers[-3:]: print(number) # Copying a list numbers2 = numbers[:] numbers2 del numbers[0] numbers numbers2 # Checking values in a list print(1 in numbers) print(1 not in numbers) # Checking if list is empty if numbers: print("There are numbers") else: print("There are no numbers")
true
bd2a9eea2977253a122e26d9b1a82795ae39d68b
syedbilal07/python
/Basic Tutorial/Chapter 12 - Functions/script10.py
494
4.15625
4
# The return Statement # The statement return [expression] exits a function, optionally passing back an # expression to the caller. A return statement with no arguments is the same as # return None. # Function definition is here def sum(arg1, arg2): "This is a function" # Add both the parameters and return them" total = arg1 + arg2 print("Inside the function", total) return total # Now you can call sum function total = sum(10,20) print("Outside the function", total)
true
ff7180f5110b873ceb2e822f20208b38b0eaabfe
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/LongestWord_ret.py
300
4.4375
4
# Python Program to Read a List of Words and Return the Length of the Longest One words=["abcde","b","c","ab","abc"] len_Lword=len(words[0]) for i in range(1,len(words)): len_word=len(words[i]) if len_word>len_Lword: len_Lword=len_word print("Length of longest word is: ",len_Lword)
true
f3f59483b02434b20d6e51383a55b937ee4b0023
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/even_odd_list.py
249
4.15625
4
# Python Program to Put Even and Odd elements in a List into Two Different Lists lst=[1,2,3,4,5,6,7,8,9,10] even=[] odd=[] for i in lst: if i%2: odd.append(i) else: even.append(i) print("Even: {}\nOdd: {}".format(even,odd))
false
7731234ee780470be4104cf2d7434064ceb36bdc
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/leap_year.py
254
4.46875
4
# Python Program to Check Whether a Given Year is a Leap Year year=int(input("Please enter an year: ")) if year%4==0 and year%100!=0 or year%400==0: print("Your entered year is a leap year!") else: print("Your entered year is not a leap year!")
false
ae484c59c8bb8fe7f1f86660eee68daaf9096b21
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/num_check.py
271
4.5
4
#Python Program to Check Whether a Number is Positive or Negative number=eval(input("Please enter a number: ")) if number>0: print("Entered number is positive") if number<0: print("Entered number is negative") if number==0: print("Entered number is neutral")
true
fd20f429fef017c2c05f29a2a49b7bad3d25eead
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/sum_series1.py
235
4.25
4
# Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + ... + 1/N plus=0 n=int(input("Please enter the last term number of the required series: ")) for i in range(1,n+1): plus+=1/i print("Sum of the given series is",plus)
true
436b73d32662a30484b38112c6c7ac57186cb7c3
YahyaNaq/INTENSIVE-PROGRAMMING-UNIT
/dec_bin_oct_hex_conversions.py
609
4.34375
4
#Python Program to Convert Decimal to Binary, Octal and Hexadecimaland vice versa without using built in functions n=int(input("Please enter the number you want to convert: ")) #Decimal to Binary quo=n//2 rem=n%2 Bin=str(rem) while quo>1: rem=quo%2 Bin=str(rem)+Bin quo=quo//2 Bin=str(quo)+Bin print("Binary:", Bin) #Decimal to Octal Q=n//8 R=n%8 Oct=str(R) while Q>0: R=Q%8 Oct=str(R)+Oct Q=Q//8 print("Octal:",Oct) #Decimal to Hexadecimal Q=n//16 R=n%16 Hex=str(R) while Q>0: R=Q%16 Hex=str(R)+Hex Q=Q//16 print("Hexadecimal:",Hex)
false
81d385f5d5f0d81b4efc3bd7e45275f9f7240caa
miikkij/python_training_basic
/hackerrank_python_ifelse.py
615
4.40625
4
""" Task Given an integer, , perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20, print Weird If n is even and greater than 20, print Not Weird """ # !/bin/python3 n = int(input()) is_odd = n % 2 # If is even and in the inclusive range of to , print Not Weird if 2 <= n <= 5 and not is_odd: print("Not Weird") elif 6 <= n <= 20 and not is_odd: print("Weird") elif n > 20 and not is_odd: print("Not Weird") elif is_odd: print("Weird")
false
5a0bb941bbd302919a773b9858e3d5d7c0370c78
SCRK16/ProjectEuler
/src/1-100/18.py
1,331
4.1875
4
def max_row(r): """ Calculate the maximum for each two consecutive numbers in a row Return the resulting list of maximums """ if len(r) == 1: return r result = [] for i in range(len(r)-1): result.append(max(r[i], r[i+1])) return result with open("18.txt") as f: content = f.readlines() content = [x.strip() for x in content] content = [x.split(" ") for x in content] content = [[int(y) for y in r] for r in content] triangle = list(reversed(content)) for i in range(len(triangle)-1): r = max_row(triangle[i]) for j in range(len(r)): triangle[i+1][j] += r[j] print(triangle[-1][0]) """ Reasoning: Start at the row second to last from the bottom. You only have to choose between two numbers at the very bottom of the triangle. Pick the bigger one! This will result in a higher score. If we were going to pick that number anyway when choosing the number on the bottom row, we may as well add it to the number in the row above it. We now have a pyramid with one fewer row. Repeat until there is only 1 row left. The pyramid now contains the maximum score attainable. Example: 3 3 3 23 7 4 7 4 20 19 2 4 6 10 13 15 8 5 9 3 This is the maximum attainable score: 3 + 7 + 4 + 9 = 23 """
true
98506579a15b4d502b64b09304c591f6b4c9237f
sadabjr/CFC--assing-pyboot
/GCD of two numbers.py
443
4.25
4
# import math # print(f"The GCD of {num1} & {num2} is :", end =" " ) # print(math.gcd(num1, num2)) #This program is for find the gcd of two numbers num1 = int(input("Inter the first number :")) num2 = int(input("Inter the second number :")) if num2>num1: mn = num1 else: mn = num2 for i in range(1, mn+1): if num1 % i == 0 and num2 % i == 0: hcf = i print(f"The hcf/GCD of {num1} and {num2} is {hcf}")
true
c7434fcbc9f1428baceaa81148290b6297d3f8b5
varshinireddyt/Python
/GoldManSachs/StringCompressionReplace*.py
1,086
4.3125
4
""" Problem Description: Given a string replace the largest repeated substring at every point with an asterisk(*). The goal is end result should be a minimal length string after compression For example, s = "abcabcd" should become "abc*d", Reason: we know abc has repeated twice, so replace the entire second instance of abc with an *. and if s = "aabbaabb" it should become "a*bb*", Reason: At index 1, a is repeated twice so put an * there, and aabb has repeated twice so replace it's second instance with an *. In this example we don't put an * right after b at index 3 because aab* would represent aabaab, but that isn't the case. Solution: The solution I came up with was at every even index check if the first half is equal to the second half, if it is, replace the entire second half with an *. """ def compressString(s): temp = "" i = 0 while i < len(s): if s[:i+1] == s[i+1:2*i+2]: temp += s[i] + '*' i += (i+2) else: temp += s[i] i += 1 return temp s = "abcabcd" print(compressString(s))
true
4bbd0b2ed581998b8491705ed2aa635013b33867
varshinireddyt/Python
/Challange/MaxDistanceArray.py
1,269
4.21875
4
""" Leetcode 624. Maximum Distance in Arrays Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance. Input: [[1,2,3], [4,5], [1,2,3]] Output: 4 Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array. Each given array will have at least 1 number. There will be at least two non-empty arrays. The total number of the integers in all the m arrays will be in the range of [2, 10000]. The integers in the m arrays will be in the range of [-10000, 10000]. """ def maxDistance(arrays): diff = 0 maximum = arrays[0][len(arrays[0])-1] minimum = arrays[0][0] for i in range(1,len(arrays)): diff = max(diff, max(abs(arrays[i][len(arrays[i])-1]-minimum),abs(maximum-arrays[i][0]))) minimum = min(minimum,arrays[i][0]) maximum = max(maximum,arrays[i][len(arrays[i])-1]) return diff # arrays = [[1,2,3], # [4,5], # [1,2,3]] arrays = [[1,5],[3,4]] # arrays = [[1,4],[0,5]] print(maxDistance(arrays))
true
baf3305de039a386b95392e77d93171c538f8964
varshinireddyt/Python
/CCI/Trees and Graphs/ListOfDepths.py
1,316
4.125
4
""" List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.next = None def dfs(root): output = [] queue = [] dummy = Node(0) head = Node(0) pre = head queue.append(root) queue.append(dummy) while queue: current = queue.pop(0) if current != dummy: pre.next = current pre =pre.next if current.left: queue.append(current.left) if current.right: queue.append(current.right) else: pre.next = None output.append(head.next) if not queue: break head.next = queue[0] pre = head queue.append(dummy) return output def printList(list): for node in list: while node: print(node.val) node = node.next root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.right.right = Node('F') #bst_to_linkedlist(root) printList(dfs(root))
true
adf3abe4203c0dcc7f7411b5019f22fb64cf040b
varshinireddyt/Python
/Challange/Count Ways To Split.py
1,886
4.21875
4
"""You are given a string s. Your task is to count the number of ways of splitting s into three non-empty parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings. NOTE: + refers to string concatenation. Example For s = "xzxzx", the output should be countWaysToSplit(s) = 5. Consider all the ways to split s into three non-empty parts: • If a = "x", b = "z" and c = "xzx", then all a + b = "xz", b + c = "zxzx" and c + a = xzxx are different. • If a = "x", b = "zx" and c = "zx", then all a + b = "xzx", b + c = "zxzx" and c + a = zxx are different. • If a = "x", b = "zxz" and c = "x", then all a + b = "xzxz", b + c = "zxzx" and c + a = xx are different. • If a = "xz", b = "x" and c = "zx", then a + b = b + c = "xzx". Hence, this split is not counted. • If a = "xz", b = "xz" and c = "x", then all a + b = "xzxz", b + c = "xzx" and c + a = xxz are different. • If a = "xzx", b = "z" and c = "x", then all a + b = "xzxz", b + c = "zx" and c + a = xxzx are different. Since there are five valid ways to split s, the answer is 5. Input/Output • [execution time limit] 3 seconds (java) • [input] string s A string to split. Guaranteed constraints: 3 ≤ s.length ≤ 100. • [output] integer The number of ways to split the given string. """ def countWaysToSplit(s): i = 0 j = 1 k = 2 count = 0 while k < len(s) and j < len(s)-1: if k < len(s)-1: a = s[i] b = s[j:k] c = s[k:] if a+b != b+c or b+c != c+a or a+b != c+a : count += 1 if k == len(s)-1: a = s[i:j] b = s[j:k] c = s[k:] if a + b != b + c or b + c != c + a or a + b != c + a: count += 1 j += 1 else: k+=1 return count s = "ababa" print(countWaysToSplit(s))
true
ba54675285d8dda84cd9abefe08546759a129d57
varshinireddyt/Python
/Challange/LargestNumber.py
582
4.25
4
""" Given a list of non negative integers, arrange them such that they form the largest number. Example: Input: [10,2] Output: "210" Input: [3,30,34,5,9] Output: "9534330" """ from functools import cmp_to_key def largestNumber(nums): func = lambda a,b: 1 if a + b < b + a else -1 if b + a < a + b else 0 # s = [str(i) for i in nums] # s = list(map(str,nums)) #s.sorted([str(i) for i in nums],key = cmp_to_key(func)) return str(int("".join(sorted([str(i) for i in nums],key = cmp_to_key(func))))) nums = [3,30,34,5,9] #nums = [10,2] print(largestNumber(nums))
true
6f5eff1bbb7a88a4b483ef78e39a6657206a35f4
wesenu/MITx600
/BookCodes/em_6_1_1_copy.py
324
4.1875
4
def copy(l1, l2): """Assumes l1, l2 are lists Mutates l2 to be a copy of l1""" while len(l2) > 0: # remove all elements from l2. l2.pop() # remove last element of l2. for e in l1: # append l1's elements to initially empty l2 l2.append(e) l1 = [1, 2, 3] l2 = l1 copy(l1, l2) print(l2)
true