blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
498b2f1bf20f12d2da8c02558edd87297f5c6fed
khanhdodang/automation-training-python
/python_basics/tutorial/31_string_formatting.py
2,023
4.65625
5
''' Python String Formatting To make sure a string will display as expected, we can format the result with the format() method. String format() The format() method allows you to format selected parts of a string. Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input? To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method: Example Add a placeholder where you want to display the price: ''' price = 49 txt = "The price is {} dollars" print(txt.format(price)) ''' You can add parameters inside the curly brackets to specify how to convert the value: Example Format the price to be displayed as a number with two decimals: ''' txt = "The price is {:.2f} dollars" ''' Check out all formatting types in our String format() Reference. Multiple Values If you want to use more values, just add more values to the format() method: print(txt.format(price, itemno, count)) And add more placeholders: Example ''' quantity = 3 itemno = 567 price = 49 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price)) ''' Index Numbers You can use index numbers (a number inside the curly brackets {0}) to be sure the values are placed in the correct placeholders: Example ''' quantity = 3 itemno = 567 price = 49 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) ''' Also, if you want to refer to the same value more than once, use the index number: Example ''' age = 36 name = "John" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name)) ''' Named Indexes You can also use named indexes by entering a name inside the curly brackets {carname}, but then you must use names when you pass the parameter values txt.format(carname = "Ford"): Example ''' myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname="Ford", model="Mustang"))
true
9c7bde7f37c9e75e5a39314ec3fd7587984a83bf
khanhdodang/automation-training-python
/python_basics/tutorial/30_user_input.py
656
4.28125
4
''' Python User Input User Input Python allows for user input. That means we are able to ask the user for input. The method is a bit different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method. The following example asks for the username, and when you entered the username, it gets printed on the screen: Python 3.6 ''' username = input("Enter username:") print("Username is: " + username) # Python 2.7 username = raw_input("Enter username:") print("Username is: " + username) # Python stops executing when it comes to the input() function, and continues when the user has given some input.
true
fc1c238515effb961f4efae4eee9d9ec71997aa0
green-fox-academy/RudolfDaniel
/[week-02]/[day-01]/Exercise-34.py
262
4.1875
4
lenght_of_list = int(input("Type in a number ")) list_of_nr = [] while len(list_of_nr) < lenght_of_list: list_of_nr.append(int(input("Type in a number: "))) print("Sum: " + str((sum(list_of_nr)))) print("Average: " + str((sum(list_of_nr))/lenght_of_list))
false
54436c30c613ca141c8a12af9e8f64c8efab1c93
dominichul/HackerRank
/python/warm_up/repeated_string/repeated_string.py
1,570
4.1875
4
#!/bin/python """ HackerRank Challenge: Warm-up Challenges -> Repeated String Args: @:param s (str): String given by user @:param n (int): Integer given by user Problem: - Assume string entered by user is infinitely repeating. - How many times is ACTIVATE_CHARACTER found in the repeating string up to index of n-1? Solution: 1. Identify the ACTIVATE_CHARACTER count for string 's'. 2. Determine how many times the entire string 's' can fit into the repeating string up to n-1. 3. Multiply result from step 1 by result from step 2 to get a base count 4. Determine # of remaining characters up to index n-1 in repeating string 5. Identify the ACTIVATE_CHARACTER count for substring of 's' from [0:x-1], where x is the result of step 4 6. Return the sum of steps 3 and 5 """ ACTIVATE_CHARACTER = 'a' def repeatedString(s, n): """ :param s: str -> Repeating string :param n: int -> Number of characters to include in repeating string :return: # of occurences of ACTIVATE_CHARACTER in repeating string of s (str) up to index n-1 (int) f(s,n) = (# of occurences of 'a' in s) * (number of times entire 's' string fits in n) + (# of occurences of 'a' in 's' up to index of (remainder character count from n - 1)) """ return s.count(ACTIVATE_CHARACTER) * (n / len(s)) + s[:(n % len(s))].count(ACTIVATE_CHARACTER) if __name__ == '__main__': print("Enter String:") s = raw_input() print("Enter Integer:") n = int(raw_input()) result = repeatedString(s, n) print(result)
true
2dfce74b1c570a8505902256578c802266fea491
akshay2242/Python_All_Basic_Programs
/Operators/3.py
230
4.15625
4
# Program to find two numbers Equal or Not a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) if a==b: print("The value of a and b are equal") else: print("The value of a and b are not equal")
true
a855f6afe88dfdbe7e619d01e4bcd649b0de8d63
akshay2242/Python_All_Basic_Programs
/Loops/3.py
245
4.28125
4
# Program to equal operator and not equal operator a = int(input("Enter the value of a: ")) b = int(input("Enter the value of b: ")) if a==b: print("The value of a and b are equal") if a!=b: print("The value of a and b are not equal")
true
f1c5713bd893ccd51ddd7d420e30cedde4bba0a7
KaterynaKandziuba/ITStep-hws
/HW_9/Kandziuba_hw9_task6-7.py
1,242
4.125
4
#Задание 6 #Напишите функцию, которая считает количество #цифр в числе. Число передаётся в качестве параметра. Из #функции нужно вернуть полученное количество цифр. #Например, если передали 3456, количество цифр будет 4. a = int(input("Enter your number: ")) def digits(n): counter = 0; i = 1 while n > 0: n = n//(10**i) counter +=1 print("Your number has", counter, "digits.") digits(a) #Задание 7 #Напишите функцию, которая проверяет является ли #число палиндромом. Число передаётся в качестве параметра. Если число палиндром, # нужно вернуть из функции true, иначе false. number = int(input('Enter a number to check if it is a palindrome:')) def palindrome(n): n = str(n) n_rev = n[::-1] if n == n_rev: return True else: return False if palindrome(number): print("Yeap!") else: print('Oh, no!')
false
a7f34b32ef678b193d30f0044cac7f5c286c76f7
KaterynaKandziuba/ITStep-hws
/HW_15/Kandziuba_hw15.py
885
4.125
4
#Створити множини: A, B, C з довільними елементами. from random import randint A = set([randint(1, 100) for i in range(10)]) B = set([randint(1, 100) for i in range(10)]) C = set([randint(1, 100) for i in range(10)]) print(f"There are sets A: {A}, \nB: {B} \nand C: {C}") #1. Знаходимо різні елементи для A, B def different(A: set, B:set): return A^B D = different(A, B) print("Different elements of A and B:", D) #2. Знаходимо однакові елементи для A, C def similar(A: set, B: set): return A&C S = similar(A, C) print ("Similar elements of A and C:", S) #3. Знаходимо об'єднання всіх трьох множин def united(A: set, B: set, C: set): return A|B|C U = united(A, B, C) print ("United elements of A, B, and C:", U)
false
1d206fae96c945bdb83ba2731365680949715e34
schartun/pythoncrashcourse
/chapter_03/3-1. Names.py
259
4.34375
4
#Store the names of a few of your friends in a list called names. Print #each person’s name by accessing each element in the list, one at a time. names = ["arvin", "mario", "paulo", "adrian"] print(names[0]) print(names[1]) print(names[2]) print(names[3])
true
c03217169380baaef5b4a39ae2799886cb975289
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 8/p14p3.py
575
4.15625
4
""" Set count to 0 Prompt for non-negative, set as limit if limit is negative print warning exit for loop between 2 and limit if limit divides by counter evenly then print not prime break else then print prime """ count=0 limit=int(input('Enter an an integer >=0: ')) if limit<=0: print(limit,'is not a prime number. The prime number sequence begins at 1.') exit() for i in range(2,limit): if limit%i==0: print(limit,'is not a prime number.') break else: print(limit,'is a prime number.')
true
2139d880cca5d28ec1c45d4e01ce2f0c024da030
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 4/p6p3.py
359
4.46875
4
''' Prompt user to enter a name as a string. If the name is Mickey Mouse or Spongebob Squarepants, then print I am not sure that is your name. Else print you have a nice name. Print finished. ''' name=str(input('Enter name:')) if name=='Mickey Mouse' or name=='Spongebob Squarepants': print('I am not sure that is your name.') else: print('You have a nice name.') print('finished!')
true
b69f3a95cb2be123852a55b5993fb756e65ff7ab
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 7/p13p6.py
713
4.3125
4
""" define factorial function of variable x if x is 0 then return 1 else then print x return x multiplied by factorial function of x-1 prompt for non-negative integer if input isn't negative print factorial function of input else then print warning """ def fact(x): """Function that returns the factorial of its argument Assumes that its argument is a non-negative integer Uses a recursive definition """ if x==0: return 1 else: print(x) return x*fact(x-1) number=int(input('Enter an integer (must be >=0): ')) if number>=0: print(fact(number)) else: print('Integer must be >=0.')
true
e5d4c440ccafc0654bfaa60a4c65ffdf1251be88
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 2/p4p1.py
438
4.15625
4
#Ask the user to enter the Euro amount euro_amount=float(input('Enter Euro amount:')) print('Amount in Euro:',euro_amount) #Converting Euro to US Dollars euro_dollar_conversion=1.117547 #Converting Euro as long as the amount entered is at least zero if euro_amount>=0: print('Amount in US Dollars:',euro_amount*euro_dollar_conversion) else: print('Amount must be >= 0') print('Please try again.') print('Finished!')
true
302a4a8e23443aa8d2221b8409b999e67b8e6647
AdamMcCarthyCompSci/Programming-1-Practicals
/Midterm/q2v2.py
678
4.3125
4
monthname=['September','October','November','December','January','February','March','April','May','June','July','August'] monthnumber=[30,61,91,122,153,181,212,242,273,303,334,365] monthvalue=0 dateinput=int(input('Enter an integer: ')) if dateinput<=0: print('Integer must be greater than 0.') elif dateinput<=30: date=dateinput else: while monthvalue<12: if (dateinput-monthnumber[monthvalue])<=0: date=dateinput-monthnumber[monthvalue-1] break else: monthvalue+=1 if monthvalue<=3: year=2020 else: year=2021 print('Day',dateinput,'is the',date,'of',monthname[monthvalue]+',',year)
true
4f93b998772d503ea5936a3f12ac78bd724bd74e
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 5/p8p2.py
848
4.15625
4
''' Prompt input Test if input<=0 print warning if true else create variables for two multiplier numbers set a while loop where the loop can't exceed the inputted number Create nested while loop, where second variable can't exceed inputted number (other axis in table) multiply two variables and add space at end add 1 to second variable print empty line reset two variables ''' numberinput=int(input('Enter a positive integer: ')) if numberinput<=0: print('Integer must be greater than 0.') else: multiplylimit=1 multiplier=1 while multiplylimit<=numberinput: while multiplier<=numberinput: print(multiplier*multiplylimit,end=' ') multiplier+=1 print() multiplier=1 multiplylimit+=1 print('Finished!')
true
2e91b7c4d5bc7acf8119e8903b5e494370fd95d8
AdamMcCarthyCompSci/Programming-1-Practicals
/Practical 5/p9p1.py
560
4.25
4
''' Prompt for positive integer If input isn't positive print warning else set counter variable set sum variable create while loop where counter must not be greater than input add counter to sum add 1 to counter print sum ''' integerinput=int(input('Enter a positive integer: ')) if integerinput<=0: print('Integer must be greater than 0.') else: counter=0 integersum=0 while counter<=integerinput: integersum+=counter counter+=1 print(integersum) print('Finished!')
true
57e95c26b15b4b2093eb13591f4b2318b57d57a8
AdamMcCarthyCompSci/Programming-1-Practicals
/Midterm/q1.py
944
4.1875
4
''' Ask for integer. If integer less than 0, print statement. Else: while loop using inputted integer to capture modulus of 3,5,7,11. Count up by 1 if true. Add 1 to while loop. ''' integerinput=int(input('Enter an integer:')) print('You entered: ',integerinput) if integerinput<0: print('Number entered should be >=0') else: count=1 divisible3=0 divisible5=0 divisible7=0 divisible11=0 while count<=integerinput: if count%3==0: divisible3+=1 if count%5==0: divisible5+=1 if count%7==0: divisible7+=1 if count%11==0: divisible11+=1 count+=1 print('Number of numbers divisible by 3: ',divisible3) print('Number of numbers divisible by 5: ',divisible5) print('Number of numbers divisible by 7: ',divisible7) print('Number of numbers divisible by 11: ',divisible11) print('Finished!')
true
c829fb744e544e7fecc846902830ece85836970f
jacobollinger/CS-112L
/Lab5/Lab5 Solution.py
1,035
4.34375
4
# Lab5: Design software to calculate continued fractions for a real number and for a rational number. # By Jacob Bollinger def findContinuedFraction(a, b) : continuedFraction = '' searching = True while (searching) : integer = a // b a = a - integer * b a,b = b,a continuedFraction = continuedFraction + ' ' + str(integer) searching = (b != 0) return continuedFraction def findRealContinuedFraction(r, steps): continuedFraction = '' for i in range(steps) : integer = int(r) r = r - integer r = 1 / r continuedFraction = continuedFraction + ' ' + str(integer) i = i - 1 return continuedFraction # Inputs # Numerator N1 = 13 # Denomenator N2 = 7 # Real Number R = 2 ** (1/3) # How many times findRealContinuedFraction runs STEPS = 10 # Outputs # Continued fraction of N1 / N2 print ('Continued Fraction:', findContinuedFraction(N1, N2)) # Real Continued Fraction print ('Real Continued Fraction:', findRealContinuedFraction(R, STEPS))
true
e1e7b170c4d6de94a102fae266176b6c1c9016d5
ArunkumarSennimalai/-Python-Assignment2
/Assingment2/35.py
1,937
4.25
4
def printTupleElements(tuple1): for element in tuple1: print element, print "\v" def concatenateTuples(tuple1,tuple2): tuple1 += tuple2 return tuple1 def findingGreaterTuple(tup1,tup2,tup3): greatertuple=tup2 if cmp(tup1,tup2)==1: greatertuple=tup1 if cmp(tup3,greatertuple)==1: greatertuple=tup3 print "Greater tuple is", greatertuple def delTuple(tup1,tup2): try: #deleting entire tuple is possible del(tup2) #trying to delete tuple element will throw error del(tup1[0]) except TypeError: print "Tuple doesn't support deletion" def convertToList(tup1): return list(tup1) print list1 list1.append(123) print list def appendValueToList(list1,value): list1.append(value) if __name__ == "__main__": try: #printing elements in tuple tuple1 = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") printTupleElements(tuple1) tuple2 = ("January","February","March","April","May","June","July","August","September","October","November","December") printTupleElements(tuple2) #concatenating tuples tuple1 = concatenateTuples(tuple1,tuple2) printTupleElements(tuple1) #finding greater tuple tup1 = (34,23,45,12,25,67,89,33,77) tup2 = (5,53,65,45,36,67,76,99,10) tup3 = (66,55,1,23,9,98,76,45,34,33) findingGreaterTuple(tup1,tup2,tup3) #tying to delete tuple element and entire tuple delTuple(tup1,tup2) #typecating to list list1 = convertToList(tup1) #inserting value into list appendValueToList(list1,123) print list1 except Exception as e: print(e)
false
c37d21f2729953d3d553935f57b409171148a7d7
mykisscool/doing-math-with-python
/Chapter 1/2_enhanced_multiplication_table_generator.py
891
4.21875
4
""" Enhanced Multiplication Table Generator """ def multi_table(a, b): for i in range(1, b + 1): print('{0} x {1} = {2}'.format(a, i, a * i)) if __name__ == '__main__': # 5: Give Exit Power to the User while True: ''' The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't. ''' try: a = int(input('Please enter the number to be multiplied: ')) b = int(input('Please enter the number of multiples of the first number: ')) multi_table(a, b) except ValueError: exit('An invalid integer was inputted.') answer = input('Do you want to exit? (y) for yes ') if answer == 'y': break
true
0fb33d1900e0bf5e5bd20a9accf5fe18c9167897
Akshaytomar893/Strings
/Isomorphic String.py
810
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. #leetcode : https://leetcode.com/problems/isomorphic-strings/ #python code : def isIsomorphic(self, s: str, t: str) -> bool: dic={} lis=[] l=len(s) for i in range(l): c1=s[i] c2=t[i] if c1 not in dic and c2 not in lis: dic[c1]=c2 lis.append(c2) elif c1 in dic and dic[c1] !=c2: return False elif c1 not in dic and c2 in lis: return False return True
true
96faa26b410a378ae2da6f9b241900c23fde0651
kumargagank/pytthon
/def add(x,y).py
609
4.125
4
def add(x,y) return x+y def substract(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=int(input("enter the first number:")) num2=int(input("enter the second number:")) if choice =='1': print(num1,"+",num2,"=",add(num1,num2)) elif choice =='2': print(num1,"-",num2,"=",subtract(num1,num2)) elif choice =='3' print(num2,"*",num2,"=",multiply(num1,num2)) elif choice =='4': print(num2,"/",num2,"=",divide(num1,num2)) else:print("invalid inputS")
false
6653cff9a769a3a03c027ca3eefd44af94c760ff
JorgeSchelotto/Practica-4---Seminario-Python
/Ejercicio2.py
2,500
4.1875
4
""" Dado el archivo utilizado con datos de jugadores del Ejercicio 3 de la Práctica 3, implemente una función que reciba el nombre del archivo como parámetro y maneje con excepciones el caso que el archivo no exista, informando dicha situación.""" import json jugadores = {} clave = {} def modifica_datos(): # leo jugador a buscar print() nom = input('ingrese el jugador a buscar: ') # cargo el diccionario almacenado en el txt. E el bloque try busco si el # jugador existe para actualizar sus datos. Sino existe, lo agrego mediante # el bloque except. En finally imprimo el diccionario completo. with open('json.txt', 'r+') as f: d = json.load(f) try: print('Los datos del jugador ',nom,' son: ',d[nom]) print('Actualice los datos del jugador: ', nom) nivel = input('Ingrese el nuevo nivel: ') puntaje = int(input('Ingrese el nuevo puntaje: ')) horasJuego = input('Ingrese las nuevas horas de juego: ') clave['nivel'] = nivel clave['puntaje'] = puntaje clave['horas'] = horasJuego d[nom] = clave.copy() except (KeyError): print() print('El jugador no existe. Cargue los datos de: ', nom, ', nuevo jugador.') nivel = input('Ingrese el nuevo nivel: ') puntaje = int(input('Ingrese el nuevo puntaje: ')) horasJuego = input('Ingrese las nuevas horas de juego: ') clave['nivel'] = nivel clave['puntaje'] = puntaje clave['horas'] = horasJuego d[nom] = clave.copy() # imprimo versión final del diccionario finally: print() print('Último registro de jugadores: ') print(d) # carga inicial de jugadores y sus datos nombre = input('Ingrese Nombre del jugador. Ingrese "fin" para cortar la carga: ') while(nombre != 'fin'): nivel = input('Ingrese Nivel del jugador: ') puntaje = input('Ingrese puntaje del jugador: ') horasJuego = input('Ingrese horas de juego del jugador: ') clave['nivel'] = nivel clave['puntaje'] = puntaje clave['horas'] = horasJuego jugadores[nombre] = clave.copy() nombre = input('Ingrese Nombre del jugador: ') # guardo el diccionario de jugadores en archivo de texto plano file = open('json.txt', 'w') json.dump(jugadores,file) file.close() print() print('diccionario inicial: ') print(jugadores) modifica_datos()
false
d933a3d320c54d9b4e108a2edb68cccfa1d26587
AbdallahElGhamry/Python-Programming-Exercises
/Decision Structures/6. Software Sales.py
796
4.1875
4
''' A software company sells a package that retails for $99. Quantity discounts are given according to the following table: Quantity Discount 10–19 10% 20–49 20% 50–99 30% 100 or more 40% Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount. ''' qnt = int(input('Enter the quantity: ')) disc = 0.0 if qnt >= 100: disc = 40/100 elif qnt >= 50 and qnt <= 99: disc = 30/100 elif qnt >= 20 and qnt <= 49: disc = 20/100 elif qnt >= 10 and qnt <= 19: disc = 10/100 print('Discount Percentage:', disc) print('Discount Value:', disc * qnt) print('Total Amount:', qnt + disc * qnt )
true
c88f233573a6b85252068141cc7f96c732c5b2f3
AbdallahElGhamry/Python-Programming-Exercises
/Decision Structures/4. Roulette Wheel Colors.py
1,536
4.5625
5
''' On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are as follows: Pocket 0 is green. For pockets 1 through 10, the odd-numbered pockets are red and the even-numbered pockets are black. For pockets 11 through 18, the odd-numbered pockets are black and the even-numbered pockets are red. For pockets 19 through 28, the odd-numbered pockets are red and the even-numbered pockets are black. For pockets 29 through 36, the odd-numbered pockets are black and the even-numbered pockets are red. Write a program that asks the user to enter a pocket number and displays whether the pocket is green, red, or black. The program should display an error message if the user enters a number that is outside the range of 0 through 36. ''' num = int(input('Enter an integer in range of 0 through 36: ')) if num == 0: print('Pocket', num, 'is green') elif num >= 1 and num <= 10: if num % 2 == 0: print('Pocket', num, 'is black') else: print('Pocket', num, 'is red') elif num >= 11 and num <= 18: if num % 2 == 0: print('Pocket', num, 'is red') else: print('Pocket', num, 'is black') elif num >= 19 and num <= 28: if num % 2 == 0: print('Pocket', num, 'is black') else: print('Pocket', num, 'is red') elif num >= 29 and num <= 36: if num % 2 == 0: print('Pocket', num, 'is red') else: print('Pocket', num, 'is black') else: print('Invalid input.')
true
707869713e87750ec6c1356f4defc3e68f9ea242
karadisairam/Loops
/45.py
259
4.21875
4
for x in range(5): print(x) #To display numbers 0 to 10: for x in range(11): print(x) #Odd numbers in 0 to 20 : for x in range(21): if x%2!=0: print(x) #Even numbers : for i in range(10): if i%2==0: print(i)
false
58ab85b8a7b00945bb1dbf69893d5c3f53480895
rollinscms430/Project-2-Search-nkirpalani
/anagrams.py
1,016
4.15625
4
#NSK, 2017 from collections import defaultdict ''' Loading tuple dictopnary with words from file using rstrip() which returns a copy of the string in which all chars have been stripped from the end of the string. ''' def load_words(filename='words.txt'): with open(filename) as f: tuples = [] for word in f: tuples.append(word.strip()) return tuples ''' Generating anagrams from the list of words in the dictionary by sorting the word alphabetically and then checking it against other words in the dictionary to see if they match up ''' def get_anagrams(source): dd = defaultdict(list) for word in source: key = "".join(sorted(word)) dd[key].append(word) return dd ''' Prints the anagrams pairings. ''' def print_anagrams(word_source): dd = get_anagrams(word_source) for key, anagrams in dd.iteritems(): if len(anagrams) > 1: print(anagrams) word_source = load_words() print_anagrams(word_source)
true
b2e9047f39d4589640e8d24b04da11b70ce19a3b
harshalb7/Python-Programming
/mathOperation.py
581
4.125
4
def addtion(num1, num2): return num1 + num2 def subtraction(num1, num2): return num1 - num2 def multiplication(num1, num2): return num1 * num2 def division(num1, num2): if num2 != 0: return num1/num2 else: print("Divide by Zero Error") #print("Enter Numbers: ") num1 = float(input(" Number 1: ")) num2 = float(input(" Number 2: ")) print(" Addition is : ",addtion(num1, num2)) print(" Subtraction is : ",subtraction(num1, num2)) print(" Multiplication is: ",multiplication(num1, num2)) print(" Division is : ",division(num1, num2))
false
fdd3f44f9134cb6d4883028607a621aab324544e
tarunteja04/cs5590-python-deep-learning
/python/ICP 1/Source/Digits and Number counting.py
531
4.15625
4
data=input("enter a string") # Taking a string from user letters=numbers=0 # Initially taking letters and numbers as zero for i in data: if i.isdigit(): # checking whether it is a digit or not numbers =numbers+1 # storing that digit in the numeric elif i.isalpha(): # checking whether it is a alphabet or not letters =letters+1 # storing that word in the letters print(numbers) # printing numbers print(letters) # printing letters
true
a8a95401de57afff950c9daa0d3ebc00a6f71d97
uchenna-j-edeh/advanced_data_structures
/trees.py
2,155
4.15625
4
from unittest import TestCase class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insertLeft(self, nodeData): """ If node has no left child, add a node to the tree When node has a left child however, insert a node and push the existing child downone level in the tree Mirror the same thing in right """ if self.left == None: self.left = Node(nodeData) else: t = Node(nodeData) t.left = self.left self.left = t def insertRight(self, nodeData): if self.right == None: self.right = Node(nodeData) else: t = Node(nodeData) t.right = self.right self.right = t def getRight(self): return self.right def getLeft(self): return self.left def setRootValue(self, data): self.data = data def getRootValue(self): return self.data def BuildSpecialTree(): nodeA = Node('a') nodeA.insertRight('c') nodeA.insertLeft('b') nodeA.getRight().insertRight('f') nodeA.getRight().insertLeft('e') # nodeA.left = Node('d') nodeA.getLeft().insertRight('d') return nodeA if __name__ == '__main__': # node = Node('a') # print(node.getRootValue()) # print(node.getLeft()) # node.insertLeft('b') # print(node.getLeft()) # print(node.getLeft().getRootValue()) # node.insertRight('c') # print(node.getRight()) # print(node.getRight().getRootValue()) # node.getRight().setRootValue('Hello Uchenna') # print(node.getRight().getRootValue()) # root = BuildSpecialTree() ttree = BuildSpecialTree() # ttree.getRightChild().getRootVal() if ttree.getLeft().getRight().getRootValue() == 'd': print("Success! d is Right child of b") if ttree.getRight().getLeft().getRootValue() =='e': print("Success! e is left child of c") print(ttree.getRight().getRootValue()) if ttree.getRight().getRootValue() == 'c': print("Success! c is Right child of a")
true
8d4e15b9469bf3995f028159220c368a65f05477
jwcheong0420/TIL
/language/python/opentutorials-lecture/string.py
873
4.46875
4
print("=== String ===") print('Hello') print("Hello") #print('Hello") #SyntaxError: EOL while scanning string literal #print('Hello 'world'') #SyntaxError: invalid syntax print("Hello 'world'") print('Hello "world"') print("=== String control ===") print('Hello ' + 'world') print('Hello '*3) #print('Hello ' - 'world') #TypeError: unsupported operand type(s) for -: 'str' and 'str' print('Hello'[0]) print('Hello'[1]) print('Hello'[2]) print('Hello'[3]) print('Hello'[4]) print("=== String control2 ===") print('hello world'.capitalize()) print('hello world'.upper()) print('hello world'.__len__()) print(len('hello world')) print('hello world'.replace('world', 'programming')) print("=== Escape character ===") print("hello\tworld\n!\\\a") print('hello\tworld\n!\\\a') print("=== Number and String ===") print("10+5 :", 10 + 5) print("\"10\"+\"5\" : " + "10" + "5")
false
975086efaaa919404fa684488fbcd4c65c503c45
ujjwaltambe03/PythonDemo
/Radio_button.py
823
4.125
4
# A radio button is a widget that allows the user to choose only one of a predefined options. # syntax : Rbttn = Radiobutton(master, option..........) from tkinter import * def Retreive_data(): var2.set(var1.get()) root = Tk() root.geometry("480x340") frame = Frame(root) frame.pack() var1 = IntVar() var2 = StringVar() # creating option 1 and 2 Rad_Button_1 = Radiobutton(frame, text = "Option_1", variable = var1,value = 1) Rad_Button_1.pack() Rad_Button_2 = Radiobutton(frame, text = "Option_2", variable = var1,value = 2) Rad_Button_2.pack() # label to print which option choosed label = Label(frame, textvariable= var2, width = 10, bg = 'grey') label.pack() # submit button to submit selected option Sub_button = Button (frame, text = "Submit", command = Retreive_data) Sub_button.pack() root.mainloop()
true
d5b43f00da6e3b1ca7b5c0a4154a2f3685abe828
mihirakaranam/Coursera_IIPP
/week4/week4a/week4a_practice_exercise_2.py
496
4.1875
4
# List reference problem ################################################### # Student should enter code below a = [5, 3, 1, -1, -3, 5] b = a b[0] = 0 print a print b ################################################### # Explanation # The assignment b = a created a second reference to a. # Setting b[0] = 0 also mutated the list that both # a and b reference. As a result, a[0] == 0. # See the Programming Tips videos for a more detail # explanation and examples
true
0de5779a615203dd0710fe663c287e105de7a76b
AviaTorX/Digit-Recognition
/src/NeuralNetworkCreation.py
807
4.25
4
import numpy as num class NetworkLayers(object): #It will create Neural Network Architecture and Assign Weights and Biases to #np.random.randn function to generate #Gaussian distributions with mean and standard deviation in given range #if we want to create neural network with 3 layers we create NetworkLayers #object like net = NetworkLayers([2, 3, 1]) means #first layer contain 2 input neuron hidden layer contain 3 neurons #nuber of hidden layer = 1 and one output layer contain 1 neuron def __init__(self, configuration): self.number_of_layers = len(configuration); self.configuration = configuration; self.weights = [np.random.randn(y, 1) for y in configuration[1:]] self.biases = [np.random.randn(y, x) for x, y in zip([:-1], [1:])]
true
3f9ad579246727df4a26bebe3c1081c0a4cbefd8
valken24/IA-Studies
/MODEL_CLASS/Python Basic/strings.py
861
4.21875
4
myStr = "Hello World" print("My name is " + myStr) print(f"My name is {myStr}") print("My name is {0}".format(myStr)) # myStr_2 = "Hello_World" #Opciones para myStr #print(dir(myStr)) # print(myStr.upper()) # print(myStr.lower()) # print(myStr.swapcase()) # print(myStr.capitalize()) # print(myStr.replace('Hello', 'bye')) # print(myStr.replace('Hello', 'bye').upper()) #Metodos Encadenados # a = myStr.count('l') # print(a) # b = myStr.startswith('Hola') # print(b) # b = myStr.endswith('World') # print(b) # c = myStr.split() # print(c) # d = myStr_2.split('_') # print(d) # e = myStr_2.split('o') # print(e) # f = myStr.find('o') # print(f) # g = len(myStr) # print(g) # h = myStr.index('e') # print(h) # i = myStr.isnumeric() # j = myStr.isalpha() # print(i,j) # k = myStr[4] # print(k) # l = myStr[-1] # print(l) # m = myStr[-5] # print(m)
false
b5875b14cd960422cdf1ad58d2c16016e902c173
FatemehRezapoor/PythonExercise
/Ex2.py
783
4.4375
4
# June 10, 2018 # Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the # user. Hint: how does an even / odd number react differently when divided by 2? # Extras: #If the number is a multiple of 4, print out a different message. # Date: July 13, 2020 num = input('Type your number:') if int(num)%2 is 0: print(' Number {} is even'.format(num)) if int(num)%4==0: print('Number {} is a multiple of 4'.format(num)) else: print('Number {} is odd'.format(num)) # Date: June 10, 2020 number=int(input('Please inter your number:\t')) if number%2==0: print('Your number is even') if number%4==0: print('This number is 4 multiple') else: print('Your number is odd')
true
3dc19f7d472668e0a72e135ba7fce1c56afcae44
FatemehRezapoor/PythonExercise
/PythonExercise/Ex15.py
523
4.375
4
# June 12, 2018 # For example, say I type the string: My name is Michele # Then I would see the string: Michele is name My shown back to me. sen='My name is sara' sent=sen.split(' ') # METHOD 1 senr=list(reversed(sent)) for x in senr: print(x,end=' ') # Avoids the print command from printing in a new line # METHOD 2 a=' '.join(reversed(sent)) print(a) # JOIN IN PYTHON # Joins a sequence of elements s = "-"; seq = ("a", "b", "c"); # This is sequence of strings. print (s.join( seq ))
true
25bc058398981b237796deed186a2a18f3892d0b
Tansir93/PythonStudy
/PythonStudy/FirstPython/使用list和tuple.py
1,298
4.40625
4
print("/n/n") print("~~~~~~~~~~~~~~~~~list~~~~~~~~~~~~~~~~~~") classmates = ['Michael', 'Bob', 'Tracy']#list是一种有序的集合 print(classmates) print(len(classmates))#获取list元素个数 print(classmates[0]) print(classmates[-1])#取最后一个元素 classmates.append('Adam')#追加元素到末尾 print(classmates) classmates.insert(1,"jack")#插入指定位置 print(classmates) classmates.pop(1)#删除指定位置元素 print(classmates) classmates[1]='sarah'#赋值 print(classmates) classmates=[123,'apple',True]#允许不同数据类型 print(classmates) classmates=[123,'apple',[123,'pop'],True]#list元素也可以是另一个list print(classmates) print(classmates[2][1])#获取嵌套list中元素 print("/n/n") print("~~~~~~~~~~~~~~~~~tuple~~~~~~~~~~~~~~~~~~") classmates = ('Michael', 'Bob', 'Tracy')#classmates这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,tuple使用(),list使用[]。 t=(1,2) print(t)#(1,2) t=()#定义空tuple print(t)#() t=(1)#括号()既可以表示tuple,又可以表示数学公式中的小括号 print(t)#1 t=(1,)#只有1个元素的tuple定义时必须加一个逗号,,来消除歧义 print(t)#(1,) t = ('a', 'b', ['A', 'B']) t[2][0] = 'X' t[2][1] = 'Y' print(t)
false
feeeb57bf97b74bfbd42d3f0a507cc38f50f4e4f
ogaroh/lpthw
/ex3.py
971
4.34375
4
# PS: # we are using the American standard in the order of execution of the arithmetic operations # (PEMDAS - Parentheses, Exponents, Multiplication, Division, Addition, Subtraction) print("I will now count my chickens: ") # addition and division print("Hens: ",25 + 30 / 6) # subtraction, multiplication & modulus* print("Roosters :", float(100 - 25 * 3 % 4)) # addition, subtraction, multiplication, division, modulus print("Now I will count my eggs: ") print(float(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)) # less than operation (comparator) print("Is it true that 3 + 2 < 5 - 7?") print(float(3 + 2) < float(5 - 7)) print("What is 3 + 2? ", float(3 + 2)) print("What is 5 - 7? ", float(5 - 7)) print("Oh that is why it's false.") print("How about some more? ") # greater than print("Is it greater? ", 5 > -2) # greater than or equal to comparator print("Is it greater or equal? ", 5 >= -2) # less than or equal to comparator print("Is it less or equal? ", 5 <=-2)
true
99e206828b296637d6454faaa00dad6a7933ad92
ogaroh/lpthw
/ex15.py
542
4.28125
4
from sys import argv # uses argv to get file names --> method 1 script_name, filename = argv # creates the file object so that you can read or write to it txt = open(filename) print(f"here is your {filename} file.") # shows the contents of the file specified print(txt.read()) # requires user to manually enter the file name --> method 2 filename_again = input("Enter your file name: \n\t>>> ") # open the file specified txtfile_again = open(filename_again) # prints out the contents of the file specified print(txtfile_again.read())
true
79f5012df575349d232f21155c78cb473bbf5d61
yulyzulu/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,137
4.21875
4
#!/usr/bin/python3 """ Module to execute the function to divides elements of a matrix. """ def matrix_divided(matrix, div): """ Function that divides all elements of a matrix. """ if type(matrix) != list: raise TypeError("matrix must be a matrix (list of lists)\ of integers/floats") if div == 0: raise ZeroDivisionError("division by zero") if type(div) != int and type(div) != float: raise TypeError("div must be a number") if len(matrix) < 1: raise TypeError("matrix must be a matrix (list of lists)\ of integers/floats") for i in matrix: if type(i) != list: raise TypeError("matrix must be a matrix (list of lists)\ of integers/floats") length = len(matrix[0]) if length != len(i): raise TypeError("Each row of the matrix must have the same size") for j in i: if type(j) != int and type(j) != float: raise TypeError("matrix must be a matrix (list of lists)\ of integers/floats") return (list(map(lambda i: list(map( lambda j: round(j / div, 2), i)), matrix)))
true
10b3e3ca4d8d51ef4bd07d04fbf90c5b0c11b571
chethan-kt/Python-Exercises
/q46.py
377
4.21875
4
""" Question: Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. Hints: Use def methodName(self) to define a method. """ class Circle: def __init__(self, rad): self.radius = rad def area(self): print "Area of a circle is ", 3.14*(self.radius**2) c1 = Circle(2) c1.area()
true
2a3ed43cf2817ef3b0b8bf0246306834e17f745d
lucasrodrix/aula_python
/aula6.py
1,369
4.375
4
# #Aula 6 - Fundamentos em Python # conjunto = {1,2,3,4} # conjunto.add(5) # conjunto.discard(3) # print(conjunto) conjunto1 = {1,2,3,4,5} conjunto2 = {5,6,7,8,9} conjuntoUniao = conjunto1.union(conjunto2) print("União entre Conjunto 1 e 2: {}".format(conjuntoUniao)) conjuntoInter = conjunto1.intersection(conjunto2) print("Intersecção entre o Conjunto 1 e 2: {}".format(conjuntoInter)) conjuntoDifer1 = conjunto1.difference(conjunto2) conjuntoDifer2 = conjunto2.difference(conjunto1) print("Diferença entre Conjunto 1 e 2: {}".format(conjuntoDifer1)) print("Diferença entre Conjunto 2 e 1: {}".format(conjuntoDifer2)) conjuntoDifeSimetr1 = conjunto1.symmetric_difference(conjunto2) conjuntoDifeSimetr2 = conjunto2.symmetric_difference(conjunto1) print("Diferença Simétrica entre Conjunto 1 e 2: {}".format(conjuntoDifeSimetr1)) print("Diferença Simétrica entre Conjunto 2 e 1: {}".format(conjuntoDifeSimetr2)) conjuntoA = {1,2,3} conjuntoB = {1,2,3,4,5,6} conjuntoSubset = conjuntoA.issubset(conjuntoB) print("A é subconjunto de B: {}".format(conjuntoSubset)) conjuntoSuperset = conjuntoB.issuperset(conjuntoA) print("B é um superconjunto de A: {}".format(conjuntoSuperset)) lista = ['cachorro', 'gato', 'gato', 'elefante'] print(lista) conjuntoAnimais = set(lista) print(conjuntoAnimais) listaAnimais = list(conjuntoAnimais) print(listaAnimais)
false
e9625d7ba880a8c1adfacbb2902436faa8f3f091
regithiel/python-homework
/homework_1.py
1,128
4.4375
4
# Catarina Soeiro # January 26 2016 # homework_1.py ##### Template for Homework 1, exercises 1.2-1.5 ###### # Do your work for Exercise 1.2 here print " | | " print "-----" print " | | " print "-----" print " | | " print "********** Exercise 1.3 **********" a = " | | " b = "-----" print a print b print a print b print a print "********** Exercise 1.4 **********" print "********* Part II *************" a = (3*5)/(2+3) print "a is " + str(a) b = ((7+9)**0.5)*2 print "b is " + str(b) c = (4-7)**3 print "c is " + str(c) d = (-19+100)**0.25 print "d is " + str(d) e = 6 % 4 print "e is " + str(e) print "********* Part III *************" #assign equations to variable names e1 = (3+4)*5+(-10/2) e2 = (3+4*5)+(-10/2) #print result print e1 print e2 print "********** Exercise 1.5 **********" #collect name info from user name1 = raw_input('Enter your first name: ') name2 = raw_input('Enter your last name: ') #collect birth date from user print 'Enter your date of birth:' mo = raw_input('Month? ') day = raw_input('Day? ') year = raw_input('Year? ') #print result print name1, name2, 'was born on', mo, day+',', year+'.'
false
fdf8fda907a1354ef5ba43ae5e0030186c0164c5
kawalot/checkio
/Digits-Multiplication.py
545
4.3125
4
#You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes. #For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes). #Input: A positive integer. #Output: The product of the digits as an integer. def checkio(number): eval = 1 for digit in str(number): if int(digit) == 0: continue else: eval = eval * int(digit) return eval print(checkio(123405)) print(checkio(999)) print(checkio(1000)) print(checkio(1111))
true
2043bdaa42162dc495174f8034c3ca1c19bd8796
kawalot/checkio
/The-Most-Numbers.py
987
4.46875
4
#Determine the difference between the smallest and the biggest numbers. #You are given an array of numbers (floats). #You should find the difference between the maximum and minimum element. #Your function should be able to handle an undefined amount of arguments. #For an empty argument list, the function should return 0. #Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. #So we should check the result with ±0.001 precision. #Think about how to work with an arbitrary number of arguments. #Input: An arbitrary number of arguments as numbers (int, float). #Output: The difference between maximum and minimum as a number (int, float). def checkio(*args): if len(args) < 1: return 0 else: min = args[0] max = args[0] for i in args: if min > i: min = i if max < i: max = i print("min =", min, "max =", max ) return max - min print(checkio(10.2, -2.2, 0, 1.1, 0.5))
true
52acb5bf56135c2731caa0d0b007c8528a01d2ef
SentientSam/Dice_Roll
/Dice_Roll.py
2,722
4.375
4
# Name : Dice_Roll.py # Author : Samuel Lamb # Purpose : Software to emulate rolling a dice, allowing for any size dice to be selected import random while(True): validEntry = False # Variable to check for a valid (or supported) dice Result = 0 Sides = int(input("Please enter number of sides (Enter 0 to leave): ")) # User enters an integer value for number os sides of dice if (Sides == 10): # For use with DnD, if they are rolling a d10 then it is a percentage roll consisting of two dice validEntry = True randRoll = random.randint(0,9) percentRoll = random.randrange(00,90,10) print("You rolled:",percentRoll,"and:",randRoll) if (randRoll == 0 and percentRoll == 0): Result = 100 else: Result = randRoll + percentRoll if (Sides == 0): # If 0 is entered, exit program and flag validEntry so that the score is not posted validEntry = True print("Thank you! Good luck") break if (Sides == 8): Quantity = int(input("How many do you want to roll?: ")) validEntry = True while(Quantity != 0): randRoll = random.randint(1,8) Quantity = Quantity - 1 print("You rolled:",randRoll) Result += randRoll if (Sides == 6): Quantity = int(input("How many do you want to roll?: ")) validEntry = True while(Quantity != 0): randRoll = random.randint(1,6) Quantity = Quantity - 1 print("You rolled:",randRoll) Result += randRoll if (Sides == 4): Quantity = int(input("How many do you want to roll?: ")) validEntry = True while(Quantity != 0): randRoll = random.randint(1,4) Quantity = Quantity - 1 print("You rolled:",randRoll) Result += randRoll if (Sides == 20): Quantity = int(input("How many do you want to roll?: ")) validEntry = True while(Quantity != 0): randRoll = random.randint(1,20) Quantity = Quantity - 1 print("You rolled:",randRoll) Result += randRoll if (Sides == 12): Quantity = int(input("How many do you want to roll?: ")) validEntry = True while(Quantity != 0): randRoll = random.randint(1,12) Quantity = Quantity - 1 print("You rolled:",randRoll) Result += randRoll if(validEntry == False): # If not valid entry, repeat loop but inform user that the type of dice they entered is not supported print("That type of dice is not supported or does not exist, please try again!") if(Sides == 10): # If a d10, the result will be a percentile print("Your score is: ",Result,"%") else: if(validEntry == True): print("Your score is: ",Result)
true
59a5d9c2c5942457919e92613191e758a82829d7
lijiyan77/API_pytest_new
/pyTest/aaatest/test_0330.py
1,903
4.21875
4
# -*- coding: UTF-8 -*- # @File : test_0330.py # author by : Li Jiyan # date : 2020/3/30 # name='' # while not name.strip(): # name = input('Please enter your name: ') # print('hello, %s' % name) # numbers=[0,1,2,3,4,5,6,7,8,9] # for number in range(0,10): # print(number) # d={'x':1,'y':2,'z':3} # for key,value in d.items(): # print(key,"corresponds to",value) # names=['anne','beth','george','damon'] # ages=[12,45,32,102] # for i in range(len(names)): # print(names[i],'is',ages[i],'years old.') # a=zip(names,ages) # print(list(a)) # for name,age in list(zip(names,ages)): # print(name,'is',age,'years old.') # from math import sqrt # for n in range(99,0,-1): # root = sqrt(n) # if root == int(root): # print(n) # break # word = 'dummy' # while word: # word = input('please enter a word: ') # print('The word was ' + word) # while True: # word = input('Please enter a word: ') # if not word:break # print("The word was " + word) # from math import sqrt # for n in range(99,81,-1): # root = sqrt(n) # if root == int(root): # print(n) # break # else: # print("Didn't find it") # def hello(name): # return ('hello, '+name+'!') # # print(hello('jojo')) # def fibs(num): # result = [0,1] # for i in range(num-2): # result.append(result[-2]+result[-1]) # return result # # print(fibs(10)) # def print_params_3(**params): # print(params) # # print_params_3(x=1,y=2,z=3) # def print_params_4(x,y,z=3,*pospar,**keypar): # print(x,y,z) # print(pospar) # print(keypar) # # print_params_4(1,2,3,5,6,7,foo=1,bar=2) def store(data,*full_names): for full_name in full_names: names = full_name.split() if len(names) == 2:names.insert(1,'') labels = 'first','middle','last' for label,name in list(zip(labels,names)): pass
false
880889547dde4dbef94e8f232b96df99bb26d088
RicardoCuevasR/Codeacademy
/Python/Shorts/likes.py
713
4.15625
4
def likes(names): #your code here if len(names) == 0: print("no one likes this") elif len(names) ==1: print(names[0]+' likes this') elif len(names) == 2: print(names[0]+' and ' + names[1]+' like this') elif len(names) == 3: print(names[0]+', ' + names[1]+' and '+ names[2]+' like this') else: print(names[0]+', ' + names[1]+' and '+str(len(names)-2)+' others like this') likes([]), 'no one likes this' likes(['Peter']), 'Peter likes this' likes(['Jacob', 'Alex']), 'Jacob and Alex like this' likes(['Max', 'John', 'Mark']), 'Max, John and Mark like this' likes(['Alex', 'Jacob', 'Mark', 'Max']), 'Alex, Jacob and 2 others like this'
true
7b555da54d5dfef0f46b1357b2ed2a4ad17ccb4b
igoraugustocostaesouza/SEII-IgorAugustoCostaeSouza
/Semana02/prog02.py
1,730
4.46875
4
#Autor: Igor Augusto #Data: 16/03/2021 # Arithmetic Operators: # Addition: 3 + 2 # Subtraction: 3 - 2 # Multiplication: 3 * 2 # Division: 3 / 2 # Floor Division: 3 // 2 # Exponent: 3 ** 2 # Modulus: 3 % 2 # Comparisons: # Equal: 3 == 2 # Not Equal: 3 != 2 # Greater Than: 3 > 2 # Less Than: 3 < 2 # Greater or Equal: 3 >= 2 # Less or Equal: 3 <= 2 #Aritmética de divisão print(3/2) #Aritmética de pegar o resto inteiro da divisão print(3//2) #Utilização de parenteses para ordenar a as operações aritméticas #Resultado será 7 print(3*2+1) #Resultado será 9 print((2+1)*3) #Incrementar uma variável num = 1 num +=1 print (num) #resultado será 2 #Função abs = valor absoluto de um número print(abs(-3)) #resultado será 3 #Função round = arredonda o número || pode-se informar a quantidade de casas para arredondamento print(round(3.75)) #resultado será 4 print(round(3.75,1)) #resultado será 3.8 #--------- Operadores Lógicos ------------ num_1 = 3 num_2 = 2 #Vai verificar se num1 é igual ao num2, caso verdade True, caso falso False print(num_1 == num_2) #resultado será False #Vai verificar se num1 é diferente do num2, caso verdade True, caso falso False print(num_1 != num_2) #resultado será True #Vai verificar se num1 é maior do num2, caso verdade True, caso falso False print(num_1 > num_2) #resultado será True #Vai verificar se num1 é menor do num2, caso verdade True, caso falso False print(num_1 < num_2) #resultado será False #Converter strings de textos em números #String no formato de texto num_3 = '100' num_4 = '200' #Convertendo a string em inteiro num_3 = int(num_3) num_4 = int(num_4) print(num_3 + num_4)
false
74c0161c03a4b03745500f1a5f48bb4d44bde202
biswanathdehury01/OpenCV-All-Fundamentals
/03_Draw Shapes with Mouse Click Event using OpenCV_1_2.py
2,192
4.34375
4
######################### Chap 3 - Draw Shapes with Mouse Click Event using OpenCV # In[ ]: # ### Drawing Blue Circles on Black Screen by Left Button Click on Mouse # In[1]: #Import Necessary Libraries import cv2 import numpy as np # Create a circle shape function to draw a circle on left button click event def circle_shape(event,x,y,flagval,par): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(image_window,(x,y),50,(255,0,0),-1) # (x,y) are treated as center of circle, with radius 50, with BGR, and -1 => a solid filled structure # Naming the window so we can reference it cv2.namedWindow(winname='Image_Window') # Connecting the mouse button to the callback function cv2.setMouseCallback('Image_Window',circle_shape) # Creating a black image image_window = np.zeros((1024,1024,3), np.uint8) while True: #Keep the black image window open until we break with Esc key on keyboard # Showing the image window cv2.imshow('Image_Window',image_window) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows() # ### Drawing Blue Circles on Black Screen by Left Button Click & Red Color Circle on Right Button Click on Mouse # In[2]: #Import Necessary Libraries import cv2 import numpy as np # Create a circle shape function to draw a blue circle on left button click & red circle on right button click event def circle_shape(event,x,y,flagval,par): if event == cv2.EVENT_LBUTTONDOWN: # left click event cv2.circle(image_window,(x,y),50,(255,0,0),-1) elif event == cv2.EVENT_RBUTTONDOWN: # Right Click Event cv2.circle(image_window,(x,y),50,(0,0,255),-1) # Naming the window for reference cv2.namedWindow(winname='Image_Window') # Connecting the mouse button to the callback function cv2.setMouseCallback('Image_Window',circle_shape) # Creating a black image image_window = np.zeros((1024,1204,3), np.uint8) while True: #Keep the black image window open until we break with Esc key on keyboard # Showing the image window cv2.imshow('Image_Window',image_window) # Coming out of window by pressing Escape key if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows()
true
3162f2fd4cdc036ff2c5d738e84c02b0a103c0f3
vinit911/python-practice-set
/list_1.py
208
4.25
4
''' Python program to interchange first and last elements in a list ''' l1 = [1,2,3,4,5,6] print("List before modification:\t",l1) l1[0],l1[-1] = l1[-1],l1[0] print("List after modification: \t",l1)
false
65ec5511e1077bc2ea20132d4fc884152b2d5694
BauerJustin/Elements-of-Programming-Interviews-in-Python
/Ch.9 Binary Trees/9.15 Exterior/exterior.py
1,153
4.125
4
#code def exterior(tree): def leaf(node): return not node.left and not node.right def left(subtree, boundary): if not subtree: return [] output = [subtree] if boundary or leaf(subtree) else [] output += left(subtree.left, boundary) output += left(subtree.right, boundary and not subtree.left) return output def right(subtree, boundary): if not subtree: return [] output = right(subtree.left, boundary and not subtree.right) output += right(subtree.right, boundary) output += [subtree] if boundary or leaf(subtree) else [] return output return ([tree] + left(tree.left, True) + right(tree.right, True)) if tree else [] # Binary tree base code class BinaryTreeNode: def __init__(self,data=None,left=None,right=None,parent=None): self.data = data self.left = left self.right = right def print_list(A): for i in A: print(i.data) tree = BinaryTreeNode(6, BinaryTreeNode(3, BinaryTreeNode(1, BinaryTreeNode(0), BinaryTreeNode(2)), BinaryTreeNode(5))) # Test print_list(exterior(tree))
true
ee5d83a77a0532313d10cbcee893239f05fd15b1
FriendlyUser/code-algorithm-questions
/python/sample_amazon/eduactive-crack-amazon/number_missing_in_array.py
495
4.1875
4
""" 1. Find the missing number in the array You are given an array of positive numbers from 1 to n, such that all numbers from 1 to n are present except one number x. You have to find x. The input array is not sorted. 3 7 1 2 8 4 5 n = 8, missing number = 6 """ def find_missing(input): n = len(input) + 1 n_sum = sum(input) expected_sum = n * (n + 1) / 2 missing_int = expected_sum - n_sum return missing_int input_list = [3, 7, 1, 2, 8, 4, 5] find_missing(input_list)
true
1ffcdeb6e51ba01fc4b94da6e3b6e327ce8de210
shereen141/learnpython
/pythonbasics/filewrite.py
583
4.34375
4
writeMe = "Some sample text" ''' to open a file in python we use the open function which accepts the filename and the mode in which the file is to be opened.If the file exists then the existing file is openened otherwise a new file is created in the mode passed. The mode can be either write(w) or append(a). where write overwrites the file contents and append, appends to the existing content. ''' fileToWrite = open("examplefilewrite.txt","a") fileToWrite.write(writeMe) #This is an important step which signifies that the operation with the file is #complete. fileToWrite.close()
true
b726cb1c56550af0e1c07dcb6382dd4da09bec07
jeffrisandy/number_guessing_game
/guessing_game.py
2,962
4.28125
4
""" Python Web Development Techdegree Project 1 - Number Guessing Game -------------------------------- """ import random import os def start_game(): """Psuedo-code Hints When the program starts, we want to: ------------------------------------ 1. Display an intro/welcome message to the player. 2. Store a random number as the answer/solution. 3. Continuously prompt the player for a guess. a. If the guess greater than the solution, display to the player "It's lower". b. If the guess is less than the solution, display to the player "It's higher". 4. Once the guess is correct, stop looping, inform the user they "Got it" and show how many attempts it took them to get the correct number. 5. Let the player know the game is ending, or something that indicates the game is over. ( You can add more features/enhancements if you'd like to. ) """ # welcome message welcome() # initiate highscore value high_score = 0 # set initial trial to zero trial = 0 # actual random number num = random.randint(1, 10) while True: trial += 1 guess = get_input() if guess < num: print("It is higher!") elif guess > num: print("It is lower!") else: # inform the user once the guess correct print(f"\nYou got it. It took you {trial} tries.\n") if high_score == 0: # set high_score equal to trial when first attempt high_score = trial # the high score is the least number of trials elif (trial < high_score): high_score = trial # take input whether player want to continue or not game = input("Do you want to continue? [y/n] : ") if game.lower() == 'y': # reset trial trial = 0 # re-generate actual random number num = random.randint(1, 10) welcome() print(f"\nThe HIGHSCORE is {high_score}\n") else: print("\nThank you for playing, Good Bye!") print(f"\nThe HIGHSCORE is {high_score}\n") break def get_input(): # ensure input is an int number and within range 1-10 while True: guess = input("Pick a number between 1 and 10 : ") try : guess = int(guess) if (guess < 1) or (guess > 10): raise ValueError("Try again, your number is outside the guessing range") except ValueError as err: print(err) else: return guess def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def welcome(): clear_screen() print("-" * 38) print(" Welcome to the Number Guessing Game!") print("-" *38) if __name__ == '__main__': # Kick off the program by calling the start_game function. start_game()
true
19fb4f046f9cf172b14966d89fa72c725fd32a3a
chuzhinoves/DevOps_Python_HW3
/6.py
998
4.46875
4
""" Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). """ def int_func(word): return word[0].upper() + word[1:] sentence = input("enter any words: ").split() print(" ".join([int_func(word) for word in sentence]))
false
203c7ee24ed65452344662a98a33aaa255b8b139
sichkar-valentyn/Processing_json_files_in_Python
/json_format.py
1,640
4.125
4
# File: json_format.py # Description: Examples on how to process json files in Python # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Examples on how to process json files in Python with help of json library // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Processing_json_files_in_Python (date of access: XX.XX.XXXX) # Working with files in json formats import json # Creating dictionaries with information about the students student1 = { 'first_name': 'Greg', 'last_name': 'Dean', 'scores': [70, 80, 90], 'description': 'Good job, Greg', 'certificate': True } student2 = { 'first_name': 'Wirt', 'last_name': 'Wood', 'scores': [80, 80.2, 80], 'description': 'Nicely Done', 'certificate': True } # Creating a list with elements of dictionaries data = [student1, student2] # Showing the results with the help of library json print(json.dumps(data, indent=4, sort_keys=True)) # Writing the data inside the file with open('students.json', 'w') as f: json.dump(data, f, indent=4, sort_keys=True) # Loading data from json into the Python object as list with dictionaries data_json = json.dumps(data, indent=4, sort_keys=True) data_again = json.loads(data_json) # Calculating the sum of all scores for the first student print(sum(data_again[0]["scores"])) # Loading data from json file with open("students.json", "r") as f: data_again = json.load(f) # Calculating the sum of all scores for the second student print(sum(data_again[1]["scores"]))
true
77908738d410ed8129e08f8e8f9c0daf425c3fb0
johnytheunbravo/python
/challenge.py
463
4.125
4
# uppercase and reverse = banana and should get back ANANAB print the result def uppercase_and_reverse(word): result = word[::-1] return result print(uppercase_and_reverse("do not go gentle into that good thing").upper()) print(uppercase_and_reverse("lol i forgot what mattan asked me to type.").upper()) print(uppercase_and_reverse("banana").upper()) # if you want to form a function def uper_rev(x): return x.upper()[::-1] print(uper_rev("banana"))
true
3a1b3832537abc58d395b143a5efb5549730cbf1
eliffyildirim1/Wtech-Homeworks
/Homework-2/02_05_Errors_Exceptions_Handling.py
1,155
4.34375
4
#!/usr/bin/env python # coding: utf-8 # # Assignments for "Errors and Exception Handling" # 1. Let us define a division operation inside a function (using `def`) but to get an error, define the denominator as 0. So, type properly except statement. # In[1]: def division(number1, number2): try: result = number1 // number2 print("Result :", result) except Exception as e: print ("'{}' hatası oluştu ! ".format(e)) number1 = int(input("Enter the number to divide:")) number2 = int(input("Enter the divisor:")) division(number1,number2) # 2. It is possible to get multiple errors after the execution of one try block. So, please define an error-exception issue with `NameError` # In[2]: try: print(x) except Exception as e: print ("'{}' hatası oluştu ! ".format(e)) # 3. Please define a function and with this function, generate a `ValueError` exception simply by entering a string instead of numerical value. # In[4]: def num(): try: x=int(input("Bir sayı girin : ")) print(x) except ValueError: print (ValueError) num() # In[ ]: # In[ ]:
true
3814a8939c8f1598fb9069ceb0b0aa3fff6869b7
kacpergrzenda/graph-theory-project
/PythonLabs/rectangle.py
711
4.21875
4
class Rectangle: # Constructor. def __init__(self, height, width): self.height = height self.width = width # Calculate the area. def area(self): # Area is width times height. return self.height * self.width # Calculate the perimeter. def perimeter(self): # Perimeter is height times two plus width times two. return (2 * self.height) + (2 * self.width) # Create Instances. r1 = Rectangle(10, 35) r2 = Rectangle(2, 5) print(f"The area of r1 = {r1.height} x {r1.width} = { r1.area() }") print("The area of the second rectangle is", r2.area()) print("The perimeter of the other rectangle is", r2.perimeter())
true
f05a587b591f6af6d3f676dbaf918c4f1a2b6a13
lianlian-YE/Mypycharm
/Python_file/write_blog/访问限制.py
902
4.125
4
class fruit(object): #定义一个类 atest='this is a test' def __init__(self,name): #定义属性name self.__name=name @property def name(self): return self.__name @name.setter def name(self,name): if isinstance(name,str): self.__name=name else: raise ValueError('name must be str') f1=fruit('apple') #实例化一个对象,name=apple f2=fruit(123) #实例化一个对象,name=123,原则上,我们希望name是一个字符串类型,可是,无法进行参数验证 # print(f1.name) #apple # print(f2.name) #123 print(f1.name) f1.name='banana' #可以直接对属性进行修改 print(f1.name) #banana print(f1.atest) #banana
false
f9e12f4dac413abd7442c2ec6690d4b8a551eefb
rpoliselit/python-for-dummies
/exercises/030.py
492
4.3125
4
""" Make a program that reads a integer number, and returns its parity. ------------------------ Terminal customization (best choices): \33[style;text;backm style: 0,1,4,7. text color: 30~37 background color: 40~47 """ number = int(input('{}Enter a integer number: {}'.format('\33[1;37m','\33[m'))) print('\33[1;35m-=-\33[m'*10) if (number % 2) == 0: print('{} is {}even!{}'.format(number,'\33[1;30;41m','\33[m')) else: print('{} is {}odd!{}'.format(number,'\33[1;30;41m','\33[m'))
true
6fe882f36016d1dc46e77ef84fdb18fa4240b231
rpoliselit/python-for-dummies
/exercises/017.py
1,034
4.25
4
""" Make a program that reads the adjacent and opposite catheta of a rectangle triangle, and returns the hypotenuse length. """ import math print('-'*20) ac = float(input('Adjacent cathetus length: ')) oc = float(input('opposite cathetus length: ')) print('-'*20) #calculating by math.hypot h1 = math.hypot(ac, oc) print('The hypotenuse length is {:.2f} by math.hypot.'.format(h1)) print('-'*20) #calculating by Pythagoras' theorem h2 = math.sqrt(ac ** 2 + oc ** 2) print('The hypotenuse length is {:.2f} by Pythagorean theorem.'.format(h2)) print('-'*20) #calculating by using the amgle angle = math.atan(oc / ac) h3 = ac / math.cos(angle) h4 = oc / math.sin(angle) angle_degrees = math.degrees(angle) print('The angle between adjacent and opposite catheta is {:.1f}º.'.format(angle_degrees)) print('The hypotenuse length is {:.2f} by cos {:.1f}º = {:.2f}.'.format(h3, angle_degrees, math.cos(angle))) print('The hypotenuse length is {:.2f} by sin {:.1f}º = {:.2f}.'.format(h4, angle_degrees, math.sin(angle))) print('-'*20)
false
318fd6e1c833584aca292e523a30a3028bcb96ad
rpoliselit/python-for-dummies
/exercises/057.py
532
4.1875
4
""" Make a game that cpu choose a number, and player must guess. The game runs until player hit the guess. """ from random import randint cpu = randint(0,10) guess = player = 0 print('Guess a number between 0 and 10') while player != cpu: player = int(input()) guess += 1 if player > cpu: print('Try a lesser one!') elif player < cpu: print('Try a greather one!') print('You got it right with ', end = '') if guess == 1: print('the FIRST guess!') else: print('{} hunches!'.format(guess))
true
306cbf064c6d98330fc23646323d2287484bec96
rpoliselit/python-for-dummies
/exercises/081.py
679
4.3125
4
""" Make a program that reads several values and registers in a list. Make other list with even numbers and another one with odd numbers. Show all lists. """ numbers, even, odd = [], [], [] while True: num = input('Enter any number ['' stops]: ').strip().lower() if num.isalnum() == False: break elif num.isnumeric() == False: print('Try again. This is not a number.') elif int(num) not in numbers: numbers.append(int(num)) for n in numbers: if n % 2 == 0: even.append(n) else: odd.append(n) print(f'All numbers: {sorted(numbers)}') print(f'Even numbers: {sorted(even)}') print(f'Odd numbers: {sorted(odd)}')
true
688eefa12611f6d19472efda8904f77311dbd17c
rpoliselit/python-for-dummies
/exercises/071.py
558
4.40625
4
""" Make a program that has a tuple fully populated by a count, from 0 to 20. Your program should read a number from the keyboard, and display it written. """ tuple = ('zero', 'one', 'two', 'three', 'four', 'five', \ 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', \ 'twelve', 'thirteen', 'fourteen', 'fifteen', \ 'sixteen', 'seventeen', 'eighteen', 'nineteen', \ 'twenty') num = -1 while num not in range(0,21): num = int(input('Enter a number between 0 and 20: ')) print(f'The chosen number is {tuple[num]}.')
true
5444981935267fb575c5962b0a460c4cbc1a7c47
rpoliselit/python-for-dummies
/exercises/101.py
829
4.5
4
""" Make a program that has a factorial function, which one gets to parameters: 1 - integer number 2 - logical value (optional) that indicates whether the calculation process is shown or not. """ def factorial(number, show=False): """ -> Calculate the factorial of a integer number. :parameter number: Number to be calculate. :parameter show: (optional) Show the calculation process. :return: Factorial of number. """ num = count = 1 print('-'*40) while count <= number: num *= count if show == True: print(f'{count}', end = '') if count < number: print(end = ' x ') elif count == number: print(end = ' = ') count += 1 return num #Main program #help(factorial) print(factorial(5, show = True))
true
5c99608d5acae4298597d87a462602e20113ae94
rpoliselit/python-for-dummies
/underscore/us001.py
223
4.40625
4
""" 2 - The underscore is used to ignore a given value. You can just assign the values to underscore. """ x, _ , z = (1,2,3) print(x, z) a, *_ , b = (1,2,3,4,5) print(a,b) for _ in range(10): print('hello world')
true
1f6f0c463871286e1537f6725b94c07d0db09b23
rpoliselit/python-for-dummies
/exercises/007.py
342
4.21875
4
""" Make a code that reads the score of a student, and calculate this mean. """ tests = [] number = int(input('What is the number of tests? ')) sum = 0 for i in range(number): tests.append(float(input('Score of test {}: '.format(i+1)))) sum = sum + tests[i] mean = sum / len(tests) print('The mean score is: {:.2f}'.format(mean))
true
9c5fb759051dfcdc71638d79f49b907f282c3ff9
rpoliselit/python-for-dummies
/exercises/062.py
419
4.1875
4
""" Make a program that show the n first elements of Fibonacci. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 """ print('{:=^40}'.format(' FIBONACCI ')) num = int(input('\nHow many Fibonacci elements do you want? ')) n = count = 0 while count != num: print('{}'.format(n), end = ' ') count += 1 if n == 0: n += 1 prev = 0 else: n = n + prev prev = n - prev print('\n')
false
8c225192a42331d6b3b69792a9ee227435bdaa58
nkanungo/session12_epfi
/calculator/cos_module.py
439
4.34375
4
""" Created on Tue Oct 27 16:30:27 2020 @author: Nihar Kanungo """ import math __all__ = ['cos'] def cos(x): ''' Calculates the cos of the given value FInd out the derivative of the cos of the given value ''' print(f'the value of cos of given input is: {math.cos(x)}') return math.cos(x) def der_cos(x): print(f'the value of the derivative of cos for given input is : {-(math.sin(x))}') return -(math.sin(x))
true
a7dfdb9022f668e3d07e6c9047fb2a6978ec14e6
rohittwr55/LetsUpgradeAssignment
/Day 2 Assignment.py
2,265
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 3 09:36:56 2020 @author: nitish """ #-------------------------------------- #List And their default functions lis=[1,2,"Rohit"] print("Lists",lis) lis.append("Tiwari") #Adding new element print(lis) print(lis.count("Rohit")) #counting particular number lis.reverse() #Reverse a string print(lis) lis.insert(1,"Mukesh") #to insert eelemet at particular index print(lis) lis2=lis.copy() #Copy list to another list print(lis2) lis2.extend(["Suresh"]) #To use of extend method print(lis2) lis2.remove("Tiwari") #To remove Particular element print(lis2) lis2.clear() #To use clear method print(lis2) lis2=[1,2,3,4] lis2.remove(2) #To use remove method print(lis2) lis2.pop(2) # To use remove method print(lis2) #--------------------------------------- #Dictionary dic={"Name":"Rohit","Age":24,"Degree":"MCA"} #Dictionary print("Dictionaru 1",dic) dic2=dic.copy() # Copy method print("Dictionaru 2",dic2) dic2["Height"]= 5.5 #Add new Item print(dic2) dic2["Name"]="Rohit Tiwari" # Updating perticular item print(dic2) del dic2["Height"] #Deletig particular item print(dic2) del dic2 #Deleting A dictionary #----------------------------------------- #Sets #Defining Sets st={"Rohit","Letsupgrade","Rohit","Letsupgrade",1,2,3} print("Sets" ,st) st.add("Hello") #Add element print(st) st2=st.copy() #copy Method print("Sets 2",st2) st2.update(["Tiwari","Python"]) #Update Method print("Set2", st2) st2.remove("Tiwari") #Remove a particular item print("Set2",st2) st3=st.union(st2) #USe of Union method print("Set 3", st3) st4=st.intersection(st2) #Intersection print(st4) #------------------------------------------ #Tupple tup=("Rohit","Tiwari",410) print("Tupple",tup) x=tup.count(410) #Count print(x) #------------------------------------------------- #String and Default method name="Rohit tiwari is my name" n=name.capitalize() #conver First leter to capital letter print(n) n=name.count("m")# To count number of word alphabet print(n) #To find the word at perticular index n=name.index("tiwari") print(n) n=name.lower() #To conver the letter to lower case print(n) n=name.upper() #To conver the letter to Upper case print(n)
true
2d43a286af1687d2a612d120f4918e4b8ec8be11
kwiseth/CIS-024
/2_assign/math_basics_better.py
978
4.34375
4
#!/usr/bin/python3.6/math_basics_better.py """Exercise P2.5. Script that prompts user for two integers and then exercises Python's math library to perform basic summary calculations, printing the results. Script uses format operator. """ print("\nEnter two different integers as prompted below to see the sum,\ndifference, \ product, average, distance between the two numbers, and\nmaximum and minimum \ values.\n") print("=" * 60) first_num = int(input("Enter the first integer: ")) second_num = int(input("Enter the second integer: ")) print("-" * 60, "\n") print("Sum: %10d" % (first_num + second_num)) print("Difference: %10d" % (first_num - second_num)) print("Product: %10d" % (first_num * second_num)) print("Average: %13.2f" % ((first_num + second_num)/2)) print("Distance: %10d" % (abs(first_num - second_num))) print("Maximum: %10d" % (max(first_num, second_num))) print("Minimum: %10d" % (min(first_num, second_num))) print("-" * 60, "\n")
true
59030f740f8b1dac5375715c79012791a910a3cc
kwiseth/CIS-024
/3_assign/letter_grades.py
950
4.34375
4
#!/usr/bin/python3.6/letter_grades.py """Exercise P3.12. User enters a letter grade at prompt and the script converts to numeric value. Only VALID_INPUT entries are evaluated. The check for letter_grade[0] != 'F' is not needed if F- and F+ are removed from VALID_INPUT. """ VALID_INPUT = {'A', 'A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+', 'C-', 'D', 'D+',\ 'D-', 'F', 'F-', 'F+'} GRADE_POINTS = {'A' : 4.0, 'B' : 3.0, 'C' : 2.0, 'D' : 1.0, 'F' : 0} letter_grade = input("Enter a letter grade: ").upper() if not letter_grade in VALID_INPUT: exit("Please enter a valid letter grade, A thru F only (A, A+, A-, B, B+, ... F): ") else: grade_pts = GRADE_POINTS[letter_grade[0]] if letter_grade.endswith("-") and letter_grade[0] != 'F': grade_pts = grade_pts - 0.3 if letter_grade.endswith("+") and letter_grade[0] != 'A' and letter_grade[0] != 'F': grade_pts = grade_pts + 0.3 print("The numeric value is", grade_pts)
true
b04c318093fdbd1a9a046abb2a335f6e183d1593
kwiseth/CIS-024
/3_assign/tax_calculator.py
1,584
4.28125
4
#!/usr/bin/python3.6/tax_calculator.py """Exercise P3.25. Computes income tax due based on schedule in book. Tax rates take into account Married or Single filing status. Rates also vary based on three different income levels. """ # Initialize constant variables for the tax rates and rate limits. RATE1 = 0.10 RATE2 = 0.15 RATE3 = 0.25 # These constants should be the threshold values between tax rates RATE1_S_CAP = 8000.0 RATE2_S_CAP = 32000.0 RATE1_M_CAP = 16000.0 RATE2_M_CAP = 64000.0 BASE_TAX_RATE2_S = 800.0 BASE_TAX_RATE3_S = 4400.0 BASE_TAX_RATE2_M = 1600.0 BASE_TAX_RATE3_M = 8800.0 # Obtain income amount and filing status income = float(input("Please enter your income: ")) filing_status = input("Please enter 's' for single or 'm' for married: ").lower() total_tax = 0 # Calculate taxes due on the income amount based on filing status if filing_status == "s" : if income < RATE1_S_CAP : total_tax = RATE1 * income elif income > RATE2_S_CAP : total_tax = BASE_TAX_RATE3_S + (income - RATE2_S_CAP) * RATE3 else : total_tax = BASE_TAX_RATE2_S + (income - RATE1_S_CAP) * RATE2 elif filing_status == "m": if income < RATE1_M_CAP : total_tax = RATE1 * income elif income > RATE2_M_CAP : total_tax = BASE_TAX_RATE3_M + (income -RATE2_M_CAP) * RATE3 else : total_tax = BASE_TAX_RATE2_M + (income - RATE1_M_CAP) * RATE2 elif filing_status != "m" or filing_status != "s": exit("Please enter 'm' for married or 's' for single.") # Print the results. print("The tax due is ${:,.2f}".format(total_tax))
true
d54aba7f63e6ad92dc356165fcbaac321c64979a
kwiseth/CIS-024
/2_assign/math_basics.py
973
4.25
4
#!/usr/bin/python3.6/math_basics.py """Exercise P2.4. Script that prompts user for two integers and then exercises Python's math library to perform basic summary calculations, printing the results. """ print("=" * 80) print("Enter two different integers when prompted below to see the sum, difference,\n\ product, average, distance between the two numbers, and maximum and\nminimum values.") print("=" * 80) first_num = int(input("Enter the first integer: ")) second_num = int(input("Enter the second integer: ")) print("Sum is ", first_num + second_num) print("Difference between first number and second is ", first_num - second_num) print("Product is ", first_num * second_num) print("Average of the two numbers is ", (first_num + second_num)/2) print("Distance between the two integer numbers is ", abs(first_num - second_num)) print("Number with the maximum value is ", max(first_num, second_num)) print("Number with minimum value is ", min(first_num, second_num))
true
94139007515084b9c89628f6da96ae392c6dc29a
jurelou/pypis
/pypis/services/html.py
1,427
4.15625
4
import html from typing import Dict def build_html_text(title: str = "", body: str = "") -> str: """Build a basic html page. Args: title (str): Title used in the HTML <head><title> tag body (str): Content of the <body> HTML tag Returns: HTML string. """ indented_body = "\n ".join(body.split("\n")) text_html = """\ <!DOCTYPE html> <html> <head> <title>{title}</title> </head> <body> {body} </body> </html> """.format( title=title, body=indented_body ) return text_html def dicts_to_anchors(d: Dict[str, Dict]) -> str: """Convert a dictionary to an HTML list of anchors. Example: The following dict: { "foo" : { "href": "http://foo.org" }, "bar": { "href": "http://bar.org", "color": "blue" } } Will be converted to: <a href="http://foo.org"> foo </a><br/> <a href="http://bar.org" color="blue"> bar </a><br/> """ response = "" for package_name, attributes in d.items(): for a, b in attributes.items(): print("MMMMMMMMMMMM", a, b) string_attributes = " ".join( [f'{a}="{html.escape(b)}"' for a, b in attributes.items()] ) response = response + f"<a {string_attributes}>{package_name}</a><br/>\n" return response
true
452e2508c61c4020d3eac97cf57ef1f5255baa0a
fernandoDB2016/FirstGitRepo
/Suspicious-test2.py
2,198
4.1875
4
# Simple examples defining functions def firstFunction(): print('Functions are very cool!!') firstFunction() def convert_bitcoint_to_usd(btc): amount = btc * 435 print(btc, ' is equivalent to: ', amount) convert_bitcoint_to_usd(3.45) convert_bitcoint_to_usd(4) # Returning values from a function # The function below returns the age of a girl (max of 7 years older) that can boy date def calculate_dating_age(my_age): girls_age = my_age//2 + 7; return girls_age my_age = 25 date_age = calculate_dating_age(my_age) print('If you age is', my_age, 'you can date with girls', date_age, 'or older') # Rather than doing for just a given age, we can do a table for different ages print() for i in range(15,60): current_age = calculate_dating_age(i) print('for boy age', i, 'can date girls',current_age,'or older') # Default values for arguments print() def get_gender(sex='unknown'): if sex == 'M': sex = 'Male' elif sex == 'F': sex = 'Female' print(sex) get_gender() get_gender('M') get_gender('F') # Variables Scope aux = 77 def func1(): print(aux) def func2(): aux = 88 print(aux) func1() func2() # Keyword Arguments def complex_function(name = 'Yo', surname = 'Soy', action = 'Sospechoso'): print(name, surname, action) complex_function() complex_function(action = 'Super hero', name = 'Yo no a') print('-------------------') numbers = [6, 7, 8, 9, 10] total = 0 for j in numbers: print('number to add is', j) total = total + j print('total is', total) ''' list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: print(list) for x in list: print(x) ''' print() # Function that receives any amount of arguments. def any_arguments(*args): total_sum = 0 total_sum1 = 0 print('argument value = ', args) for i in args: print('value i =', i) total_sum = total_sum + i total_sum1 += i print('Total Sum =', total_sum) print('Total Sum2 =', total_sum1) print('One argument') any_arguments(4) print() print('Two arguments') any_arguments(3, 4) print() print('More arguments') any_arguments(8, 20, 44, 50)
true
b8e7fc418a1ca093c0c937046a31e231b2719180
Azer7/PY1
/chap3.py
1,459
4.53125
5
#Working with lists #Just a list with element selection. colors=["red", "blue", "green", "orange"] print(colors) print(colors[3].upper()) print(colors[-1].upper()) #New list with using format or f. cars=["bmw", "mercedes", "audi", "toyota"] print("My favourite car is {0} Land Cruiser \n".format(cars[3].title())) print(f"My favourite car is {cars[0].upper()} M5") #2 ways of adding new element to the list. cars.append("suzuki") print("\n",cars) cars.insert(1, "jeep") print("\n",cars) #Deleting element from the list by element number or elemen value. poped_car=cars.pop(2) print("\n", cars) print("===", poped_car, "===") cars.remove("suzuki") print("\n" , cars) # Soring methods for lists print("\n" , sorted(cars)) cars.reverse() print("\n" ,cars) cars.reverse() print("\n" ,cars) cars.sort() print("\n" , cars) cars.sort(reverse=True) print("\n" , cars) #Element q-ty in lists print("\n" ,len(cars)) print(cars[-4]) #Homework visit_places=["japan","korea","canada","new zeeland","italy"] print(visit_places) print(sorted(visit_places)) print(visit_places) #Sorted above didn't change the list itself print(sorted(visit_places, reverse=True)) print(visit_places) #Sorted reverse above didn't change the list itself visit_places.reverse() print(visit_places) visit_places.reverse() print(visit_places)#Second reverse returned to the first stage visit_places.sort() print(visit_places) visit_places.sort(reverse=True) print(visit_places)
true
e542e56ece9454291ea2396f8161e3fe1b16e64f
atnguyen1/AdventOfCode2017
/src/4b.py
2,135
4.5
4
#!/usr/bin/env python """ A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate words. For example: aa bb cc dd ee is valid. aa bb cc dd aa is not valid - the word aa appears more than once. aa bb cc dd aaa is valid - aa and aaa count as different words. The system's full passphrase list is available as your puzzle input. How many passphrases are valid? For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase. For example: abcde fghij is a valid passphrase. abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word. a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word. iiii oiii ooii oooi oooo is valid. oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word. Under this new system policy, how many passphrases are valid? """ import argparse import sys PASS = 'data/4.txt' def main(args): """Main.""" pass_data = dict() valid = 0 with open(PASS, 'r') as fh: for line in fh: data = dict() repeat = False line = line.rstrip().split(' ') for entry in line: entry2 = sorted(list(entry)) entry2 = ' '.join(entry2) if entry2 in data: repeat = True break else: data[entry2] = 1 if not repeat: valid += 1 print valid if __name__ == '__main__': desc = 'Advent of Code 2' parser = argparse.ArgumentParser(description=desc) # parser.add_argument('dir1', type=str, help='Dir 1') args = parser.parse_args() main(args)
true
ce25838044eb5e061bee745c7c279e256cd5d5af
JuanchoVoltio/python-2021-II
/Taller05/Triangulos_Diana.py
918
4.4375
4
""" Ejercicio 1: Dado los 3 ángulos de un triángulo definir que tipo de triángulo es. """ print("#################### TIPOS DE TRIÁNGULOS ##################") angulo1 = int(input("Digite el primer ángulo: ")) angulo2 = int(input("Digite el segundo ángulo: ")) angulo3 = int(input("Digite el tercer ángulo: ")) if angulo1 > 0 and angulo2 > 0 and angulo3 > 0: suma = angulo1 + angulo2 + angulo3 if suma == 180 and angulo1 == 90 or angulo2 == 90 or angulo3 == 90: print("Es un triángulo rectángulo") elif suma == 180 and angulo1 < 90 and angulo2 < 90 and angulo3 < 90: print("Es un triángulo acutángulo") elif suma == 180 and angulo1 > 90 or angulo2 > 90 or angulo3 > 90: print("Es un triángulo escaleno") else: print("Los ángulos no corresponden a un triángulo (La suma de estos debe ser mayor que 180)") else: print("Los valores no aplican")
false
7cea4e88bd8635f59ba127bbf6851d8f4adc26cc
Uswa-Habeeb/PythonLearning
/Assignment#10.py
1,487
4.46875
4
# PROBLEM 1 # Create a program that will take all the necessary information from the user like # (First Name, Last Name, Age, Gender, Religion, Nationality, Polling Station City, User's residential city etc.). # Base on that information show that whether the user is allowed to cast the vote or not keeeping the following parameters in mind for decision making: # User must be 18 or over. # SOLUTION: # User's Information: FirstName = (input("Enter your First Name : ")) LastName = (input("Enter your Last Name : ")) Age = int(input("Enter your Age : " )) Gender = (input("Enter your Gender : ")) Religion = (input("Enter your Religion : ")) Nationality = (input("Enter your Nationality : ")) Polling_Station_City = (input("Enter your Polling Station City : ")) Residential_City = (input("Enter your User's Residential City : ")) # Age = 17 if Age >= 18: print(f"{FirstName} {LastName}, Age {Age}, Gender {Gender}, Religion {Religion}, Nationality {Nationality}, Polling Station City {Polling_Station_City}, Residential City {Residential_City} is ALLOWED TO CAST THE VOTE.") else: print(f"{FirstName}, {LastName}, Age {Age}, Gender {Gender}, Religion {Religion}, Nationality {Nationality}, Polling Station City {Polling_Station_City}, Residential City {Residential_City} is NOT ALLOWED TO CAST THE VOTE.") # Uswa, Habeeb, Age 17, Gender Female, Religion Islam, Nationality Pakistani, Polling Station City Sahiwal, Residential City Sahiwal is NOT ALLOWED TO CAST THE VOTE.
true
3df59ff4121decc45813fd98c0462b4f31ec1d6d
HoldenGs/holbertonschool-higher_level_programming
/0x06-python-test_driven_development/0-add_integer.py
536
4.28125
4
#!/usr/bin/python3 """ 0-add_integer 1 Function: add_integer """ def add_integer(a, b): """ add_integer: adds two integers a: first integer b: second integer converts floats to ints; raises exceptions for non-number input """ try: if isinstance(a, (int, float)) is False: raise TypeError("a must be an integer") if isinstance(b, (int, float)) is False: raise TypeError("b must be an integer") c = int(a) + int(b) return c except: raise
true
acd415474a377d0f46e7d00214e3a21c49dcfdea
Ty-Allen/Allen_T_DataViz
/data/america_medals_by_year.py
818
4.125
4
import matplotlib.pyplot as plt #draw a simple line chart showing population growth over the last 115 years years = [1924, 1928, 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2002, 2006, 2010, 2014] medals = [13, 14, 45, 16, 16, 30, 26, 27, 8, 7, 25, 11, 30, 9, 7, 14, 21, 34, 84, 53, 98, 65] #plot our chart with the data above, and also format the line color and width plt.plot(years, medals, color=(10/255, 10/255, 255/255), linewidth=3.0) #label on the left hand side plt.ylabel("Medals Won") #label on the bottom of the chart plt.xlabel("Year") #add a title to chart plt.title("United States of America's Medal Count by Year", pad="15") #run the show method (this lives inside the pyplot package) #this will generate a graphic in a new window plt.show()
true
52765eb47d6434526b4b923705a2b13d9fa22042
RichardAfolabi/Scientific-Python
/dow_database.py
2,804
4.15625
4
""" Dow Database ------------- This exercise covers with interacting with SQL databases from Python using the DB-API 2.0 interface. It will require for you to write a few basic SQL instructions. Take the time to refresh on them if you haven't written SQL commands in a while. Feel free to refer to http://www.sqlcourse.com/ or search for other resources. The database table in the file 'dow2008.csv' has records holding the daily performance of the Dow Jones Industrial Average from the beginning of 2008. The table has the following columns (separated by a comma). DATE OPEN HIGH LOW CLOSE VOLUME ADJ_CLOSE 2008-01-02 13261.82 13338.23 12969.42 13043.96 3452650000 13043.96 2008-01-03 13044.12 13197.43 12968.44 13056.72 3429500000 13056.72 2008-01-04 13046.56 13049.65 12740.51 12800.18 4166000000 12800.18 2008-01-07 12801.15 12984.95 12640.44 12827.49 4221260000 12827.49 2008-01-08 12820.9 12998.11 12511.03 12589.07 4705390000 12589.07 2008-01-09 12590.21 12814.97 12431.53 12735.31 5351030000 12735.31 ... ... ... ... ... ... ... 1. Create a new sqlite database. Create a table that has the same structure (use real for all the columns except the date column). """ import sqlite3 as db conn = db.connect('dowbase.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS dowtable (Data text, Open float, High float, Low float, Close float, Volume float, Adj_Close float) """) conn.commit() #%% """ 2. Insert all the records from dow.csv into the database. """ try: with open("dow2008.csv") as fp: fp.readline() for row in fp: value = row.strip().split(',') cursor.execute("INSERT INTO dowtable VALUES (?, ?, ?, ?, ?, ?, ?)", value) conn.commit() except: conn.rollback() raise else: conn.commit() #%% """ 3. Select (and print out) the records from the database that have a volume greater than 5.5 billion. How many are there? """ point = 5500000000 cursor.execute(""" SELECT * FROM dowtable WHERE volume > ? """,(point,)) countx = 0 for row in cursor: countx += 1 print(row) cursor.execute("SELECT COUNT(*) FROM dowtable WHERE volume > 5500000000") print "Number of entries:" for row in cursor: print row print("\n -- %s rows --" %countx) #%% """ Bonus ~~~~~ 1. Select the records which have a spread between high and low that is greater than 4% and sort them in order of that spread. """ lpt = 0.04 cursor.execute(""" SELECT * FROM dowtable WHERE (High - Low)/Low > ? ORDER BY (High - Low)/Low """,(lpt,)) countx = 0 for row in cursor: countx += 1 print(row) print("\n -- %s entries have spread above 4 percent --" %countx) #%% cursor.close() conn.close()
true
e393b61785254a6185d3bfe1e9c3f92ea9f5bd87
shivaniraut5555/sorting-algorithms
/shell_python.py
1,084
4.21875
4
''' Shell sort By breaking the original list into a number of smaller sublists,each sublist is sorted using the insertion sort It will move the items nearer to its original index step1:Take the list of numbers step2:Find out the gap(turnacted division 2)/incrementor step3:Create the sublist based on gap and sort them using insertion sort algorithm step4:reduce gap and repeat step3 step5:stop when gap is 0 ''' def shell_asc(li): gap=len(li)//2#turncated gap while(gap>0): for i in range(gap,len(li)): curr_ele=li[i] pos=i while(pos>=gap and curr_ele<li[pos-gap]):#comparison with index gap, for descending order " curr_ele>li[pos-gap]):" li[pos]=li[pos-gap] pos=pos-gap li[pos]=curr_ele print(f'In the gap {gap} list is:{li}') gap=gap//2#reducing gap return li n=int(input("Enter the number of elements:"))#input of elements of list li=[int(input("Enter elements:")) for x in range(n)] print("Unsorted list:",li) print('List in ascending order is:',shell_asc(li))
true
1b6854b1073fc7009538f9d4ba04155be29fbb58
EdssonOziel/Programacion2doSemestre
/Funciones.py
1,836
4.46875
4
#Demostracion de los diferentes tipos de funciones #Argumentos utilizados # No recibe argumentos # Recibe argumentos # Tiene argumentos opcionales #Retorno de valores # No retorna valores # Retorna valores #Se pueden dar combinaciones de ambos aspectos #Para declarar funciones se utiliza def #def nombredefuncion(): #Codigo #El codigo de la funcion es obligatorio. Si no hay codigo por el momento, usar pass #Si una variable se declara fuera de procedimiento se dice que es global variableglobal="soy global" #Dentro de las funciones, si se quiere usar la variable global, debe anteponerse la palabra reservada global def pendiente(): pass def norecibeargumentos(): #Si se comenta la siguiente linea, usar la variable equivalente a declarar una version local de la variable; si no se comenta, usar la variable implica usar la global variableglobal variableglobal=4 print("No recibe argumentos") print(variableglobal) #Los argumentos son dentro del parentesis en forma de lista separada por comas. def recibeargumentos(fname, lname): print(fname + " " + lname) print(variableglobal) #Un argumento es opcional cuando le asignas un valor al momento de su declaracion. #Los argumentos opcionales siempre van al final de la lista de argumentos. def argumentosopcionales(city, country = "Mexico"): print("I am from " + city + ", " + country) #Si se especifica return, la funcion retorna valores #Cuidar que el flujo del programa siempre los retorne #Se debe utilizar como expresion, atendiendo el retorno correspondiente def elevoalcuadrado(x): return x * x def main(): #norecibeargumentos() #recibeargumentos ("Felipe", "Ramirez") #argumentosopcionales("Monterrey") #argumentosopcionales("New York", "USA") print(elevoalcuadrado(4)) #Creditos: FelipeRamirezPhD
false
e0b3b47054e242abaabb1208e16734f2c6e7b592
ea3/lists-Python
/lists.py
836
4.15625
4
# Indexing , slicing and concatenation of lists. my_list = [1,2,3] my_list = ['STRING', 100, 23.2] print(len(my_list)) # prints the length of the list. mylist = ['one','two','three'] print(mylist[0]) # prints elemtent at position 0. print(mylist[1:]) # prints elements 1 and two from the list. another_list = ['four', 'five'] newlist = mylist + another_list print(newlist) newlist[0] = 'ONE IN ALL CAPS' print(newlist) newlist.append('six') print(newlist) newlist.append('seven') newlist.append(8) newlist.append("NINE") print(newlist) newlist.pop() print(newlist) popped_item = newlist.pop() print(popped_item) print(newlist) new_list = ['s','k','j','b','a','f','g'] num_list = [4,8,0,3,6,2,1] new_list.sort() print(new_list) num_list.sort() print(num_list) num_list.reverse() print(num_list) new_list.reverse() print(new_list)
true
bcf2cad6e00d7254fd6b60499e0daa2a124aa278
JoyJoel/HelloWorld
/chapter22/person.py
1,204
4.21875
4
"""人 类型 """ # # class Person: #先不设定对象类的定义 # pass # # from chapter22 import person # from chapter22.person import Person # # p1 = Person() # p1.name = 'Tom' # p1.age = 20 # # p2 = Person() # p2.name = 'Jerry' # p2.age = 23 # # p1.say = lambda word:print('说', word) # p1.say('优品课堂') # # print('-------------------------------------------') # #构造函数就是初始化实例成员的功能函数! # class Person: #事先设定对象类的定义 # def __init__(self): #self指的是三个步骤里实际实例的对象 # self.name = '' # self.age = 0 # self.gender = '' # 构造函数-例: class Person: def __init__(self, name='', age=0, gender='Male'): #此处可写为 def __init__(self, name, age, gender),但因无默认值,各项均需传值,否则报错 self.name = name self.age = age self.gender = gender # p = Person('Tom', 20, 'Male') # p = Person(name='Tom', age=20, gender='Male') def say(self, word): print('{}说:{}'.format(self.name,word)) p = Person('Tom', 20) p2 = Person('Jerry', 22) print(p.name) print(p2.name) p.say('今天天气真好!') p2.say('我想学Python!')
false
e8c2e10306f54d38bc472fb5cf46ae1bf0b06d26
vietthanh179980123/VoVietThanh_58474_CA20B1
/page_70_exercise_02.py
216
4.15625
4
""" Author: Võ Viết Thanh Date: 15/09/2021 Program: Write a loop that prints your name 100 times. Each output should begin on a new line. Solution: .... """ for count in range(100): print("Vo Viet Thanh")
true
e99e3ca19c906f4f8984edf2a72323e89c46f5bd
saikatsahoo160523/python
/FileHandling/Ass8a.py
246
4.1875
4
def longest_word(file3): with open(file3, 'r') as infile: words = infile.read().split() maxlen = len(max(words, key=len)) return [word for word in words if len(word) == maxlen] print(longest_word('file3.txt'))
true
a369cfc16af14d945ab3370f9b635f43c9a5c397
saikatsahoo160523/python
/FileHandling/Ass10.py
364
4.21875
4
# 10. Write a Python program to get the file size of a plain file. def file_size(python): import os statinfo = os.stat(python) return statinfo.st_size print("File size in bytes of the File3 is : ", file_size("file3.txt")) '''OUTPUT : [root@python FileHandling]# python Ass10.py ('File size in bytes of the File3 is : ', 41)'''
true
f2e2a6f793497629e3bb1bafc0274b7ce9840148
saikatsahoo160523/python
/FileHandling/Ass8.py
378
4.40625
4
# 8. Write a python program to find the longest words. def longest_word(file3): with open(file3, 'r') as infile: words = infile.read().split() maxlen = len(max(words, key=len)) return [word for word in words if len(word) == maxlen] print(longest_word('file3.txt')) ''' OUTPUT : [root@python FileHandling]# python Ass8.py ['Raspberry'] '''
true
48592530c9935c09d8ebe002b2b552224ae55914
Mazhar004/algo-in-python
/data_structure/linked_list/UniLinkedList.py
1,731
4.125
4
class Node(): def __init__(self, val=None): ''' Node for Unidirectional Linked List val = Value of the node next_address = Address of next node linked with current node ''' self.val = val self.next_address = None class UniLinkedList(): def __init__(self): ''' Unidirectional Linked List head = Linked list starting node ''' self.head = None def append(self, val): ''' Append value in Linked List val = Value append in Linked list at last position ''' new_node = Node(val) temp = self.head if temp: while temp.next_address: temp = temp.next_address temp.next_address = new_node else: self.head = new_node def delete(self, val): ''' Delete value from Linked List val = Find matching value in Linked list to delete ''' prev, current = None, self.head while current: if current.val == val: break prev, current = current, current.next_address if current: if current == self.head: self.head = self.head.next_address else: prev.next_address = current.next_address del current print('Value deleted\n') else: print("Value not found in the list!") self.traverse() def traverse(self): ''' Print all value of the Linked List ''' temp = self.head while temp: print(temp.val, end=" ") temp = temp.next_address print("\n")
true
be7604df227006c9de4075194f0cbda22a23fc61
clairejaja/project-euler
/src/main/python/problem2/even_fibonacci_numbers.py
871
4.125
4
# Claire Jaja # 11/1/2014 # # Project Euler # Problem 2 # Even Fibonacci numbers # # Each new term in the Fibonacci sequence is generated by adding # the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence # whose values do not exceed four million, # find the sum of the even-valued terms. def main(): max_value = 4000000 # set up first three terms previous_previous_term = 1 previous_term = 1 current_term = 2 my_sum = 0 while current_term < max_value: if current_term % 2 == 0: my_sum += current_term previous_previous_term = previous_term previous_term = current_term current_term = previous_term + previous_previous_term print(my_sum) if __name__ == "__main__": main()
true
3184028f7e719da8eac53ff60066beb2aaa497f8
jrhodesy4/DojoAssignments
/Python/multiples.py
577
4.21875
4
#Part 1 this for loop runs through 1 to 1000 and prints all the numbers for count in range(1, 1001): print count #Part 2 his for loop runs through 5 to 1000000 and prints all multiples of 5 for count in range(5, 1000001): if count % 5 == 0: print count #Sum list- this program takes the sum of all the numbers in the list a =[1, 2, 5, 10, 255, 3] b = sum(a) print b #AvgList -this program first finds the sum of the list, then divides it by the number of values in the list, thus finding the average a = [1, 2, 5, 10, 255, 3] b = sum(a) c = b/len(a) print c
true
3ae8582cc2be6eac26d12ed12c76667e482b597e
MartiniBnu/DataScienceLearning
/python/map.py
290
4.15625
4
def double(x): return x*2 value = 2 print(double(value)) #### If we pass a list, python will just duplicate the list list = [1,2,3,4,5] print(double(list)) ### We can map the list to double all the list members mapped_list = map(double, list) for v in mapped_list: print(v)
true
b99a9e50590a845c6880260fc58ce856fcf04c9d
Abhishesh123/Python-list-coding-question-answer-interview
/list13.py
778
4.28125
4
# # Python | Convert a nested list into a flat list # Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ] # Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]] # Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”] # Python code to flat a nested list with # multiple levels of nesting allowed. # input list l = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] # output list output = [] # function used for removing nested # lists in python. def reemovNestings(l): for i in l: if type(i) == list: reemovNestings(i) else: output.append(i) # Driver code print ('The original list: ', l) reemovNestings(l) print ('The list after removing nesting: ', output)
false
6c9d08f1c9ac10a6258c195dc3fcc9bcaf00d284
Chronocast/pythonRefresher
/newTest.py
875
4.4375
4
# The pound sign is used as a comment character in Python. Programmers # use comments to annotate code. Python ignores everything after the # comment character on a line. # Notice how the 'print' command has been inserting a new line at the # end of our strings. print("The last three mayors of Philadelphia were:") # We can insert newlines ourselves, using "\n". print("Michael Nutter\nJohn Street\nEd Rendell\nObama Biden") # "" Is the empty string. Since the print command will insert a # newline at the end, this will print a newline by itself: print("") # Here's a new kind of printing: you can use triple quotes to create # multiline strings. print("""Jim Kenney was elected Mayor of Philadelphia on November 3, 2015, beating Republican challenger Melissa Murray Bailey.""") print("") # When you use triple quotes, whitespace is preserved. print("""Jim Kenney received 84% of the popular vote""")
true