blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bbb71d70e73cf24cf4a4b9c6f9922d69810eb245
Jonasjoja/PythonExams
/GeneratorsDecoratersContextManagers/simpleGeneratorExample.py
858
4.125
4
def countUpTo(max): count = 1 while count <= max: yield count count += 1 countUpTo(5) #This will return a generator object counter = countUpTo(5) print(counter) #this will show it returns a generator object #u will have to use methods to iterate over it if u want data out #Each time this will increase by 1 #It stores one thing at a time, the most recent one print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter)) #create a list my_list = [1, 3, 6, 10] #square each with list comprehension list_ = [x**2 for x in my_list] #same thing, but generator expression #surrounded by () cause generator expr. generator = (x**2 for x in my_list) print(list_) print(generator) #prints a generator object, then use next to iterate print(next(generator)) print(next(generator)) #and so on
true
9a6eeb76d5914b23d6061829caaf2c83197b7ddf
bking2415/python_essentials
/Chap03/sequence.py
499
4.125
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = [1, 2, 3, 4, 5] # Changing value in list x[2] = 42 # loop through list for i in x: print('i is {}'.format(i)) # Tuple # Cant change list x = (1, 2, 3, 4, 5) # loop through list for i in x: print('i is {}'.format(i)) # range x = range(1, 10) # loop through list for i in x: print('i is {}'.format(i)) # range x = {'one': 1, 'two': 2} # loop through list for k, v in x.items(): print('k: {}, v: {}'.format(k, v))
false
3b57b47bb137b6414fc1eacd91d9882d90295489
capunita7770/CTI110
/M3HW2_BodyMassIndex_AdrianCapunitan.py
394
4.25
4
# Body Mass Index # 6/13 # CTI-110 M3HW2 - Body Mass Index # Adrian Capunitan # # Get the weight and height. weight = int(input('Please enter the weight:')) height = int(input('please enter the height:')) # Calculate the BMI. BMI = weight * 703/height**2 print ('Your BMI is',BMI) if BMI <=18.5: print ('Underweight') elif BMI >=25: print ('Overweight') else: print ('Optimal')
true
7272f41a824b0badf80cf0cff9258b7451f4cb56
Robo-Pi/Alysha-Speak
/filesClass.py
1,257
4.21875
4
# Files utility class - Tutorial #1 # by Robo Pi class filesClass: # __init__ defines the file to be used. def __init__(self, filename): self.filename = filename def readFile(self, print_line_numbers = False): # Open the file for reading. with open(self.filename, "r", encoding='utf8') as voice: # Read the lines into a list called lines. lines = voice.readlines() # Set a line counter to zero. if print_line_numbers == True: lineNumber = 0 # Print out the lines with line numbers for line in lines: print (lineNumber, end="") # end="" prevents an extra line return print(" ", end="") print (line, end="") lineNumber += 1 # increment the line number print("\n") # add an extra line return when finished. return lines # return the list of lines from the file. def writeFile(self, lines): # Open the file for writing. with open(self.filename, 'w', encoding='utf8') as outfile: # Write the lines to the file. for line in lines: outfile.write(line)
true
151574517e474a7d3f1e3448442cdc1e86ba404e
green-fox-academy/IBS_guthixx23
/week-03/day-03/shopping_list.py
292
4.28125
4
shopping_list = ["Eggs", "milk", "fish", "apples", "bread", "chicken"] if "milk" in shopping_list: print("milk is on the list") else: print("milk is not on the list") if "bananas" in shopping_list: print("bananas is on the list") else: print("bananas is not on the list")
true
1306d08d5b1aebdde1eea22a914d0018eed91e1f
AshwithGarlapati/Hangman-Game
/hangman.py
2,621
4.125
4
import random def get_attempts(): # To get number of attempts form the user and checking the attempts are in the range of 1 to 25. attempts = int(input('\nHow many number of incorrect attempts do you need[1-25]? ')) if attempts > 25 or attempts < 1: print('{} is not an integer between 1 and 25\nPlease select an integer between 1 and 25.'.format(attempts)) return attempts def get_word_length(): # Getting the word length from the user an checking weather the length is in the range 4 to 16. length = int(input('\nSelect the word length that is between [4-16] ')) if length > 16 or length < 4: print('Please select the word length that is between 4 to 16') return length # Starting of the execution of the program. print('''Welcome to the game of HANGMAN...''') # Getting number of attempts and word length. no_of_attempts = get_attempts() word_length = get_word_length() # Opening the word fle file in read mode and reading all the words in the file and separating them into a string list. f = open("words.txt.txt", "r") all_text = f.read() words = list(map(str, all_text.split())) # Filtering the words that are of length equal to word length. filtered_words = list(filter(lambda word: len(word) == word_length, words)) # Getting a random word from filtered word. random_word = random.choice(filtered_words) # Guessing of characters print('\n\nGuess the character\'s: ') print('-' * word_length) char = ' ' # Generating a empty string of hyphens with length 16. guess_word = list('-' * 16) while no_of_attempts > 0: # Checking weather the character is present in random word and printing it. if char in random_word: for j in range(len(random_word)): if random_word[j] == char: print(char) guess_word[j] = char else: print(guess_word[j]) char = ' ' # Checking weather the word is guessed completely and printing 'won the game' and braking of while loop. if random_word == ''.join(guess_word[:word_length]): print('You have won the Game.') print('The word is', random_word) break # Displaying remaining attempts and guessing of character. print('\nAttempts remaining:', no_of_attempts) char = input('Guess the character: ') no_of_attempts -= 1 # If word is not guessed properly. if random_word != ''.join(guess_word[:word_length]): print('Sorry! you have lost the game\nBetter luck next time!') print('The word is', random_word)
true
ef6ab603ee10574f85394e7db546ab0fab31c528
marcelarosalesj/python-scripts
/learning/generators.py
428
4.1875
4
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b fib = fibonacci() print('fib is type {}'.format(type(fib))) fib_func = fibonacci print('fib_func is type {}'.format(type(fib_func))) print('Let\'s print first ten numbers in Fibonacci\'s sequence using fib:') for i in range(10): print(next(fib)) print('Let\'s print more numbers:') for i in range(10): print(fib.__next__())
false
b0b04e7283258cf6085b4b45cdd0687701c09de9
malluri/python
/21.py
377
4.28125
4
""" 21. Given an age, figure out whether someone's a baby, toddler, child, teenager, adult or old codger. """ age=input("enter age:") if(age<2): print("baby") elif(age>=2 and age<=3): print("toddler") elif(age>3 and age<13): print("child") elif(age>=13 and age<18): print("teenager") elif(age>=18 and age<35): print("adult") else: print("old codger")
true
70f136edd9fc92305d8d7889f53349fdc2060174
FrauleinGela/Python-exercises
/src/mean_list.py
1,179
4.28125
4
from decimal import Decimal # The mean of a set of numbers is the sum of the numbers divided by the # number of numbers. Write a procedure, list_mean, which takes a list of numbers # as its input and return the mean of the numbers in the list. """ Exercises """ def list_mean(list_numbers): """The mean of a set of numbers is the sum of the numbers divided by the number of numbers. Write a procedure, list_mean, which takes a list of numbers as its input and return the mean of the numbers in the list.""" if not list_numbers: return "not a valid list" sum_numbers = 0 for l_number in list_numbers: sum_numbers = sum_numbers + l_number return sum_numbers/float(len(list_numbers)) print(list_mean([1, 2, 3, 4])) #>>> 2.5 print(list_mean([1, 3, 4, 5, 2])) #>>> 3.0 print(list_mean([])) #>>> ??? You decide. If you decide it should give an error, comment # out the print line above to prevent your code from being graded as # incorrect. print(list_mean([2])) #>>> 2.0 print(list_mean([7.7000000000000002, 1.2, 3.2000000000000002, 8.1999999999999993,3.3999999999999999])) #>>> 4.74 print(list_mean([2, 4, 5, 6, 7, 1, 1, 1])) #>>> 3.375
true
c79a16f567e666844a6f803d47c9e477989f74c7
ajaykommaraju/Courseera_Python_Project
/basics.py
596
4.15625
4
def format_name(first_name, last_name): if len (first_name) > 0 and len(last_name) > 0: str1 = "Name: " + first_name+", "+last_name return str1 elif len (first_name) = 0 and (last_name) > 0: return "Name: " + last_name elif len first_name > 0 and last_name < 0: return "Name: " + first_name return "" print(format_name("Ernest", "Hemingway")) # Should be "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should be "Name: Madonna" print(format_name("Voltaire", "")) # Should be "Name: Voltaire" print(format_name("", "")) # Should be ""
true
1b8594b88ad5dc93ba7d6a6aba68c39fb7c5995a
ajaykommaraju/Courseera_Python_Project
/skip_element_using_enumrate_function.py
850
4.40625
4
'''Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.''' #The enumerate() function takes a list as a parameter and returns a tuple for each element in the list. The first value of the tuple is the index and the second value is the element itself. def skip_elements(elements): new_list=[] for index, element in enumerate(elements): if index % 2 == 0: new_list.append(element) return new_list print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
true
533191b8fad130a336cf204f4ab08ae68dcb5a23
winniecluk/RealPythonExercises
/temperature.py
266
4.21875
4
celsius_input = input('Enter degrees in Celsius: ') def convert_to_f(c_num): fahrenheit = (c_num * 9/5) + 32 return fahrenheit print(convert_to_f(37)) def convert_to_c(f_num): celsius = (f_num - 32) * 5/9 return celsius print(convert_to_c(72))
false
9d194a365085897fe618728e06711b7bb46791e7
git-athul/Python-exercises
/challenge-series1-solutions/table.py
283
4.15625
4
# table.py: # Multiplication table def table(m,n): for i in range(1,n+1): print(f"{m} X {i} = {m*i}") print("We are going to print the m times tables from 1 to n.") a = int(input("Enter value of m: ")) b = int(input("Enter value of n: ")) table(a,b)
true
5a7891cbf708e30e6e75d1c17bd0eede2044a9fa
git-athul/Python-exercises
/challenge-series1-solutions/minimum.py
350
4.25
4
# minimum.py # Program to find the smallest number from given list. def min(list): min = list[0] for i in list: if min > i: min = i return min # Driver function: if __name__ == '__main__': list = input("Enter a list of numbers using commas: ").split(",") print("Smallest number from given is "+ min(list))
true
013553b7218d75904bc1333c6355c60cb07ab9dd
asap16/Some-Python-Problems
/removeduplicates.py
836
4.28125
4
'''The program below returns all characters besides the one that are repeated. It avoids all repetitions. For example, 'noodles' would return 'ndles'. The order in which strings are concatenated can change due to the use of dictionary. ''' def RemoveDuplicates(str1): d = {} result_str = '' for i in range(len(str1)): d[str1[i]] = d.get(str1[i], 0) + 1 for k in d: if d[k] == 1: result_str += str(k) return result_str print(RemoveDuplicates('cutcopypaste')) '''The program below returns a single item for all repeated items. For example , [11, 2, 2] would return [11,2].''' def RemoveDuplicatesList(a_list): new_list = [] for item in a_list: if item not in new_list: new_list.append(item) return new_list print(RemoveDuplicatesList([1, 2, 2, 4, 5, 5]))
true
7cd16cbc87d7451ded09b6d0314c234b3694a537
leninhasda/python-101
/basic-language-structure/005-condition-loop.py
344
4.125
4
#!/usr/bin/env python # there is only one kind of condition # if..elif..else # sorry no switch case for you :p # loop # while loop and for loop # while condition: # do something # for item in list: # do something with item # or not # there is another thing called # while..else # for...else # i still don't get the use of it because
true
6b39700d6e8df4be9bae848299bb3316be5488c8
guohuaCabin/Algorithm
/multiply/multiply.py
605
4.21875
4
#!/usr/bin/env python ''' 递归乘法 写一个递归函数,不使用 * 运算符, 实现两个正整数的相乘。可以使用加号、减号、位移,但要吝啬一些。 示例1: 输入:A = 1, B = 10 输出:10 示例2: 输入:A = 3, B = 4 输出:12 ''' def multiply_one(A, B): if B == 0: return 0 return A + multiply(A,B-1) def multiply(A, B): if B == 1: return A if (B % 2) == 0: return multiply((A << 1),(B >> 1)) else: return A + multiply((A << 1),(B >> 1)) print(multiply_one(10,11)) print(multiply(5,3))
false
6c3633221a7d580770279167ee1b94e1afb94ac1
Jkim516/editors-unicorn
/dow.py
476
4.375
4
#!/usr/bin/env python """Tells us the day of the week.""" from datetime import datetime import calendar DAYS = list(calendar.day_name) def find_day_if_week(): """Returns the day of week as a string, e.g. 'Monday'""" now = datetime.now() weekday = now.weekday() return DAYS[weekday] def main(): """Sends the day of the week to stdout.""" day = find_day_if_week() print(f"It's {day}!") print("test") if __name__ == "__main__": main()
true
e9d655f45df556486b1e3c4f99607982f168be80
jayjay1984/MyEulerAndLib
/problem_2.py
732
4.1875
4
# Gerade Fibonacci-Zahlen DEBUG = False def fibonacci_even_sum(limit): """calculates and returns the sum of the even values in the Fibonacci sequence up to limit. Args: limit ([integer]): [only values up to limit are considered.] """ #init sum S = 0 f0 = 1 f1 = 1 if(DEBUG): print(f0, end=' ') while (f1 < limit): h = f1 f1 = f0 + f1 f0 = h if(f0 % 2 == 0): S = S + f0 if(DEBUG): print(f0, end=' ') if(DEBUG): print("\n") return S if __name__ == "__main__": L = 4000000 sum_even_fibo = fibonacci_even_sum(L) print(f"the sum of even fibonacci numbers below {L} is {sum_even_fibo}")
true
ca80618efce4cafddd653dd4adbf5ac6503bdaa9
bopopescu/curly-octo-goggles
/Basics.py
1,084
4.15625
4
""" print("hello world") print(2/2) print("hello world "+ str(2)) print(str(22)+str(2)) """ #print("hello") # this is single line comment """ multi line comment """ ## data types ##100, 22, 22.5-->int ,+,-,/,* int, float ##"dwarak", "prasad"--> strings ## loops """ num=3 ## check if numner is odd or even if num%2==0: print("even") else: print("odd") if num-2==6: print ("yes") else: print ("no") """ #=, == # """ restro='I' dish="k" if restro=='I': print("i") if dish=="k": print("k") else: print("not k") elif restro=='C': print("d") elif restro=='S': print("s") else: print("A") """ ## for loop """ i=6 for i in range(5): print(i*2) """ #[] """ x=["apple","pine","mango"] #print(x[2]) x.append("orange") #print(x) x.append("custard") #print(x) for i in range(len(x)): print(x[i], i) """ #set=() #x=[0,1,1,1,2,3,3,4,4,4,99,99] #print(set(x)) # apple: its a fruit #map """ new_dict={} new_dict['venkat']="prasad" print(new_dict) new_dict["dwarak"]="nath" print(new_dict) """ ## ## import
false
683a82e4123c4562f7dc3b9fca47279f32b094a9
Neckmus/itea_python_basics_3
/shevchenko_mike/03/3.2.py
1,048
4.34375
4
print('Approach_1') print('map_original') my_list = ['hello', "what`s up", 'good morning'] map_original = list(map(lambda x: x[:: -1], my_list)) print(map_original) """ So, this is test function custom_map = map_original Firstly,the function map_original we will use python collection (list), than function 'map', than function 'lambda'. Secondly, this is function custom_map return first latter in end words :param python collection (list) :param str. :param lambda. """ print('') print('custom_map') custom_map = [i[:: -1] for i in my_list] print(custom_map) #Approach_2 print('Approach_2') print ('Enter numeral "For example: 1 76 33 5..."') """ So, this Approach_2 to use function map. Firstly, you must to enter new numeral Secondly, this is function custom_map return first latter in end words :param python collection (list) :param int :param input() :param Python String split() Method """ def f(x): return x * 2 my_list_2 = list(map(int, input().split())) print (my_list_2)
false
90c8c85a3f39268890cdb8331bae24b080822fdc
Neckmus/itea_python_basics_3
/safonov_roman/03/task_3.3.py
1,026
4.25
4
def filter_cust (func, sequence): """ This function is analog of build in "filter" function. :param func: is a function which verify each element of sequence on specified condition :param sequence: is a list of iterable elements which are passed as an argument to "func" one by one :type func: def :type sequence: int/str/bool/list/tuple :return: filter_cust returns list of sequence elements which meets condition described into func :return: list """ output_list = [] for i in range (len(sequence)): if func(sequence[i]): output_list.append (sequence[i]) return output_list def odd_check (a): answer = a % 2 return answer def upper_chk (a): if a == a.upper(): answer = 1 else: answer = 0 return answer print (filter_cust (odd_check, [1, 2, 3, 4, 5])) print (filter_cust (upper_chk, ['A', 'B', 'C', 'd', 'E'])) print (filter_cust (lambda x: x % 2, [1, 2, 3, 4, 5]))
true
5becde6429db21e35e927c37182eaf0962914b07
Neckmus/itea_python_basics_3
/pivak_gennadii/03/01.py
650
4.15625
4
def implement_diff(list_a, list_b): """ This is a function witch subtracts one list from another. It should remove all values from list_a, witch are present in list_b. :param list_a: list from witch will be remove values :param list_b: list witch will be remove from list_b :type list_a: list :type list_b: list :return: list_c list_a without values in list_b :rtype: list """ list_c = [] for _ in range(len(list_a)): if not list_a[_] in list_b: list_c.append(list_a[_]) return list_c #print(implement_diff.__doc__) print(implement_diff([1, 2, 3, 4, 2, 3, 4],[2, 1, 4]))
true
86c24036cc2c0be87988bdb552c9d3511f3afbcd
Wade-Philander/python-excersise
/TICKPRACT.py
874
4.40625
4
from tkinter import * window = Tk() #Make a window window.geometry("500x500") window.title("Changing Text") enter = Entry(window, width=20) #Entry is a widget to use in the window label = Label(window, text="Label") #how to make a label def change(): # (function) was whatever i name it, also def label.config(text=enter.get()) button = Button(window, text="Button", command=change) enter.grid(row=0, column=0) # will allow the winow to have a format label.grid(row=5, column=2) # Will place the label in the window using grid button.grid(row=6, column=4) # allow the button to show in window window.mainloop() # Make Tk run by looping the window constantly
true
ec7f8c71b7fbb37b6ae60e291a8abf3c65f97798
ezvone/advent_of_code_2020
/src/day1.py
1,472
4.40625
4
from typing import Iterable, Tuple from input import get_input_filename def find_sum_of_two(numbers: Iterable[int], wanted_sum: int, start=0 ) -> Tuple[int, int]: """Return two numbers from `numbers` which sum up to `wanted_sum` If `start` is set, only look at the part of the list starting at that index """ numbers = sorted(numbers) i = start j = len(numbers) - 1 a = numbers[i] b = numbers[j] while i < j: if a + b < wanted_sum: i += 1 a = numbers[i] elif a + b > wanted_sum: j -= 1 b = numbers[j] else: return a, b raise ValueError("Sum not found") def find_sum_of_three(numbers: Iterable[int], wanted_sum: int ) -> Tuple[int, int, int]: """Return three numbers from `numbers` which sum up to `wanted_sum`""" numbers = sorted(numbers) for i in range(len(numbers) - 2): a = numbers[i] try: b, c = find_sum_of_two(numbers, wanted_sum-a, start=i+1) return a, b, c except ValueError: continue raise ValueError("Sum not found") with open(get_input_filename(1), 'rt') as f: numbers = (int(line) for line in f) a, b = find_sum_of_two(numbers, 2020) print(f'Solution one: {a * b}') with open(get_input_filename(1), 'rt') as f: numbers = (int(line) for line in f) a, b, c = find_sum_of_three(numbers, 2020) print(f'Solution two: {a * b * c}')
true
eb7928eb6514007dd4a90fd4a8146c7d9b31e46a
javierramon23/Curso-Python-KeepCoding
/5. Mis Ejercicios/Ejercicios Teoria/p18.py
1,164
4.625
5
''' FUNCIONES RECURSIVAS/ITERATIVAS: Una FUNCION es RECURSIVA si en su EJECUCIÓN SOLO SE INVOCA A SI MISMA de forma REPETIDA. ''' ''' NOTA: FORMA ALTERNATIVA de la FUNCION "print()" --> print('cadena_para_imprimir', end = 'un_caracter') En esta forma, se sustituye el SALTO de LINEA por defecto de print() por el CARACTER ASIGNADO A "end". ''' ''' Con la FUNCION "range()" tambien es posible establecer SERIES DE NUMEROS INVERSOS, utilizando INDICES NEGATIVOS para REDUCIR la SERIE. ''' for contador in range(10, -1, -1): print(contador, end = ':') print('Final') ''' COMO CREAR una FUNCION RECURSIVA/ITERATIVA: 1.- Establecer cuna el la OPERACION BASICA a REALIZAR(Ej. Disminuir Contador). 2.- Establecer el PUNTO DE SALIDA o FINALIZACION (Ej. Contador < 0) Este ultimo punto es FUNDAMENTAL para evitar la creación de un BUCLE INFINITO. ''' def cuenta_atras(contador): if contador >= 0: print(contador, end = ',') return cuenta_atras(contador - 1) print('Fin de la Recursividad') return print() print('Cuenta Atras RECURSIVA:') cuenta_atras(10)
false
03da2f762808c887a4c4e23b0c3a1b8ff2f2b8c6
javierramon23/Curso-Python-KeepCoding
/5. Mis Ejercicios/Ejercicios Teoria/p15.py
1,997
4.25
4
''' ESTRUCTURAS DE CONTROL: 1.- SECUENCIA. 2.- SELECCION. 3.- ITERACION. 4.- BLOQUE CODIGO. 5.- FUNCIONES. ''' ''' SELECCION(CONDICION): Es una BIFURCACION en la SECUENCIA a causa de una CONDICION LOGICA (True/False). Aparece la INSTRUCCION "IF" que PERMITE IMPLEMENTAR esta SELECCION (CONDICION), en PYTHON existen TRES FORMAS de utilizar el "IF" (SELECCION): 1.- SELECCION/CONDICION BASICA: if if condicion_logica_se_cumple: Bloque_Codigo 2.- SELECCION/CONDICION SIMPLE: if - else if condicion_logica_se_cumple: Bloque_Codigo else: Bloque_Codigo 3.- SELECCION/CONDICION MULTIPLE: if - elif - else if condicion_logica_1_se_cumple: Bloque_Codigo elif condicion_logica_2_se_cumple: Bloque_Codigo elif condicion_logica_3_se_cumple: Bloque_Codigo else: Bloque_Codigo La SELECCION/CONDICION permite ROMPER el FLUJO "NORMAL" de EJECUCION de las INSTRUCCIONES, es decir la SECUENCIA de un PROGRAMA. ''' print('SELECCION BASICA:\n') print('Gracias x participar\n') print('SELECCION SIMPLE:\n') num_str = input('Introduce un numero: ') num = int(num_str) if num % 2 == 0: print('{} es un numero PAR'.format(num)) else: print('{} es un numero IMPAR'.format(num)) print('Gracias x participar\n') print('SELECCION MULTIPLE:\n') vocal = input('Selecciona una VOCAL: ') if vocal == 'a': print('Has pulsado la letra "a"') elif vocal == 'e': print('Has pulsado la letra "e"') elif vocal == 'i': print('Has pulsado la letra "i"') elif vocal == 'o': print('Has pulsado la letra "o"') elif vocal == 'u': print('Has pulsado la letra "u"') else: print('NO HAS PULSADO UNA VOCAL') print('Gracias x participar')
false
d794502520c6fba85ef0764343385d52467e16ae
Tarang-1996/100-days-
/day11/leap.py
380
4.125
4
def is_leap(year): leap = False if year % 4 == 0 or year % 400 == 0: return True else: return leap year = int(input()) print(is_leap(year)) for i in range(1, 11): print(i, end='') n = int(input()) if N % 4 == 0 or N >20 and N % 2 == 0: print("Not Weird") elif N % 2 == 0 and N >=6 and N <= 20: print('Weird') else: print('Weird')
false
4ac9560ad5a3b5bb93b20bf93991927c35f2d122
darcy-amadio/Lab1
/main.py
1,871
4.15625
4
#question 1 # my codes are commented out. # print('What is your first name?') # first_name = input() #first name is typed # print('What is your last name?') # last_name = input() #last name is typed # print('Hi', last_name, first_name) #prints name out #question 2 # print('What is your number?') # given_number = int(input()) # if given_number == 0: # print('Zero') # elif given_number % 2 == 1: # x divided by 2 and a remainder 1 always = a odd number # print('Odd') # else: # print('Even') #question 3 # print('What day is it?') # ask for day number # day_given = int(input()) # if day_given in range (0,31 +1): #if num. is in days of january, it stats january than day number # print('January', day_given) # elif day_given in range (32, 59 +1): # print('Febuary', day_given - 31) # same thing happens for other months, except I subtract the days form the months before so the number that goes with the month is good. # elif day_given in range (60, 90 +1): # print('March', day_given - 59) # elif day_given in range (91, 120 +1): # print('April', day_given - 90) # elif day_given in range (121 , 151 +1): # print('May', day_given - 120) # elif day_given in range (152,181 +1): # print('June', day_given - 151) # elif day_given in range (182, 212 +1): # print('July', day_given - 181) # elif day_given in range (213, 243 +1): # print('August', day_given - 212) # elif day_given in range (244, 273 +1): # print('September', day_given - 243) # elif day_given in range (274, 304 +1): # print('October', day_given - 273) # elif day_given in range (305, 334 +1): # print('November', day_given - 304) # elif day_given in range (335, 365 +1): # print('December', day_given - 334) #question 4 # i ran out of time, as question 3 took me very long to complete n = 5 for i in range (n, 0, -1): print(i)
true
b34c5fc0a7366f7344f8f07a719d270fe9521760
SANJAY9068068086/Python-Major-Projects
/Simple input Dictionary Program for Beginners.py
518
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Simple input Dictionary Program for Beginners keys = [] values = [] dict_range = int(input("Enter the range of your dictionary : ")) for i in range(dict_range): x = input("Enter Key : ") keys.append(x) y = input("Enter Value : ") values.append(y) my_dict = dict(zip(keys,values)) print() find = input("To find the Value, Please Enter Key : ") print("\n","-"*50,"\nValue of Entered Key ",[find]," is : ",my_dict[find],sep="") # In[ ]:
true
767eecab506c550c1a3f0a417154a6ad6adf4b76
SACHSTech/ics2o1-livehack-2-AstonCheng23
/problem2.py
594
4.34375
4
""" Name: Problem 2 Date: Febuary 23, 2021 Author: Aston """ print("----------RightTriangleMachine----------\n") print("This program calculates if a triangle is a right triangle.") #These are the side inputs. side_1 = float(input("Enter in a value for side 1: ")) side_2 = float(input("Enter in a value for side 2: ")) side_3 = float(input("Enter in a value for side 3: ")) #checks for the sides. if side_1**2 + side_2**2 == side_3**2 or side_3**2 + side_2**2 == side_1**2 or side_3**2 + side_1**2 == side_2**2: print("It is a right triangle.") else: print("It is not a right triangle.")
true
38d4cb61c1fc84888c44e869e76e76369774db92
ani07/Starting_Out_with_Pythoni
/loan_qualifier_3_5.py
408
4.125
4
min_salary = 30000 min_experience = 2 Salary = float(input('Enter your salary')) Experience = int(input('Enter your experience')) if Salary >= min_salary: if Experience >= min_experience: print('You are qualified for the loan') else: print('You should have minimum experience of',min_experience ,'to qualify') else: print('You must earn minimum of',min_salary,'to be qualified')
true
80fcc5159bfb95f4c0dab7a11399ec4c438cfc47
hewei-bit/PYTHON_learning
/Leetcode/1.数据结构/2.数组和字符串/2.二维数组/1.旋转矩阵.py
1,985
4.15625
4
""" 面试题 01.07. 旋转矩阵(medium) 给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。 不占用额外内存空间能否做到? 示例 1: 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] """ from typing import List # 暴力解法 class Solution1: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return n = len(matrix) matrix_new = [[0] * n for _ in range(n)] for i in range(len(matrix)): for j in range(len(matrix)): matrix_new[i][j] = matrix[n - 1 - j][i] matrix[:] = matrix_new # 原理旋转 class Solution2: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return n = len(matrix) for i in range(n // 2): for j in range((n + 1) // 2): temp = matrix[i][j] matrix[i][j] = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j] matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = temp class Solution3: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix) # 水平翻转 for i in range(n // 2): for j in range(n): matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j] # 主对角线翻转 for i in range(n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] if __name__ == '__main__': l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Solution2().rotate(l) print(l)
false
c3405f44a2f24290dfe2b8017d140e5b4db8caa3
hewei-bit/PYTHON_learning
/labuladuo/1.数据结构/数组与矩阵/2. 改变矩阵维度.py
1,153
4.21875
4
''' 566. Reshape the Matrix (Easy) In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix \ into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r\ and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix \ in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, \ output the new reshaped matrix; Otherwise, output the original matrix. ''' class Solution: def matrixReshape(self, nums: list, r: int, c: int) -> list: m = len(nums) n = len(nums[0]) if m * n != r * c: return nums ans = [[0] * c for _ in range(r)] index = 0 for i in range(r): for j in range(c): ans[i][j] = nums[index // n][index % n] index += 1 return ans aaa = [[0, 1, 2], [1, 2, 3]] ans = Solution().matrixReshape(aaa, 1, 6) print(ans)
true
1b5fa5a570b1bd1a5e95d53693a3d763e8c8a5e3
hewei-bit/PYTHON_learning
/Leetcode/1.数据结构/6.二叉树/1.树的遍历/1.前序遍历.py
1,614
4.375
4
""" 144. 二叉树的前序遍历(medium) 给定一个二叉树,返回它的 前序 遍历。  示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] """ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: """ :type root: TreeNode :rtype: List[int] """ if not root: return [] resls = [] stack, node = [], root while stack or node: while node: stack.append(node) resls.append(node.val) node = node.left node = stack.pop() node = node.right return resls class Solution2: def preorderTraversal(self, root: TreeNode) -> List[int]: """ :type root: TreeNode :rtype: List[int] """ if not root: return [] res, stack = [], [] stack.append(root) while stack: node = stack.pop() res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res if __name__ == '__main__': n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 obj = Solution2().preorderTraversal(n1) print(obj)
false
ea671e7c2750a61772520c52a008cfca01c39f12
gupongelupe/ExerciciosFeitosPython
/ex033.py
459
4.1875
4
num = int(input('Digite um valor: ')) num2 = int(input('Digite um valor: ')) num3 = int(input('Digite um valor: ')) menor = num # veficando menor if num2 < num and num2 < num3: menor = num2 if num3 < num and num3 < num2: menor = num3 # veficar o maior maior = num if num2 > num and num2 > num3: maior = num2 if num3 > num and num3 > num2: maior = num3 print('O menor é {}'.format(menor)) print('O maior é {}'.format(maior))
false
3eebbd1354a49fad07eefafdc3d5164ac757ebd2
gupongelupe/ExerciciosFeitosPython
/ex060.py
225
4.125
4
from math import factorial n = int(input('Digite um número: ')) t = factorial(n) while n != 0: print('{}'.format(n),end='') print(' x 'if n > 1 else ' = '.format(n), end='') n = n - 1 print('{}'.format(t))
false
db6c7989dde091bfbf6be7d8aa6448b3975b99b8
lelenux/python-520
/4linux/aula03/exerc01_for.py
299
4.15625
4
alunos = [ { "Nome": "Mariana", "curso": ["Python"] }, { "Nome": "João", "curso": ["Python", "Infra Agil"] } ] curso = (input("Escolha um curso: ")) for a in alunos: for c in a ["curso"]: if c == curso: print(a["Nome"])
false
6ad3d22e00a4a00a81485ff66e51d2b2b85f2cf7
qianlongzju/project_euler
/python/PE007.py
1,080
4.25
4
#!/usr/bin/env python import math """ Some useful facts: 1. 1 is not a prime. 2. All primes except 2 are odd. 3. All primes greater than 3 can be written in the form 6k+/-1. 4. Any number n can have only one primefactor greater than sqrt(n). 5. The consequence for primality testing of a number n is: if we cannot find a number f less than or equal sqrt(n) that divides n then n is prime: the only primefactor of n is n itself. """ def isPrime(n): if n <= 1: return False elif n < 4: # 2 and 3 return True elif n % 2 == 0: return False elif n < 9: # 5 and 7 return True elif n % 3 == 0: return False else: r = int(math.sqrt(n)) f = 5 while f <= r: if n % f == 0: return False if n % (f+2) == 0: return False f += 6 return True def main(): num = 1 i = 3 while num < 10001: if isPrime(i): num += 1 i += 2 print i - 2 if __name__ == '__main__': main()
true
07ba11dc5705beae8a814fecd0d1fefb5c2cbc5b
yashkha3/Exercises
/test/ans5_b.py
995
4.46875
4
# Pre-Defined Dictionary stu = {'name' : "Yash Khatri", 'age' : "20", 'height' : "5feet 11inch"} # a) get() : Get is a method which return the value of the key ehich is provided to it.. Ex : print(f"\n Student Name: {stu.get('name')}") # b) keys() : Keys is a method which is used to view the keys of Dict.. Ex : print(stu.keys()) # c) pop() : Pop is method which removes an element of which key is provided.. Ex : whoo = stu.pop('height') print(f"\n Removed element is : {whoo} \n Updated dictionary : {stu}") # d) update() : Update method is used to add elements to dictomary.. Ex : u = {'hobby': "Watching Movies"} stu.update(u) print(f"\n\n Updated Element in Dict : {stu}") # e) values() : Value is a method which is used to view the list of values from Dict.. Ex : print(f"\n\n {stu.values()}") # f) items() : Items is a method which is used to display the key and its value from a given dict.. Ex : print(f"\n\n {stu.items()}") # which shows as tuples in which ('key', 'value')
true
5e0082c4a0b7ddcc3d5aa06c68547f5d2217a991
OlgaZaytsevaV/calculator-2
/arithmetic.py
945
4.1875
4
"""Math functions for calculator.""" lst = [] def add(lst): """Return the sum of the two inputs.""" nums = len(range(lst[1], lst[-1])) for num in nums: nu def subtract(lst): """Return the second number subtracted from the first.""" return num1 - num2 def multiply(lst): """Multiply the two inputs together.""" return num1 * num2 def divide(lst): """Divide the first input by the second, returning a floating point.""" return num1 / num2 def square(lst): """Return the square of the input.""" # Needs only one argument return num1 * num1 def cube(lst): """Return the cube of the input.""" # Needs only one argument return num1 * num1 * num1 def power(lst): """Raise num1 to the power of num and return the value.""" return num1 ** num2 # ** = exponent operator def mod(lst): """Return the remainder of num / num2.""" return num1 % num2
true
096024bc53fbef79430ab54ef457844c71405b5c
Fl0r14n/PLP
/beginner_P1.py
832
4.1875
4
# -*- coding: utf-8 -*- """ Implement a function that will flatten two lists up to a maximum given depth """ def _flatten(lst, depth_limit = -1): result = [] if type(lst) is list: for item in lst: if depth_limit <= 0: result.append(item) elif type(item) is list: depth_limit-=1 result.extend(_flatten(item, depth_limit)) else: result.append(item) return result; def flatten(list_a, list_b, max_depth): l1 = _flatten(list_a, max_depth) l2 = _flatten(list_b, max_depth) l1.extend(l2) return l1 a_list = [1,[2,3,[4,5,[6,7,[8]],9],10,11],12,13,14] b_list = [3,6,9,[12,15,17,[22,24,26]]] print '#'*40 print a_list print '-'*40 print b_list print '-'*40 print flatten(a_list, b_list, 2) print '#'*40
true
e92111f17d4408378f438318801665c312b46cb4
mittortz/LearnPythonTheHardWay
/ex20.py
1,187
4.3125
4
from sys import argv script, input_file = argv # defines function to read the file and print it entirely def print_all(f): print f.read() # defines function to set reading position to zero def rewind(f): f.seek(0) # defines function to print a single line from the file, starting wherever # the reading position is # added comma to end of readline function to prevent adding newline character def print_a_line(line_count, f): print line_count, f.readline(), # declares file object (DVD player) for the file current_file = open(input_file) # calls the print_all function to display entire file print "First let's print the whole file:\n" print_all(current_file) # calls function to reset reading position to zero print "Now let's rewind, kind of like a tape." rewind(current_file) # calls function to read and print individual lines from file # each time function is called, reading position moves up print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) # calls function to close file current_file.close()
true
8546c30f92973cb3e1c4f7b8d10666060c76d069
jgyy/python-masterclass
/section4/truefalse.py
353
4.15625
4
""" Practicing true false for this script """ DAY = "Friday" TEMPERATURE = 30 RAINING = True if (DAY == "Saturday" and TEMPERATURE > 27) and not RAINING: print("Go swimming") else: print("Learn Python") NAME = input("Please enter your name: ") if name != "": print("Hello, {}".format(name)) else: print("Are you the man with no name?")
true
b36b4407850b50372659136991b64c2852553c53
udo-art/Calculator
/main.py
549
4.28125
4
def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 operations = { "+": add, "-": subtract, "*": multiply, "/": divide } num1 = int(input("What's the first number: ")) operation_symbol = input("Pick an operation: ") num2 = int(input("What's the second number: ")) calculation_function = operations[operation_symbol] answer = calculation_function(num1, num2) print(f"{num1} {operation_symbol} {num2} = {answer}")
false
81fff5be7deac96beb07c18f49f8c748cd8cce29
QuaziBit/Python
/submited/Assignment_9/Olexandr-Matveyev-Assignment9.py
1,175
4.28125
4
# -----------------------------------------+ # Olexandr Matveyev | # CSCI 107, Assignment 9 | # Last Updated: November 25, 2019 | # -----------------------------------------+ # This python program computes Fibonacci | # Sequence by using recursion approach and | # loop in order to print Fibonacci Value | # for each 'k' value. | # -----------------------------------------+ # Computing Fibonacci Sequence for each 'k' value def fibonacci_sequence(k): # for 0 and 1 'k' return 1, else do recurrence call of this function if k <= 1: return 1 elif k > 1: f = fibonacci_sequence(k - 1) + fibonacci_sequence(k - 2) return f # run program def run(n): output = "" # loop 'n' times to computing Fibonacci Sequence for each 'k' value for k in range(n): f = fibonacci_sequence(k) # store output as string output = output + ("%d " % (f) ) # print result print("%s" % (output) ) def main(): # get input n = input("Enter n: ") # convert string to int n = int(n) # start program run(n) # entry point main()
false
c76b4d4a2f58929bc372112c2c73de7a63f8e203
QuaziBit/Python
/Assignment_7/assignment7.py
2,101
4.125
4
# -----------------------------------------+ # Olexandr Matveyev | # CSCI 107, Assignment 7 | # Last Updated: November 04, 2019 | # -----------------------------------------+ # This application asks user to enter | # two input valuse cost and isTeacher. | # After, it will compute discount | # information, and will print it. | # -----------------------------------------+ print("") cost = input("Enter the cost of your items: ") cost = float(cost) isTeacher = input("Are you a music teacher (y or n)? ") def nicePrint(a, b): output = "" max_length = 50 a_length = len(a) b_length = len(b) diff_length = max_length - (a_length + b_length) output = a for _ in range(diff_length): output = output + " " output = output + b print("%s" % (output) ) def compute(cost, isTeacher): option = 0 discount = 0 if (isTeacher == "y"): option = 1 if (option == 1): if (cost < 100): discount = 10.0 else: discount = 12.0 d = cost / 100.0 * discount total_d = cost - d sales_tax = total_d / 100.0 * 5.0 total = sales_tax + total_d a = "Total purchases: " b = "%.2f" % (cost) nicePrint(a, b) a = "Teacher’s Discount (%.2f%%): " % (discount) b = "%.2f" % (d) nicePrint(a, b) a = "Discounted Total: " b = "%.2f" % (total_d) nicePrint(a, b) a = "Sales Tax (5%) " b = "%.2f" % (sales_tax) nicePrint(a, b) a = "Total " b = "%.2f" % (total) nicePrint(a, b) else: sales_tax = cost / 100.0 * 5.0 total = sales_tax + cost a = "Total purchases: " b = "%.2f" % (cost) nicePrint(a, b) a = "Sales Tax (5%) " b = "%.2f" % (sales_tax) nicePrint(a, b) a = "Total " b = "%.2f" % (total) nicePrint(a, b) def main(): print("") compute(cost, isTeacher) print("") main()
true
3e76a84df28cdb443ab75c6892b68af713f584e0
NiAT2704/PythonLab9
/p2.py
791
4.46875
4
#Lambda Function print("1)Adding two numbers using Lambda Function:"); l=lambda a,b: a+b ans=l(5,4); print("Addition=",ans); print("----------------------------------------------------"); print("2)Multiplication using lambda function"); a=int(input("Enter the value1=")); b=int(input("Enter the value2=")); m=lambda a,b:a*b mul=m(a,b); print("Multiplication of ",a,"and",b,"=",mul); print("----------------------------------------------------"); print("3)Lambda functiion that returns even numbers from the list"); l=[1,2,3,4,5,6,7,8,9,10]; print(l); lst=list(filter(lambda x: (x%2==0),l)); print("Even numbers are",lst); lst2=list(filter(lambda y: (y%2!=0),l)); print("Odd Numbers are:",lst2); print("----------------------------------------------------");
false
1a55e60267f3cd6f295266aafd328e1195e4c66f
cooluks2/iot
/01.Interface/01_python/chapter8/guess.py
2,811
4.15625
4
# 2 # 함수 만들기 연습 import random start = 1 rng = 6 number = int(random.random()*(rng)) + start ########################################################## # 위에 것을 함수로 import random start = 1 rng = 6 def rand(start, rng): number = int(random.random()*(rng)) + start return number number = rand(start,rng) print(number) # Python에서는 이미 만들어진 함수를 변수로 쓸 수 있다. # 다만 다시 함수를 이용할 수 없다. # ex) range=10 이후 range(10) X ########################################################## # rand(start, end) 로 해보자 def rand(start, end): return int(random.random()*(end-start)) + start # 위에서 number는 필요없는 변수 ########################################################## # 앞으로 시작 함수를 만들자. def main(): start = 1 end =6 number = rand(start, end) print(number) main() # 전역변수를 다 지역변수로 옮긴 것 (전역변수의 사용을 최대한 자제하자.) ########################################################## # 랜덤한 숫자 5개 뽑아보기(main함수 내에서) def main(): start = 1 end =6 for i in range(5): number = rand(start, end) print(number) main() # entry point (다른 언어의 main 함수와 같음) ########################################################## import random def main(): com=rand(1, 100) print(com) for i in range(5): print(i+1,'번째 추측값: ', end='') me = int(input()) if i == 4: print("실패했습니다.\n정답은",com) else: if com == me: print("정답입니다.") break elif com < me: print(me, "보다는 작습니다.") else: print(me, "보다는 큽니다.") main() ############################################################ # 강사님 풀이 import random def rand(start, end): return int(random.random()*(end-start)) + start def main(): number = rand(1, 100) print(number) for i in range(1, 6): num = int(input(str(i)+ "번째 추측값: ")) result = number - num if result == 0: # 정답 print("정답입니다.") break elif result > 0: print(num, "보다는 큽니다.") else: print(num, "보다는 작습니다.") if result != 0: print('실패했습니다.\n정답은 ', number) main() # 정렬이 되어있다면 위 경우는 7번 (∵log_2 100 = 6.xxx) # 40억개 데이터면 32번 ############################################################
false
8f26a0888ae44a9d168d94e3f09cffc60e7bf697
tokaisuDev/Code-Coding-Series
/Python Family/Create/Game Series/gumballgame.py
2,844
4.125
4
#This is the final version of the game. #Don't delete it! #Press Enter to continue the sentence. #Choose the right thing! print("Hello! Oh, I forgot your name.") name = input("Please enter name") input() print("Please", name,",tell me what is going on.") input() print("Anais go to your room.") input() print("A foul curse has been unleashed upon our town by",name) input() print("Do you mean the gates of doom were opened by",name,"?") input() print("the fabric of the universe was ripped apart by", name) input() print(name,"has made quite a mess.") input() print("Here's some healing ointment to help", name,"in the heat of battle.") input() print("You got a healing ointment!") input() print("Anais and Darwin have joined your team") input() print("You go outside.") input() print("Oh no, the path is blocked by an awkwardly placed shrub") input() print("and we're apprently too stupid to walk on the lawn.") input() rightThingtodo = input("What do you do with the shrub?(hint: Based in the episode:The console.)") if "kick" in rightThingtodo: print("You are right! But, be careful!") else: print(name,"uses", rightThingtodo,".It is ineffective.") break print("A flower plant fight you!") input() print("You not careful. You lost 125 HP!") input() print("Leaf monsters would be susceptible to fire attack!") input() Choicingright = input("Do you do to Anais say and give Anais the fire power?") if Choicingright == 'Yes': print("You're right!") print("You win the fight!") elif Choicingright == "No": print("Nope") print("Leslie is the flower monster!") input() print("You meet Leslie.") input() print("Leslie? What happened to you?") input() print("I bought some fertilizer from THE AWESOME STORE") input() print("I went home after visiting THE AWESOME STORE") input() print("And use the fertilizer I'd just bought at THE AWESOME STORE") input() print("Sorry for disturb you, but i will not for you watch the next thing Leslie will saying.") print("And continue to the game!") input() print("So THE AWESOME STORE is the bad.") print("THE AWESOME STORE!") time.sleep(5) print("Make it stop!!!!!!!!!!") GoodChoice = input("Do somthing!") while True: if GoodChoice == 'Fight him': print("The right thing!....Maybe.") else: print("Do somthing more smart!") break print("We could just walked away") print("but now maybe we should run") input() print("You go to the Robbinson's house because,.......No reason. Maybe looting?") input() print("What are we doing at Mr. Robbinson's") input() print("Your choice.") input() choice = input("1 to say: get loot, 2 to say: like all the gamers do in the RPG.") while True: if choice == '1': print("Do you mean looting?") elif choice == '2': print("Do as you want. You're wrong.") break print("You see an mailbox")
true
75f5fdda85b28910a5750883fdf6b8e84ac07116
rpbarnes/codingPractice
/maxStockProfit.py
1,243
4.1875
4
""" This calculates the maximum stock profit that one could get from buying and selling stock in one day between opening and closing. I get data in the form of a list. stock_prices_yesterday = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices_yesterday) # returns 6 (buying for $5 and selling for $11) I should be able to do this by going through the list only once. That means I need to keep track of the minimum stock price and the maximum profit as I go through the list. I also need to return a negative value if the stock price goes down all day, this tells the user if they lost money during the day. """ def max_profit(stock_prices_yesterday): if len(stock_prices_yesterday) < 2: raise IndexError('length of stock prices must have two elements to calculate a profit') minPrice = stock_prices_yesterday[0] maxProfit = stock_prices_yesterday[1] - stock_prices_yesterday[0] for index,val in enumerate(stock_prices_yesterday): if index == 0: continue potentialProfit = val - minPrice maxProfit = max(maxProfit,potentialProfit) minPrice = min(minPrice,val) return maxProfit stock_prices_yesterday = [10, 7, 5, 4, 2, 0] profit = max_profit(stock_prices_yesterday)
true
7dccb827b63e75a1928f62e4db987538ff62b078
thepushkarp/JFF-Python-Scripts
/searchSize/searchSize.py
2,043
4.4375
4
""" searchSize.py - Lets you search through a folder based on file size. Files and subfolders greater than or equal to the size entered, would be displayed. Usage: run "python3 searchSize.py". When prompted, enter the minimum size (in bytes) and the folder where files are to be searched. If the path entered is correct, the files, above and equal the size entered would be displayed. """ import os import sys # Dictionary to save large files/folders with path as key ad size as # value large = {} # Get size of folder and save path of files and folders greater than # input size to the dict. large def getSize(folPath): totalSize = 0 for folderName, subfolders, fileNames in os.walk(folPath): for subfolder in subfolders: subfolderPath = os.path.join(folderName, subfolder) subfolderSize = getSize(subfolderPath) if subfolderSize >= size: large[subfolderPath] = subfolderSize totalSize += subfolderSize for fileName in fileNames: filePath = os.path.join(folderName, fileName) if not os.path.islink(filePath): # Skip if symbolic link fileSize = os.path.getsize(filePath) if fileSize >= size: large[filePath] = fileSize totalSize += fileSize return totalSize # Input minimum size size = int(input('Enter the minimum size (in bytes)\n')) # Input folder name folder = input('Enter the path of the folder to search\n') folder = os.path.abspath(folder) # Absolute path # Verify if folder name and path exists if not os.path.exists(folder): print('The folder path entered does not exists.') sys.exit() else: folderSize = getSize(folder) # If no files/folders found if large == {}: print(f'There are no files or folders with size greater than {size} \ bytes.') # Print paths with size else: print(f'The files and folders with size greater than {size} are:') for path in large.keys(): if os.path.isfile(path): print(f'The size of the file {path} is: {large[path]} bytes.') elif os.path.isdir(path): print(f'The size of the folder {path} is: {large[path]} bytes.')
true
208078347c96e9e95d01c7f32215eae3e0fd78e8
Pandiarajanpandian/Python---Programming
/Beginner Level/PrimeOrNot.py
204
4.125
4
num=int(input("enter a number")) if num>1: for i in range(2,num): if (num%i)==0: print("the number is not a prime") break else: print("prime") else: print("not a prime")
true
b3657005cbe629cd2b16eb4a25c1416b7b4581cd
mas2020-python/flask-api
/src/create_sqlite_test.py
1,737
4.21875
4
import sqlite3 def create_db(db: str): # connection to temp db connection = sqlite3.connect(db) cursor = connection.cursor() # create the users' table cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER NOT NULL, username VARCHAR(100), password VARCHAR(100), PRIMARY KEY (id) ) """) cursor.execute("""CREATE TABLE IF NOT EXISTS items ( id INTEGER NOT NULL, name VARCHAR(100), price FLOAT, store_id INTEGER, PRIMARY KEY (id), FOREIGN KEY(store_id) REFERENCES stores (id))""") cursor.execute(""" CREATE TABLE IF NOT EXISTS stores ( id INTEGER NOT NULL, name VARCHAR(80), PRIMARY KEY (id)) """) # create a tuple for users users = [(1, "ag", "test")] cursor.execute("DELETE FROM users") cursor.execute("DELETE FROM stores") cursor.execute("DELETE FROM items") # insert row (to add more rows use executemany) cursor.executemany("INSERT INTO users (id,username,password) VALUES (?,?,?)", users) # stores stores = [(1, "store-1"), (2, "store-2"), (3, "store-3"), ] cursor.executemany("INSERT INTO stores (id,name) VALUES (?,?)", stores) # items items = [(1, "item-1", 10.0, 1), (2, "item-2", 12.03, 2), (3, "item-3", 99, 2), ] cursor.executemany("INSERT INTO items (id,name,price,store_id) VALUES (?,?,?,?)", items) connection.commit() connection.close() # If started as main module create temp data.db and insert users inside if __name__ == "__main__": create_db('data.db')
true
f25e20e38f507a749f6e17b13c5908c686a1282c
Mudassir-Hasan/python-46-simple-exercise
/25.py
1,313
4.25
4
# QUESTION : # 25. In English, the present participle is formed by adding the suffix ­ing to the infinite form: go ­> going. # A simpleset of heuristic rules can be given as follows: # 1. If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.) # 2. If the verb ends in ie, change ie to y and add ing # 3. For words consisting of consonant-­vowel-­consonant, double the final letter before adding ing # 4. By default just add ing # Your task in this exercise is to define a function make_ing_form() # which given a verb in infinitive form returns its present participle form. # Test your function with words such as lie, see, move and hug. # However,you must not expect such simple rules to work for all cases # Solution : def make_ing_form(form) : if (form.endswith('ie')) : form = form.replace(form[-2:: ] ,'y') form += 'ing' elif (form.endswith('e')) : if (form.endswith('ee')): form += 'ing' else: form = form.replace(form[-1] ,'') form += 'ing' else: form += 'ing' return form # checking : print(make_ing_form('be')) print(make_ing_form('flee')) print(make_ing_form('see')) print(make_ing_form('knee'))
true
808f66f4de8a52a918d72cf1ff0a151c7039f868
Mudassir-Hasan/python-46-simple-exercise
/10.py
919
4.1875
4
# QUESTION : # 10. Define a function overlapping()that takes two lists and returns True if they have at least one member in # common, False otherwise. You may use your is_member() function, or the in operator, but for the sake # of the exercise, you should (also) write it using two nested for­loops. # Solution : def overlapping(lst1 , lst2) : if ( len(lst1) > len(lst2) ) : for item2 in lst2 : for item1 in lst1: if(item2 == item1): return True elif ( len(lst2) > len(lst1) ): for item1 in lst1 : for item2 in lst2 : if ( item1 == item2 ) : return True return False list1 = [1,2,3,4,5,6] list2 = [6,7,8,9,10] # function calling f = overlapping(list1, list2) print(f)
true
c30dec206a45b26b3dd0e490d6808944d1b13221
Mudassir-Hasan/python-46-simple-exercise
/38.py
564
4.40625
4
# QUESTION : # 38. Write a program that will calculate the average word length of a text stored in a file # (i.e the sum of all thelengths of the word tokens in the text, divided by the number of word tokens). # Solution : def calculator (fileName) : with open(fileName , 'r') as f : content = f.read() l = [] lst = content.split() for item in lst : l.append(len(item)) avg = sum(l) / len(l) return f'The average of length of words in given file is {int(avg)}' print(calculator('38.text') )
true
c72b8b73311cc3d3bad1df449bb796c35b90e76b
shakirahola/Retirement-account
/Oladokun_Shakirah_FP/Transactionitem.py
1,366
4.15625
4
# Author : Shakirah_Oladokun # Assignment number & name: Final Project # Date : July 2020 # Program Description: Problem Solving and programming #The TransactionItem class holds data fot ID,name,quntity and price class TransactionItem(): #Initialize the data attribute def __init__(self): self.__id = 0 self.__name = "" self.__quantity = 0 self.__price = 0 #create the get and set methods def get_id(self): return self.__id def set_id(self, new_id): self.__id = new_id def get_name(self): return self.__name def set_name(self, new_name): self.__name = new_name def get_qty(self): return self.__quantity def set_qty(self, new_qty): #Ensure quantity is positive if new_qty > 0: self.__quantity = new_qty def get_price(self): return self.__price def set_price(self, new_price): self.__price = new_price #Calculate the total cost of the transaction def calc_cost(self): cost = self.__quantity * self.__price return cost def __str__(self): transaction_cost = format(self.calc_cost(), '.2f') strout = str(self.__id) + ' ' +self.__name + ' ' + \ str(self.__quantity) + ' $' + str(transaction_cost) return strout
true
9ff29c29222e8bc93c20b5bc0923cca7876c5a66
helenajuliakristinsdottir/Tile-Traveller
/Code listing/Code Listing 2.20, game.py
1,047
4.1875
4
#leikur, að giska á rétta tölu #while-else #Simple guessing game: start við a random numer and guess with hints until: #Guess is correct #the guess is out of range indicating the user is quitting #All non-typed variables ar integers import random #get the random number module number = random.randint(0,100) #get a random number, milli 0 og 100 að meðtöldum 0 og 100, random integer print('Hi-Lo Number Guessing Game: between 0 and 100 inclusive.') print() #get an initial guess guess_str = input('Guess a number: ') guess=int(guess_str) #while guess is range, keep asking while 0 <= guess <= 100: if guess > number: print('Guessed Too High.') elif guess < number: print('Guessed Too Low.') else: print('You guessed it. The number was:',number) break #þá skippa ég else suitið á while lykkjunni og fer út úr öllu #keep going, get the next guess guess_str = input('Guess a number: ') guess=int(guess_str) else: print('You quit early, the number was:',number)
false
e4b2f82db93e148b5c0679d7fdd64aa90b5483a1
Dharmendar-G/Python_Assignments
/4.Arrays/specific_array_value.py
374
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 29 16:15:00 2021 @author: dharmendar """ # function to test if array contains a specific value def array_contains_value(arr,x): for i in range(len(arr)): if(arr[i] == x): return print(True) return print(False) arr = [1,2,3,5,6,7,8] array_contains_value(arr, 4) array_contains_value(arr, 6)
true
c334f43cf5d29d7131bb455de19213e326d31feb
Dharmendar-G/Python_Assignments
/5.Static/3_static_instance.py
512
4.25
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 30 11:15:34 2021 @author: dharmendar """ # 3. Define a static variable and change within the instance '''Static methods cannot access or change the values of instance variables, but instance variables can access or change the values of static variables''' # Static Variable class static: my_var = 'static variable' # Creating Instance instance = static() # changing within the instance instance.my_var = 'Instance variable' print(instance.my_var)
true
8ce0268155d4711befc4092ef92910b322ebd7ff
Werefriend/CS112-Spring2012
/hw05/lists.py
2,105
4.3125
4
#!/usr/bin/env python """lists.py A bunch of excercises to see if you understand list comprehensions """ # Solve the following problems with one python statement. It is fine # to break up the statement into multiple lines as long as it is only # one actual command. # # This is fine: # print [ (x,y) # for x in range(10) # for y in range(10) ] # # 1. Read a bunch of numbers from the input separated by spaces and # convert them to ints print "1.", [ int(i) for i in raw_input().split(" ") ] # 2. Read another bunch of numbers, convert them, and return the list # of only the first 3 print "2.", [ int(i) for i in raw_input().split(" ") ][:3] # 3. Read a bunch of words separated by commas from the command line, # remove any excess spaces, and print a list of their lenghts print "3.", [ len(s.strip()) for s in raw_input().split(",") ] # 4. Create a list of every multiple of 3 between 1 and 100 with their # index # ex: [ [0,3], [1,6], [2,9]...] print "4.", [ (i,v) for i,v in enumerate(range(3,100,3)) ] # 5. create a list of every card in a deck of card print "5.", [(s,t) for s in ["spades","hearts","diamonds","clubs"] for t in ["A","2","3","4","5","6","7","8","9","J","Q","K"]] # 6. Create a 5 by 5 array filled with zeros print "6.", [[ 0 for i in range(5) ] for j in range(5) ] # 7. Make a list of every perfect square between 1 and 1000 print "7.", [ i**2 for i in range(100) if i**2 < 1000 ] # 8. Make a list of every perfect square between 1 and 1000 # a different way import math print "8.", [ i for i in range(1000) if math.sqrt(i) % 1 == 0 ] # 9. List every python file in this directory import os print "9.", [ s for s in os.listdir(".") if s.endswith(".py")] # 10. Print a list of every pythagorean triple with a side less than # or equal to 20. Don't include duplicates ([3,4,5] == [4,3,5]) print "10.", [ (x,y,z) for x in range(1,21) for y in range(1,21) for z in range(1,21) if x**2 + y**2 == z**2 and x >= y ]
true
37d93e10e3654a6ae1bea97bb11f3d6acae1718d
Werefriend/CS112-Spring2012
/day12.py
764
4.1875
4
#!/usr/bin/env python class Student(object): def __init__(self, name = "Jane Doe"): self.name = name def say(self, message): print self.name + ": " + message def say_to(self, other, message): self.say(message + ", " + other.name) def printing(self): print self.name class Course(object): def __init__(self, name): self.name = name self.enrolled = [] def enroll(self, student): self.enrolled.append(student) def printMe(self): for student in self.enrolled: student.printing() bob = Student("Bob") fred = Student("Fred") cs112 = Course("CS112") bob.say_to(fred, "Hi") fred.say_to(bob, "Go away") cs112.enroll(bob) cs112.enroll(fred) cs112.printMe()
false
dbe70e24335e1a89954a7e7fe3d21146c7b7273c
Werefriend/CS112-Spring2012
/hw04/sect1_if.py
732
4.21875
4
#!/usr/bin/env python from hwtools import * print "Section 1: If Statements" print "-----------------------------" # 1. Is n even or odd? n = raw_input("Enter a number: ") n = int(n) if n%2 == 0: print "1.", "%d is even." %(n) else: print "1.", "%d is odd." %(n) # 2. If n is odd, double it if n%2 == 1: n*=2 print "2.", n # 3. If n is evenly divisible by 3, add four if n%3 == 0: n += 4 print "3.", n # 4. What is grade's letter value (eg. 90-100) grade = raw_input("Enter a grade [0-100]: ") grade = int(grade) lettergrade = "A" if grade < 90: lettergrade = "B" if grade < 80: lettergrade = "C" if grade < 70: lettergrade = "D" if grade < 60: lettergrade = "F" print "4.", lettergrade
false
193894f4b940c9283832167d284a525c2368ebd2
davidkirakosyan/MIPT-Python-lab
/Lab 2 (Turtle part 1)/Упражнение N11/butterfly.py
433
4.40625
4
import turtle def two_circles(radius): '''Drawing two opposite circles.''' step = radius * 3 / 57.3 for i in range(int(360 / 3)): turtle.forward(step) turtle.left(3) for i in range(int(360 / 3)): turtle.forward(step) turtle.right(3) turtle.shape('turtle') # making circles horizontal turtle.left(90) for i in range(70, 140, 10): two_circles(i) # hold window turtle.mainloop()
true
353b257f56c38e04f1df743d96305e8a75ad2e71
AMUSLU/bioinformatics
/lentghofstring.py
822
4.21875
4
## Another useful built-in tool in Pyhton is len function #len("ATGC") BUT the len fuction does not put an outcome to the screen when we run # the program. It only uoutputs a value that can be stored. dna_length = len("AGCCCCTTGGAGATGACCCAGGTCCCCTTTTAATTATCCGGAAGAGAT") print(dna_length) dna_length = len("AGCCCCTTGGAGATGACCCAGGTCCCCTTTTAATTATCCGGAAGAGAT") b = len("AAAAAAA") print(str(b) + str(dna_length)) # if you run this code the result will be 48 #PYTHON TREATS STRINGS AND NUMBERS (INT // INTEGER) DIFFERENTLY #BUT PYTHON HAS A SOLUTION FOR THAT. THE SOLUTION IS TO CREATE A STRING FOR # THE NUMBER SO THAT WE CAN STCIK TO STRINGS TOGETHER my_dna = "ATGCGAGT" dna_length = len (my_dna) print ("The length of the DNA sequence is" + " " + str(dna_length)) print(str(dna_length))
true
9c174517fd60bff1ed0e04c6306f96637209cbae
petrussola/Sprint-Challenge--Algorithms
/recursive_count_th/count_th.py
1,130
4.34375
4
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): # if initial word is less than 2 words, return 0 # because it won't be possible for the word # to be "th" if len(word) < 2: return 0 # Recursive component # If we are assessing the last 2 chars of the word # and if word matches 'th', return 1 elif len(word) == 2 and word == "th": return 1 # if the last 2 chars are not 'th', return 0 elif len(word) == 2 and word != "th": return 0 # if word length is bigger than 2, then check # the first 2 chars. If they match 'th' it means # that we should call teh recursion with our # counter at 1. That is why we call 1 + recursion elif word[0:2] == "th": return 1 + count_th(word[1:]) # if the first 2 chars are not 'th', then # we call the recursion without any counter else: return count_th(word[1:])
true
4735d9a64dd2fafb68a32614f7769a46d32586c9
ElAwbery/Python-Practice
/Loops/while_loop_practice.py
2,235
4.65625
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 9 17:15:04 2018 @author: ElAwbery """ ''' Taken from various versions on Stack Overflow ''' ''' Use a while loop to print a triangle of asterisks, like this: * *** ***** ******* ********* ''' count = 0 asterisks_low = 5 asterisks_high = 5 characters_in_row = 10 row = "" while count < 5: for character in range(characters_in_row): if character >= asterisks_low and character <= asterisks_high: row += '*' else: row += ' ' print (row) count += 1 asterisks_low -= 1 asterisks_high += 1 row = "" ''' Write a function that prints a triangle of asterisks like the one in the previous question. The function should accept a single parameter, height, that defines how tall the triangle is (in the previous example height = 5). Use a while loop and ensure your function works by trying different heights. ''' def asterisks_triangle(height): """ Assumes height is an integer representing number of rows desired Prints a triangle of asterisks containing rows of height specification eg: if height = 9, there are 9 rows in the triangle """ count = 0 characters_in_row = (height*2)-1 asterisks_low = int(characters_in_row/2) asterisks_high = int(characters_in_row/2) row = "" while count < height: for character in range(characters_in_row): if character >= asterisks_low and character <= asterisks_high: row += '*' else: row += ' ' print (row) count += 1 asterisks_low -= 1 asterisks_high += 1 row = "" test1 = asterisks_triangle(7) test2 = asterisks_triangle(10) test3 = asterisks_triangle(24) ''' When the condition for the while loop requires a lot of code, it is sometimes more readable to loop forever and explicitly use the break keyword. Fix the following code to do this: ''' attempts = 0 while True : response = input("Do you want to quit? (y/n): ") attempts += 1 if response == 'y': break print("Exiting after", attempts, "attempts")
true
75c1b02eda3eaf6a513a8c3952e64ebad5e07f23
abervit/Python-Base
/hw_1.py
382
4.46875
4
#### If we want to calculate the area of rectangle we need to know two sides of it - length and width print("Area = width*length") width = float(input("Enter your width: ")) length = float(input("Enter your length: ")) ### we can use float or int functions. depends on our numbers - whole or decimals area = width*length print(area) print("The area of rectangle is ", area)
true
fa19dcda22ede750df790f3f70b0a3a4565284a0
abervit/Python-Base
/less25_classes_objects.py
684
4.34375
4
# Classes & Objects # With classes we can create our own data type class Student: """init is defining what is object of the class""" def __init__(self, name, major, gpa, is_on_probation): # self.name means -> student's name will be equal to a name that we pass, # the same with major, gpa and is_on_probation self.name = name self.major = major self.gpa = gpa self.is_on_probation = is_on_probation """The object is the instance of the class""" """if we want to import class Student from other file""" """ from Student import Student """ student1 = Student("Mark", "Art", 3.2, False) print(student1.name) # --> Mark
true
e76208d70f10f1b15ab5930687b3f996880ef0f9
abervit/Python-Base
/less2_strings.py
1,125
4.40625
4
# Working with strings """Creating a string""" print("Giraffe Academy") print("Giraffe \nAcademy") print("Giraffe \"Academy") # allowing us to have a quotation mark before academy """Concatenation""" phrase = "Giraffe Academy" new_pharase = "Welcome to " + phrase print(new_pharase) # --> Welcome to Giraffe Academy """Functions""" phrase = "Giraffe Academy" print(phrase.isalnum()) # --> False print(phrase.lower()) # --> giraffe academy print(phrase.upper()) # --> GIRAFFE ACADEMY print(phrase.capitalize()) # --> Giraffe academy print(phrase.swapcase()) # --> gIRAFFE aCADEMY print(phrase.upper().isupper()) # --> True print(len(phrase)) # --> 15 print(phrase.replace("Giraffe", "Crocodile")) # --> Crocodile Academy print(phrase[2:5]) # --> raf """Index function tells where is the first occurrence of specified character. We also can specify the position space - like between 0th and 10th index of the string""" print(phrase.index("a", 0, 15)) # --> 3 print(phrase.index("a")) # --> 3 """Some other functions""" phrase = "Giraffe Academy" print(phrase.count("a")) # --> 2 print(phrase.count("a", 0, 3)) # --> 0
true
aa30c28a505be26dadea27d9192298e2d9ed0853
AdemHodzic/python-learning
/Day #13/oddFibonaccis.py
438
4.15625
4
def main(): number = int(input('Enter your number: ')) print(sumOdds(number)) def sumOdds(number): sum = 0 counter = 1 while fibonacci(counter) <= number: if fibonacci(counter) % 2 == 1: sum += fibonacci(counter) counter += 1 return sum def fibonacci(num): if num == 0: return 0 elif num == 1: return 1 else: return fibonacci(num - 1) + fibonacci(num - 2) if __name__ == '__main__': main()
false
eec1595a564b84d29d528e60ab60481ccebf1c98
voidyao/mytest
/qiepiantest.py
552
4.1875
4
# itemslist = ['bord', 'computer', 'cpu', 'memory', 'ip'] # print("The first there iteams in the list are: ") # print(itemslist[:3]) # print("\nThere items from the middle of the list are: ") # print(itemslist[1:4]) # print("\nThe last there items in the list are: ") # print(itemslist[2:5]) mypizzas = ['bishenke', 'kfc', 'hh'] myfriendpizzas = mypizzas[:] myfriendpizzas.append("zz") print("My favorite pizzas are: ") for pizza1 in mypizzas: print(pizza1) print("My friends favorite pizzas are: ") for pizza in myfriendpizzas: print(pizza)
true
949fe465342bca0da3e346bafc65ad56f9df4800
gisli91/gitproject
/sequence.py
435
4.25
4
n = int(input("Enter the length of the sequence: ")) # Do not change this line counter = 0 #Need 3 ints which change values since the sequence is int1 + int2 + int3 first_int = 1 second_int = 1 third_int = 0 printed_int = first_int for x in range(n): print(printed_int) first_int, second_int = second_int, third_int third_int = printed_int printed_int = first_int + second_int + third_int
true
3cdd45515d57d20193f2fd6cf69e54743738c48f
justintucker1/interview-questions
/hw/recursion-hw.py
366
4.125
4
#!/usr/bin/python3 def print_reverse(a): def f(i): if i == len(a): return f(i + 1) print(a[i]) f(0) def reverse_string(str): def f(s): i = len(str) - len(s) - 1 if i < 0: return s return f(s + str[i]) return f('') a = [1,2,3] print_reverse(a) print(reverse_string('hello'))
false
8f5871997f77fa8129c44dcbef44d5f92cf629e2
deshearth/python-exercise
/chap7/dict.py
826
4.34375
4
# examples to create a dictionary dict(zip(('x','y'),(1,2))) # the dictionary would be {'x':1,'y':2} #dict(['x',1]) why this does not work # may when there is only one key, it must be like this # dict1 = {'x':1} dict([['x',1],['y',2]]) # the dictionary would be {'x':1,'y':2} # so I think if the parameter in the dict is sequence container, every # elements in the container must have two elements # and the number of parameter must be one and the number of parameter's # elements must be larger than one # in detail: ''' dict(['x',1]) NO dict(['x',1],['y',2]) NO dict(['x',2,3],['y',3,5]) NO dict([['x',1],['y',2],['u',4]]) YES ''' # some other methods to create dictionary d = {} # it means that d is a dictionary d['a'] = 2 print d['a'] # or d = {'a':2} dict8 = dict(x=1,y=2) # copy dict9 = dict8.copy()
true
d259339ba005c66798feba3107a1fd7c8ef0a834
gibson1395/CS0008-f2016
/f2016_cs8_sag122_a1/f2016_cs8_sag122_a1.py
1,960
4.25
4
# have the user enter which system they would like to use system = str(input('Would you like to use USC or Metric: ')) # have the user enter the distance and gas used for their appropriate system distance = float(input('Enter the distance driven: ')) gasUsed = float(input('Enter the gasoline used: ')) # USC to metric: metricDistance = float(format(distance * 1.60934, '10.3f')) metricGas = float(format(gasUsed * 3.78541, '10.3f')) # Metric to USC: usDistance = float(format(distance * 0.621371, '10.3f')) usGas = float(format(gasUsed * 0.264172, '10.3f')) # depending on which system the user # entered, those numbers will be converted to the other system if system == str('USC'): print('The distance driven in kilometers is', metricDistance) print('The liters of gasoline used is', metricGas) elif system == str('Metric'): print('The distance driven in miles is', usDistance) print('The gallons of gasoline used is', usGas) else: print('An error occurred') # fuel consumption rating fuelConsumptionUSA = float(format(usDistance / usGas, '10.3f')) fuelConsumptionMetric = float(format(((100 * metricGas) / metricDistance), '10.3f')) # print the fuel consumption rating print('The fuel consumption in miles per gallon:', fuelConsumptionUSA) print('The fuel consumption in liters per 100 kilometers:', fuelConsumptionMetric) # give the consumption rating a category based on 1/100Km if fuelConsumptionMetric > 20: print('The gas consumption rating is extremely poor') elif fuelConsumptionMetric > 15 and fuelConsumptionMetric <= 20: print('The gas consumption rating is poor') elif fuelConsumptionMetric > 10 and fuelConsumptionMetric <= 15: print('The gas consumption rating is average') elif fuelConsumptionMetric > 8 and fuelConsumptionMetric <= 10: print('The gas consumption rating is good') elif fuelConsumptionMetric <= 8: print('The gas consumption rating is excellent') else: print('An error occurred')
true
f933fbbd95a3f4b88f609942420e6819f24f65c7
gibson1395/CS0008-f2016
/Chapter 2 Exercise 9.py
298
4.34375
4
# have user enter temperature temperature = float(input('Enter the temperature in degrees Fahrenheit ')) # conversion into celsius celsius = float(5 * (temperature - 32) / 9) # display the current temperature in celcius print('The current temperature in degrees Celsius: ' + format(celsius, '.2f'))
true
342b8876dd5bbd1d24950c289b9e22c080c33d37
MukeshLohar/Python
/__pycache__/Exercise File/question95.py
366
4.28125
4
# # Please write a program which accepts a string from console and print it in reverse order. # Example: # If the following string is given as input to the program: # rise to vote sir # Then, the output of the program should be: # ris etov ot esir s = [ x for x in input().split(' ')] s = s[::-1] y= [] for x in s : x = x[::-1] y.append(x) print(y)
true
a3ddd15b9908433bde0a8a2c74cbe4a9c84d9a67
MukeshLohar/Python
/__pycache__/Exercise File/question59.py
326
4.125
4
# Assuming that we have some email addresses in the "username@companyname.com" format, # please write program to print the company name of a given email address. Both user names and company names are composed of letters only. import re emailAddress = 'mukesh@yahoo.com' pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAddress) print(r2.group(2))
true
85496d9a8c0226761b1a32dcd39f2081e1a3e239
katzuv/pre-season
/functions/ex02.py
1,712
4.625
5
"""A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice: def do_twice(f): f() f() Here’s an example that uses do_twice to call a function named print_spam twice. def print_spam(): print('spam') do_twice(print_spam) 1. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument. 2. Copy the definition of print_sum from earlier chapter to your script. 3. Use the modified version of do_twice to call print_twice twice, passing 2 as an argument. 4. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.""" """This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ def do_twice(func, arg): """Runs a function twice. func: function object type func: function arg: argument passed to the function """ func(arg) func(arg) def print_square(x): """Prints the argument twice. arg: any number """ print(x ** 2) print(x ** 2) def do_four(func, arg): """Runs a function four times. func: function object arg: argument passed to the function """ do_twice(func, arg) do_twice(func, arg) def main(): do_twice(print_square, 2) print('') do_four(print_square, 2) if __name__ == '__main__': main()
true
4d3b4516e68f3755ed48bf6700a4c25a3a11baba
Chris-Maina/Boot-camp-Day-4
/missing_number.py
732
4.21875
4
import collections def find_missing(arr1,arr2): #check if arr1 and two are empty if len(arr1)&len(arr2)==0: return 0 #check if arr1 and arr2 are same if not set(arr1).symmetric_difference(set(arr2)): return 0 #finds and returns missing number else: #creating sets from parameters first_set = set(arr1) second_set = set(arr2) #returns missing number using Symmetric difference return list(first_set.symmetric_difference(second_set) ) """ def main(): #list1 = find_missing([2], [2]) #list2 = find_missing([4, 6, 8], [4, 6, 8, 10]) #list3 = find_missing([5, 4, 7, 6, 11, 66], [5, 4, 1, 7, 6, 11, 66]) #print list2 #find_missing([list1,list2,list3]) if __name__ == '__main__': main() """
true
188a5dbbfb91ac8270ffef27f1e48bbe3e43b636
duanlidewugui/day3
/frog.py
385
4.125
4
# #一只青蛙掉在井里了,井高20米, # 青蛙白天往上爬3米,晚上下滑2米, # 问第几天能出来?请编程求出。 # #掉下去的天数 day = 1 #距离井口的米数 meter = 20 while meter>0: meter -= 3 if meter<=0: break meter += 2 day += 1 print("青蛙跳出来了") print("青蛙总共跳了",day,"天")
false
6e091227580a085a5a77a12421f1b368e0da0b03
ahuja-shivam/educative_machine_learning
/Numpy/1_numpy_indexing.py
1,045
4.375
4
import numpy as np #index is almost same as we do in arrays #slicing arr = np.array([1, 2, 3, 4, 5]) print(repr(arr[:])) print(repr(arr[1:])) print(repr(arr[2:4])) print(repr(arr[:-1])) print(repr(arr[-2:])) #Slicing in one d array is same as that of strings and lists #If one arg is given, then slicing of outer most index is done arr1 = np.arange(9) arr1 = np.reshape(arr1,(3,3)) print(repr(arr1[1:])) #print except 1st row #For multi-dimensional arrays, we can use a comma to separate slices across each dimension. print(repr(arr1[:, -1])) #print last element(column) of every row print(repr(arr[:, 1:])) #print except 1st element of each row print(repr(arr[0, 1:])) #print except 1st element of first row only #arg min & arg max print(np.argmin(arr1)) #index of a flatten array print(repr(np.argmin(arr, axis=0))) #axis 0 means among columns print(repr(np.argmin(arr, axis=1))) #axis 1 means among rows print(repr(np.argmax(arr, axis=-1))) #axis = -1 means across last dimension, in this case -1 means 1, in case 3d, it will bw 2
true
7fe3611e3d9980a6ebd472db6ab887b9b4a076cd
verdatestudo/Algorithms_Khan
/selection_sort.py
1,130
4.46875
4
''' Algorithms from Khan Academy - selection sort https://www.khanacademy.org/computing/computer-science/algorithms Last Updated: 2016-May-11 First Created: 2016-May-11 Python 2.7 Chris ''' def selection_sort(my_list): ''' There are many different ways to sort the cards. Here's a simple one, called selection sort, possibly similar to how you sorted the cards above: Find the smallest card. Swap it with the first card. Find the second-smallest card. Swap it with the second card. Find the third-smallest card. Swap it with the third card. Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted. ''' if len(my_list) == 1: return my_list small = float('inf') for idx, item in enumerate(my_list): if item < small: small = item small_idx = idx my_list[small_idx] = my_list[0] my_list[0] = small return [my_list[0]] + selection_sort(my_list[1:]) print selection_sort([1, 4, 21, 3, 8, 12, 99, 2, 2, -1]), [-1, 1, 2, 2, 3, 4, 8, 12, 21, 99]
true
86353fec06214eaca6e8576e5317af2a23ea385a
CaoYiMing0/PythonStudy_2020621
/day_02/Test06_更新列表.py
2,261
4.1875
4
a = [1, 2, 3, 2, 1] a[1] = 10 print(a[1]) # 10 a[2] = 'hello' print(a) # [1, 10, 'hello', 2, 1] print(type(a)) # <class 'list'> print(type(a[1])) # <class 'int'> print(type(a[2])) # <class 'str'> """ 由上面的输出结果可知,可以对一个列表中的元素赋不同类型的值 """ # 加入对列表赋值时使用的编号超过了列表中的最大编号,是否还可以赋值呢?答案是不可以 tring = [1, 2, 3] # tring[3]='test'#错误:IndexError: list assignment index out of range print("----------------------------------------------------") # 增加元素 tring1 = [1, 2, 3] tring1.append(4) print(tring1) # [1, 2, 3, 4] tring1.append('test') print(tring1) # [1, 2, 3, 4, 'test'] s = ['a', 'b', 'c'] s.append(4) print(s) # ['a', 'b', 'c', 4] print("------------------------------------------------------") # 删除元素 tring2 = ['a', 'b', 'c', 'd', 'e'] print(len(tring2)) # 5 del tring2[1] print(tring2) # ['a', 'c', 'd', 'e'] print(len(tring2)) # 4 num = [1, 2, 3, 4] del num[1] print(len(num)) # 3 print("---------------------------------------------") # 分片赋值 print(list('正道的光')) # ['正', '道', '的', '光'] boil = list('正道的光') print(boil) # ['正', '道', '的', '光'] show = list('hi,boy') print(show) # ['h', 'i', ',', 'b', 'o', 'y'] show[3:] = list('man') print(show) # ['h', 'i', ',', 'm', 'a', 'n'] # list()函数可以直接将字符串转换为列表 greeting = list('hi') print(greeting) # ['h', 'i'] greeting[1:] = list('ello') print(greeting) # ['h', 'e', 'l', 'l', 'o'] # 分片赋值的另一个强大的功能就是 可以使用与原序列不等长的序列将分片替换 field = list('ae') print(field) # ['a', 'e'] field[1:1] = list('bcd') print(field) # ['a', 'b', 'c', 'd', 'e'] boil2 = list('正道的光') boil2[3:3] = list('大太阳') print(boil2) # ['正', '道', '的', '大', '太', '阳', '光'] field=list('abcd') print(field)#['a', 'b', 'c', 'd'] field[1:3]=[] print(field)#['a', 'd'] boil3 = list('正道的大太阳光') boil3[3:6]=[] print(boil3)#['正', '道', '的', '光'] """ 通过上面示例可以看出,通过分片赋值删除元素也是可行的, 并且分片赋值删除的功能和del删除的操作结果时一样的。 """
false
c926ddfa2b5e479f88aec6c8ee3a3e902058c6af
CaoYiMing0/PythonStudy_2020621
/day_07/Test16_多继承注意事项_多父类存在同名的属性和方法.py
711
4.28125
4
""" 如果不同的父类存在同名的方法,子类对象在调用方法时,会调用哪一个父类中的方法呢? 开发时,应该尽量避免这种容易产生混淆的情况!--如果父类之间存在同名的属性和方法, 应该尽量避免使用多继承。 """ class A: def test(self): print("A test 方法") def demo(self): print("A demo 方法") class B: def test(self): print("B test 方法") def demo(self): print("B demo 方法") class C(A, B): pass c = C() c.test() # A test 方法 c.demo() # A demo 方法 # 调整继承顺序 class D(A, B): pass d = D() d.test() # A test 方法 d.demo() # A demo 方法
false
37fe324ed65257ff37adf267cdaf870ccf08f51f
CaoYiMing0/PythonStudy_2020621
/day_05/Test12_for循环.py
962
4.15625
4
""" 语法格式如下: for iterating_var in sequence: statements(s) sequence是任意序列,iterating_var是序列中需要遍历的元素。statements是待执行的语句块 """ fields = ['a', 'b', 'c'] for f in fields: print('当前字母是:', f) print('-----for循环字符串-----') for letter in 'good': print('当前字母:', letter) print('-----for循环数字序列-----') number = [1, 2, 3] for num in number: print('当前数字:', num) print('-----for循环字典-----') tups = {'卢本伟': '1001', '五五开': '1002', 'white': '1003'} for tup in tups: print('%s:%s' % (tup, tups[tup])) """ 当前字母是: a 当前字母是: b 当前字母是: c -----for循环字符串----- 当前字母: g 当前字母: o 当前字母: o 当前字母: d -----for循环数字序列----- 当前数字: 1 当前数字: 2 当前数字: 3 -----for循环字典----- 卢本伟:1001 五五开:1002 white:1003 """
false
583713f5a424d5e758ce31be2f0201c88fd21595
CaoYiMing0/PythonStudy_2020621
/day_03/Test06_04_upper().py
688
4.59375
5
""" upper()方法用于将字符串中的小写字母转化为大写字母 upper()方法语法如下: str.upper() 该方法不需要参数,返回结果为转化后的字符串 """ field = 'do it now' print(field.upper()) # DO IT NOW greeting = 'Hello,World' print(greeting.upper()) # HELLO,WORLD print('--------------------------------------') """ 如果想要编写‘不区分大小写’的代码,就可以使用upper()方法。 如果想要在一个字符串中查找某个字符串并忽略大小写,也可以使用upper方法。 """ field = 'do it now' print(field.find('It')) # -1 print(field.upper().find('It')) # -1 print(field.upper().find('It'.upper())) # 3
false
c90620c68f5ddd281ccf8987e03403928879921e
CaoYiMing0/PythonStudy_2020621
/day_12/test02___thread模块.py
1,466
4.15625
4
""" Python中调用_thread模块中的start_new_thread()函数产生新线程。_thread的语法如下: _thread.start_new_thread(function,args[,kwargs]) 其中,function为线程函数;args为传递给线程函数的参数,必须是tuple类型;kwargs 为可选参数。 _thread模块除了产生线程外,还提供基本同步数据结构锁对象(lock object,也叫原语锁、 简单锁、互斥锁、互斥量、二值化信号量)。同步原语与线程管理是密不可分的。 """ import _thread from time import sleep from datetime import datetime date_time_format = "%y-%M-%d %H:%M:%S" def date_time_str(date_time): return datetime.strftime(date_time, date_time_format) def loop_one(): print("+++线程一开始于:", date_time_str(datetime.now())) print("+++线程一休眠4秒") sleep(4) print("+++线程一休眠结束,结束于:", date_time_str(datetime.now())) def loop_two(): print("***线程二开始于:", date_time_str(datetime.now())) print("***线程二休眠2秒") sleep(2) print("***线程二休眠结束,结束于:", date_time_str(datetime.now())) def main(): print("------所有线程开始时间:", date_time_str(datetime.now())) _thread.start_new_thread(loop_one, ()) _thread.start_new_thread(loop_two, ()) sleep(6) print("------所有线程结束时间:", date_time_str(datetime.now())) if __name__ == '__main__': main()
false
0c82f7f968419dbcc7176931f9412d234d983d6e
CaoYiMing0/PythonStudy_2020621
/day_05/Test15_翻转和排序迭代.py
677
4.28125
4
""" reversed和sorted这两个函数可作用于任何序列和可迭代对象, 但不是原地修改对象,而是返回翻转或排序后的版本。 """ print(sorted([5, 3, 7, 1])) # [1, 3, 5, 7] a = [5, 3, 7, 2] b = a a[3] = 10 print(a == b) # True print(a is b) # True c = sorted(a) print(c == a) # False print(a is c) # False print(a) # [5, 3, 7, 10] a.sort() print(a) # [3, 5, 7, 10] print(a == b) # True print(sorted('hello,world!')) # ['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] print(list(reversed('hello,world!'))) # ['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h'] print(''.join(reversed('hello,world!'))) # !dlrow,olleh
false
1c5f29b5c99eca39911c2f184da60caa497ddf8d
wentixiaogege/python
/module/fibo.py
670
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a + b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result # 1. one methond # >>> import fibo # >>> fibo.fib(1000) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 # >>> fibo.fib2(100) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # >>> fibo.__name__ # 'fibo' # 2. another method # >>> from fibo import fib, fib2 # >>> fib(500) # 1 1 2 3 5 8 13 21 34 55 89 144 233 377
false
edab073d8397de6ce2bcb002521f45b20b67b1f4
abdu95/python-projects
/Python-for-Beginners-Mosh-Hamedani/HelloWorldTwo/unpacking.py
708
4.46875
4
coordinates = (1, 2, 3) # approach 1 print(coordinates[0] * coordinates[1] * coordinates[2]) # let's say we want to use these values in quite a few places in our program, our code is getting too long # approach 2 x = coordinates[0] y = coordinates[1] z = coordinates[2] # approach 3: unpacking (less code) x, y, z = coordinates # line 10 is same as line 6-8 # When Python interpreter sees this statement, it will get the 1st item in this tuple and assign it to the x variable. so on # so we are unpacking this tuple into 3 variables print(x) print(y) print(z) # we can use this feature for lists as well: we can unpack our list into 3 variables values = [4, 5, 6] a, b, c = values print(a) print(b) print(c)
true
e2865c144f7532f3ba2d38d825b5e9496293ae51
hd8414/corepython
/loop for pattern 9.py
226
4.1875
4
for row in range(7): for col in range(7): if row==6 or row==3 or row== 0 or col==6 or(col==0 and row>=0 and row<=3): print('*',end=' ') else: print(end=' ') print ('') print('')
false
cf054d2c4d5b6b3de090cce4434fb4baa883bead
hd8414/corepython
/To find minimum number.py
1,260
4.28125
4
# program to find minimum number out of three number number_1 = float(input('Enter 1st number :')) number_2 = float(input('Enter 2nd number :')) number_3 = float(input('Enter 3rd number :')) if number_1 == number_2 and number_1 != number_3 and number_2 != number_3: print('input is incorrect as 1st and 2nd numbers are same with value %d'%number_1) elif number_2 == number_3 and number_2 != number_1 and number_1 != number_3: print('input is incorrect as 2nd and 3rd numbers are same with value %d'%number_2) elif number_1 == number_3 and number_1 != number_2 and number_2 != number_3: print('input is incorrect as 1st and 3rd numbers are same with value %d'%number_1) elif number_1 == number_2 == number_3 : print('input incorrect as entered value %d of all three numbers are same'%number_1) elif number_1 < number_2: if number_1 < number_3: print('1st number is minimum with value %.2f out of three number'%number_1) else: print('3rd number is minimum with value %.2f out of three number' % number_3) else: if number_2 < number_3: print('2nd number is minimum with value %.2f out of three number'%number_2) else: print('3rd number is minimum with value %.2f out of three number' % number_3)
true
76ebf684dab5db24c3f7533ea6b67ddd08d0c945
Coderode/Python
/OOPS/ploymorphism.py
1,756
4.375
4
#polymorphism - having many forms #same function name (but diff signatures) #being uses for diff types #inbuilt polymorphic functions print(len("Sandeep")) #len() being used for string print(len([1, 4, 6])) #len() being used for list #user defined polymorphic functions def add(x,y,z=0): return x+y+z print(add(2,3)) print(add(2,3,4)) print("\n") #polymorphism with class methods class India(): def capital(self): print("New delhi is capital of india.") def language(self): print("Hindi the primary language of india.") def type(self): print("India is a developing country.") class USA(): def capital(self): print("Washington ,d.c. is the capital of USA.") def language(self): print("English is the primary language in USA.") def type(self): print("USA is a developed country.") obj_ind=India() obj_usa=USA() for country in (obj_ind,obj_usa): country.capital() country.language() country.type() print("\n") #polymorphism with inheritance #process of reimplementing a method in the child class is kn/as method overriding class Bird: def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") class sparrow(Bird): def flight(self): print("Sparrows can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird=Bird() obj_spr=sparrow() obj_ost=ostrich() obj_bird.intro() obj_bird.flight() obj_spr.intro() obj_spr.flight() obj_ost.intro() obj_ost.flight() print("\n") #polymorphism with a function and objects #a function that can take any object #taking above exmaple of india and usa classes def func(obj): obj.capital() obj.language() obj.type() obj_ind=India() obj_usa=USA() func(obj_ind) func(obj_usa)
true
61ea8f6e1701fa5bfbf9810aac5b8702e328a2d7
Coderode/Python
/OOPS/inheritance.py
1,202
4.28125
4
#major advantage of oops is re-use #a (super class or Base class) is inherited by another class called subclass #the subclass adds some attributes to superclass #in python3 class Person is similar to class Person(object) class Person(object): #constructor def __init__(self,name): self.name=name #to get name def getName(self): return self.name #to check if this person is employee def isEmployee(self): return False #inherited or subclass (person in bracket)-shows inheritance of Person class class Employee(Person): #here we return true def isEmployee(self): return True #driver code emp=Person("person1") #obj of person print(emp.getName(),emp.isEmployee()) emp=Employee("person2") #obj of Employee print(emp.getName(),emp.isEmployee()) #to check if a class is subclass of another? #using issubclass() function class Base(object): pass class Derived(Base): pass #driver code print(issubclass(Derived,Base)) #true print(issubclass(Base,Derived))#false d=Derived() b=Base() #b is not an instance of Derived print(isinstance(b,Derived)) #but d is an instance of base print(isinstance(d,Base)) #object class-object is root of all classes #python supports multiple inheritance
true
bf7cf9fedaacfdff41e46db924574fd6c7efcc04
Coderode/Python
/OOPS/multi inheri.py
1,391
4.59375
5
#multiple inheritance #specify all parent classes as comma separated class Base1(object): def __init__(self): self.str1="hello1" print("base1") class Base2(object): def __init__(self): self.str2="hello2" print("Base2") class Derived(Base1,Base2): def __init__(self): #calling constructors of base1 and base2 classes Base1.__init__(self) Base2.__init__(self) print("Derived") def printStrs(self): print(self.str1,self.str2) ob=Derived() #as we create an object it runs __init__ method by its own #this line prints #base1 #base2 #Derived ob.printStrs() #str1 and str2 are come in derived when we called init function of base classed in derived class #it prints #hello1 hello2 ob.__init__()#-> base1 base2 Derived print("\n") '''access parent members in a subclass ''' #using parent class name class Base(object): def __init__(self,x): self.x=x class Derived2(Base): def __init__(self,x,y): Base.x=x #parent member self.y=y def printXY(self): print(Base.x,self.y) #print(self.x,self.y)#wil also work #driver code d=Derived2(10,20) d.printXY() #->prints 10 20 print("\n") #using super() class Base3(object): def __init__(self,x): self.x=x class Derived3(Base): def __init__(self,x,y): #super(Derived3,self).__init__(x) or super().__init__(x) self.y=y def printXY(self): print(self.x,self.y) #driver code d=Derived3(10,20) d.printXY()
true
2857511a333b4fc9c3f4f932e156977ca8299465
Fargekritt/Python-Fun
/checkio_solutions/Electronic Station/date_and_time_converter.py
2,238
4.3125
4
#!/usr/bin/env checkio --domain=py run date-and-time-converter # https://py.checkio.org/mission/date-and-time-converter/ # Computer date and time format consists only of numbers, for example: 21.05.2018 16:30 # Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes # Your task is simple - convert the input date and time from computer format into a "human" format. # # # # Input:Date and time as a string # # Output:The same date and time, but in a more readable format # # Precondition: # 0<date<= 31 # 0<month<= 12 # 0<year<= 3000 # 0<hours<24 # 0<minutes<60 # # # END_DESC def date_time(time: str) -> str: #replace this for solution #list of all the months for converting month number to month text month_lst = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] #time.replace(" ", ".").replace(":",".") to convert 01.01.2000 00:00 to 01.01.2000.00.00 making it easier to split in one go day, month, year, hours, mins = time.replace(" ", ".").replace(":",".").split(".") #converts month number to month text need a - 1 because the list counts from 0 - 11 and the month number is from 1 - 12 month = month_lst[int(month) - 1] #checks if the hours and minutes are 1 for grammer corrections if int(hours) == 1: hour = "hour" else: hour = "hours" if int(mins) == 1: min = "minute" else: min = "minutes" #formats the string in the desired way formated_date = "%d %s %s year %d %s %d %s" % (int(day), month , year, int(hours),hour, int(mins),min) return formated_date if __name__ == '__main__': print("Example:") print(date_time('01.01.2000 00:00')) #These "asserts" using only for self-checking and not necessary for auto-testing assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium" assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory" assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born" print("Coding complete? Click 'Check' to earn cool rewards!")
true
ce00d92310bf025cf06dba8ba460f6a711855649
Peter2220/Python
/Simple_Calculator.py
426
4.34375
4
##Basic Calculator ## ##Num_1 = input("Enter a number: ") ##Num_2 = input("Enter another number: ") ## ##result= Num_1 + Num_2 ##print(result) ## Python automatically converts anything in the input function into a String ## So you must do the following Num_1 = input("Enter a number: ") Num_2 = input("Enter another number: ") result= float(Num_1) + int(Num_2) print(result) ## The output will be float
true