blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
128c8d0f0abc7836dea6c071ffe329bcae2dfcb3
oldomario/CursoEmVideoPython
/desafio25.py
221
4.125
4
""" Faça um programa que leia o nome completo de uma pessoa e diga se ela tem Silva no nome """ nome = str(input('Digite seu nome completo: ')).strip() print('O seu nome possui Silva? {}'.format('SILVA' in nome.upper()))
false
bd6139b20c0e49f38719f9e209e2e14c1bd5716c
Tanuj-tj/Python
/HangMan_Game/main.py
1,408
4.15625
4
import random import hangman_words import hangman_art # Hangman Shapes imported from hangman_art.py file stages = hangman_art.stages # Word List imported from hangman_words.py file word_list = hangman_words.word_list # Hangman Logo imported from hangman_art.py file print(hangman_art.logo) choose_word = random.choice(word_list) # Testing #print(f'Choosen word in {choose_word}') # Some Hint print(f"HINT :\n No. of letters are {len(choose_word)} and 1st letter is {choose_word[0]}\n") list_of_words = [] for _ in range(len(choose_word)): list_of_words += "_" lives = 6 end_of_game = False while not end_of_game: guess = input('Choose a letter \n').lower() if guess in list_of_words: print(f"You've already guessed {guess}, Try another letter :)\n") for position in range(len(choose_word)): letter = choose_word[position] if (letter == guess): list_of_words[position] = letter if guess not in choose_word: print(f'{guess} is not in the choosen word, You loose a life :(:(') lives -= 1 print(f"Life Remaining: {lives}") if lives == 0: end_of_game = True print("you loose :(") print(f"{' '.join(list_of_words)}") if '_' not in list_of_words: end_of_game = True print("You Win :)") print(stages[lives])
true
8b1f577c22b9a9587ab9053dc64b06d09af8042e
wenxuefeng3930/python_practice
/interview/program/program_str/test_include_char2.py
861
4.15625
4
#!/usr/bin/env python # encoding: utf-8 """ @author: cbr """ def is_all_char_included(l1, l2): l1 = sorted(l1) l2 = sorted(l2) a = 0 for b in range(0, len(l2)): while (a < len(l1)) and l1[a] < l2[b]: # 注意这两个表达式的顺序 a += 1 if a >= len(l1) or l1[a] > l2[b]: return False return True def is_all_char_included_solution2(s1, s2): # force search for b in range(0, len(s2)): is_char_find = False for a in range(0, len(s1)): if s2[b] == s1[a]: is_char_find = True break if not is_char_find: return False return True if __name__ == '__main__': test_1 = "abcd" test_2 = "aaae" print(is_all_char_included(test_1, test_2)) print(is_all_char_included_solution2(test_1, test_2))
true
3f7dd821dbea3727b7d4a9585b05815d3fe1cfc7
leonardef/py_exercises
/q2.py
424
4.21875
4
# Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: 8 # Then, the output should be:40320 n = 8 i = 1 fat = 1 while i <= n: fat = fat * i i = i + 1 print(fat) # n = int(input('Log: ')) # fat = 1 # for i in range(1, n + 1): # fat = fat * i # print(fat)
true
9ba984176696d7740c37b350c3dc49da3f737641
JohnJTrump/Python_Projects
/polymorphism.py
1,577
4.375
4
# # # Python: 3.9 # # Author: John Trump # # # Purpose: Create two clases that inherit from another class # 1. Each child will have two attributes # 2. Parent will have one method # 3. Both children will use polymorphism of parent # class Fruit: # Define the attribute of the class name = "No Name Provided" origin = "No Region Provided" ripe_color = "Color" #Define the methods of the class def Info(self):#"self" is the key to the Fruit class, def is its method msg = "\nName: {}\nCentrally located: {}\nColor when ripe: {}".format(self.name,self.origin,self.ripe_color) return msg #child classes of user below (Kiwi and Mango) #inherited all properties from Fruit and added their own properties(attributes) class Kiwi(Fruit): price = 5.00 taste = 'sweet and sour' #Define the methods of the class def Info(self): msg = "\nName: {}\nCentrally located: {}\nColor when ripe: {}\nPrice: {}\nHow it tastes: {}".format(Fruit.name,Fruit.origin,Fruit.ripe_color,self.price,self.taste) return msg class Mango(Fruit): messy = 'yes' delicious = True #Define the methods of the class def Info(Fruit,Self): msg = "\nName: {}\nCentrally located: {}\nColor when ripe: {}\nIs messy?: {}\nIs delicious?: {}".format(Fruit.name,Fruit.origin,Fruit.ripe_color,self.messy,self.delicious) return msg #Invokes the methods inside class Kiwi Mango if __name__ == "__main__": Kiwi = Kiwi() print(Kiwi.Info())
true
c5991d1c4015f0fa4a20c567b14f364155aeb750
VivekJadeja/CBCode
/0. Crash Course/StringCrashCourse.py
1,015
4.375
4
a = [[]] * 3 # "a" actually just has one inner list but referenced 3 times print(a) a[0].append("value") print(a) n = [[] for _ in range (3)] n[0].append("value") print(n) a = [1] print(a) n = a print(n) n[0] = 2 print(n) random_list = ["Joe", "Steve", "Ann", "Bnn"] sorted_list = sorted(random_list) # [1,2,3,4,5] print(sorted_list) reverse_list = sorted(random_list, reverse = True) # [5,4,3,2,1] print(reverse_list) # One can also sort lists with a custom key using lambda. class Person: def __init__(self, name, age): self.age = age self.name = name # Provides a string representation of this object. def __repr__(self): return repr((self.name, self.age)) bob = Person("Bob", 14) sam = Person("Sam", 12) ann = Person("Ann", 16) people = [bob, sam, ann] print(people) # Sort it by their first name. people.sort(key=lambda x: x.name) # [("Ann", 16), ("Bob", 14), ("Sam", 12)] print(people) people.sort(key=lambda x: x.age) # [("Sam", 12), ("Bob", 14), ("Ann", 16)] print(people)
true
adc13f7ee53e97f8860fe77e35052b634ad9b7b7
FireAndYce/99proj
/pi.py
308
4.125
4
### Pi to the Nth digit import math while True: try: i = int(input("How many digits of pi would you like to see?")) except ValueError: print("that is not an integer") continue else: break print(str(math.pi)[0:(i+2)])
true
880e77500423299024072387afeec6eee528b17f
CatherineTrevor/api-practice
/api.py
2,267
4.1875
4
#Currency Converter - www.101computing.net/currency-converter/ import json, urllib.request #Request an API Key from https://free.currencyconverterapi.com/free-api-key API_Key = "api_key" #When requesting an API key, you will also be asked to verify your email. Please do so by following the instructions on the email you will receive. if API_Key[0:6]=="Insert": print("You will not be able to run this code without a valid API Key. Please request an API key first and insert it on line 5 of this code.") else: #See full lists of valid currencies on https://free.currencyconverterapi.com/api/v7/currencies validCurrencies = ["EUR","GBP","USD","JPY"] #Display banner print("$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€") print("$£¥€ $£¥€") print("$£¥€ Currency Converter $£¥€") print("$£¥€ $£¥€") print("$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€$£¥€") print("") print("List of currencies: ") print(" GBP - British Pound £") print(" JPY - Japanese Yen ¥") print(" EUR - Euro €") print(" USD - US Dollar $") print("") #Initialise key variables currencyFrom = "" currencyTo = "" amount = 0 #Retrieve user inputs while not currencyFrom in validCurrencies: currencyFrom = input("Enter Currency to convert From: (e.g. GBP)").upper() while not currencyTo in validCurrencies: currencyTo = input("Enter Currency to convert To: (e.g. EUR)").upper() amount = float(input("Enter amount to convert: (e.g. 10.00)")) #A JSON request to retrieve the required exchange rate url = "https://free.currconv.com/api/v7/convert?apiKey=" + API_Key + "&q="+currencyFrom + "_" + currencyTo +"&compact=y" response = urllib.request.urlopen(url) result = json.loads(response.read()) #Let's extract the required information exchangeRate=result[currencyFrom + "_" + currencyTo] rate = exchangeRate["val"] #Output exchange rate and converted amount print("") print("Exchange rate: 1 " + currencyFrom + " = " + str(rate) + " " + currencyTo) print(str(amount) + " " + currencyFrom + " = " + ("{0:.2f}".format(amount*rate)) + " " + currencyTo)
true
3e39c4b6be9ca04215a01e46e3a85c60b636dea0
benhall847/Python-Exercises
/tipCalculator.py
970
4.125
4
def tipCalculator(): start = True try: bill = float(input("Total bill? : ")) except: print("Invalid input! Try again.") return tipCalculator() while start: service = str(input("Was the service good, fair, or bad? : ")).lower() if service == 'good': tip = float(bill) * .2 start = False elif service == 'fair': tip = float(bill) * .15 start = False elif service == 'bad': tip = float(bill) * .1 start = False else: print("Invalid input!") start = True while start: try: split = int(input("Split how many ways? : ")) start = False except: print("Invalid input!") total = bill + tip per_person = (total + tip) / split print("Tip amount : $%.2f\nTotal amount : $%.2f\nAmount per person : $%.2f" % (tip, total, per_person)) tipCalculator()
true
7d680556b70c6b1e7090424d2af0f642d54067b9
bertohzapata/curso_python_uptap
/10-Tuplas/tuplas.py
501
4.28125
4
# Conocidas como arreglos o vectores tupla = (5, "UNO", True, False, 5, [1,2,3]) # print(tupla.index(5)) # print(tupla.index(5,2,-1)) # print(tupla[0]) # tupla.append() // ERROR # tupla.insert() # tupla.pop() # tupla.remove() # for elemento in tupla: # print(elemento) # for i in range(len(tupla)): # print(f'{i+1}-{tupla[i]}') # if i == 5: # lista = tupla[i] # for elemento in lista: # print(elemento) # tupla = (1,2,3,4,5,6,7,8,9,10) # print(max(tupla))
false
0390efcfd7c3cd5db43c25191c005382f261d780
guipw2/python_exercicios
/ex035.py
380
4.125
4
print(15 * '-=-') print('Analizador de Triângulos') print(15 * '-=-') r1 = float(input('Primeiro seguimento:')) r2 = float(input('Segundo seguimento:')) r3 = float(input('Terceiro seguimento')) if r1 < r2 +r3 and r2 < r1 + r3 and r3 < r1 + r2: print('Os seguimentos acima PODEM FORMAR um triângulo!') else: print('Os seguimentos acima NÃO PODEM FORMAR um triângulo!')
false
b6a120014bda4e55128520f3fe7ce55965f34096
minikin/dsa
/Algorithmic Toolbox/Week 4/Final/Python/edit_distance.py
1,189
4.21875
4
# Uses python3 def edit_distance(s, t): """Edit distance between two strings. The edit distance between two strings is the minimum number of insertions, deletions, and mismatches in an alignment of two strings. Samples: >>> edit_distance("ab", "ab") 0 >>> edit_distance("short", "ports") 3 >>> # Explanation: s h o r t − >>> # − p o r t s >>> edit_distance("editing", "distance") 5 >>> # Explanation: e d i − t i n g − >>> # − d i s t a n c e """ len_s = len(s) + 1 len_t = len(t) + 1 # Create a distance matrix and write in initial values. d = [[x] + [0] * (len_t - 1) for x in range(len_s)] d[0] = [x for x in range(len_t)] for i in range(1, len_s): for j in range(1, len_t): # Levenshtein distance calculation. if s[i - 1] == t[j - 1]: d[i][j] = d[i - 1][j - 1] else: d[i][j] = min(d[i][j - 1], d[i - 1][j], d[i - 1][j - 1]) + 1 # The last element of the matrix is edit distance metric. return d[-1][-1] if __name__ == "__main__": print(edit_distance(input(), input()))
false
93c146237da216bb360cc1677df62c0139696030
iamneha/LearningPython
/ex19.py
556
4.1875
4
#!/usr/bin/env python def add(a, b): print "ADDING %d + %d " % (a, b) return a + b def sub(a, b): print "SUBTRACT %d + %d" % (a, b) return a - b def mul(a, b): print "Multiply %d * %d" % (a, b) return a * b def div(a, b): print "DIVIDE %f / %f" % (a, b) return a / b age = add(30, 5) height = sub(78, 4) weight = mul(90, 2) iq = div(100, 2) print "Age: %d, Height: %d, weight: %d, IQ: %f" % (age, height, weight, iq) print "Here is puzzle" what = add(age, sub(height, mul(weight, div(iq, 2)))) print "That becomes:", what, "can you do it by hand"
false
066b4961fec27beafd8f60a65f21a8022ed28fd7
digitalgroovy/py-loops
/nested_ex_2.py
263
4.1875
4
x = float (input('Enter a number for x: ')) y = float (input('Enter a number for y: ')) if x == y: print ('x and y are equal') if y != 0: print ('therefore, x/y is', x/y) elif x < y: print ('x is smaller') else: print ('y is smaller') print ("Thanks")
true
88af69ab5bfa3bbc56cc2e9f228db0c9b74eeec4
jaxtonw/Sp21-Julia-Demonstration
/src/bisection.py
1,733
4.15625
4
import math # Constants PI = math.pi def absErr(value, valueApprox): ''' The following code will compute the absolute error between value and valueApprox ''' val = value - valueApprox return abs(val) def bisectionMethod(function, lowerbound, upperbound, maxIter=100, tol=10e-10, returnIter=False): if upperbound < lowerbound: temp = upperbound upperbound = lowerbound lowerbound = temp lb = function(lowerbound) ub = function(upperbound) if not (lb * ub < 0): return None iter = 0 error = 1 midpoint = 0 while tol < error and iter < maxIter: midpoint = (lowerbound + upperbound) / 2 mp = function(midpoint) iter += 1 if mp * ub < 0: lowerbound = midpoint error = absErr(lowerbound, upperbound) elif mp * lb < 0: upperbound = midpoint error = absErr(lowerbound, upperbound) else: if returnIter: return midpoint, iter return midpoint if returnIter: return midpoint, iter return midpoint if __name__ == "__main__": # Demonstrates what Bisection method can do # Using some identities, this is equivelant to xcosh(x) + x^3 - \pi = 0 def func(x): return (((x * math.exp(x)) + (x * math.exp(-x))) / 2) + pow(x, 3) - PI import time start = time.time() num = bisectionMethod(func, 0, 2) print(f"Elapsed time: {time.time() - start} seconds") print("When given the function, xcosh(x) + x^3 - \pi = 0, and the first guess of a lowerbound = 0 and upperbound = 2,\n" "the bisection method produced the approximation for the root to be: " + str(num))
true
c708ad0b9f524bc757ac205bd9b4e7233011f76a
saurbhc/k-nearest_neighbors_algorithm
/calculate_k_nearest_neighbors.py
2,710
4.21875
4
import pandas as pd from calculate_euclidean_distance import EuclideanDistance def get_input(): help_text = """ Find Euclidean Distance between multiple n-dimension cartesian-coordinate(s) with given same-dimension cartesian-coordinate (note) Send your suggestion on Saurabh.Chopra.2021@live.rhul.ac.uk for any suggestions. """ print(help_text) from_vector = input( f"!Enter comma-seperated-without-spaces values your `test-coordinate` vector/cartesian-coordinate (Example: 1,2,3): " ) number_of_vectors = int(input( f"How many coordinates would you like to compute the distance with your test-coordinate with? (Example: 3): ")) euclidean_distance_df = pd.DataFrame() to_vector = None for vector_number in range(number_of_vectors): counter = vector_number + 1 vector_or_cartesian_coordinate = input( f"!Enter comma-seperated-without-spaces values your `{counter}` vector/cartesian-coordinate (Example: 1,2,3-label): " ) if not from_vector: from_vector = vector_or_cartesian_coordinate else: to_vector = vector_or_cartesian_coordinate ed = EuclideanDistance(_from_vector=from_vector, _to_vector=to_vector) ed_df = ed.execute() if euclidean_distance_df.empty: euclidean_distance_df = ed_df else: euclidean_distance_df = euclidean_distance_df.append(ed_df) print(f""" >> Euclidean Distance Table: {euclidean_distance_df.to_string()} """) _k_in_knn_value = int(input( f"Which `k`-nearest-neighbor Algorithm would you like to Apply: " )) return _k_in_knn_value, number_of_vectors, from_vector, to_vector, euclidean_distance_df def most_common(lst): return max(set(lst), key=lst.count) class KNearestNeighborsAlgorithm: def __init__(self, _k_in_knn_value, _euclidean_distance_df): self.euclidean_distance_df = _euclidean_distance_df self.k_in_knn_value = _k_in_knn_value def execute(self): return self.euclidean_distance_df.sort_values('EuclideanDistance') if __name__ == "__main__": k_in_knn_value, number_of_vectors, from_vector, to_vector, euclidean_distance_df = get_input() knn_obj = KNearestNeighborsAlgorithm(_k_in_knn_value=k_in_knn_value, _euclidean_distance_df=euclidean_distance_df) knn_distance = knn_obj.execute() print(f""" >> {k_in_knn_value}-Nearest-Neighbour Distance Table: {knn_distance.head(k_in_knn_value)} """) print(f""" >> {k_in_knn_value}-Nearest-Neighbours are: {knn_distance.head(k_in_knn_value).Label.tolist()} >> Most Common Label is: {most_common(knn_distance.head(k_in_knn_value).Label.tolist())} """)
true
8ae04d18ade6242e8a7a13a77559dbc6276c5c73
saad-abu-sami/Learn-Python-Programming
/basic learning py/string_0.py
1,257
4.21875
4
a = ' data science ' print(a[1]) #strings in Python are arrays of bytes representing unicode characters. print(a[2:5]) #font 0,1=d,a then t,a,space print(a[-7:-4]) #from end e,c,n,e, -4 then sci -7 print(len(a)) print(a.strip()) #no space on terminal [data science].The strip() method removes any whitespace from the beginning or the end print(a.upper()) #all capital letter print(a.lower()) #all small letter print(a.replace(' data','Python string')) #to replace the word data print(a.split()) #to divide a pherese or sentense to all word b= 'a am a student' print(b.split()) print('My favourite topic is %s' %a) #1 way to print strng print('My favourite topic is',a) #2 way to print strng print('My favourite topic is %s' %(a)) #3 way to print strng m = input() n = input() #input string can e declared print('My favourite language are: ',m, 'and',n ) #1 way to declare number = 234.497462590 print('%.4f' %number) message_double_cote = """ Hi John, This is SAMI from PSTU Blah blah blah """ print(message_double_cote) #multi line type messege with double qutetion message_single_cote = ''' Hi John, This is SAMI from PSTU Blah blah blah ''' print(message_single_cote) #multi line type messege with single qutetion
true
476af194a68f4acf371a0ff19460e7f72bf0bfa8
grayjac/Test_Project
/cylinder.py
328
4.25
4
#!/usr/bin/env python # ME499-S20 Python Lab 0 Problem 2 # Programmer: Jacob Gray # Last Edit: 4/1/2020 from math import pi # Import pi from math library # Calculating the volume of a cylinder with radius r, height h r = 3 # Radius of cylinder h = 5 # Height of cylinder print((pi * r ** 2) * h) # Print volume of cylinder
true
7d8b892679697a903b2d4b34b081526f8b558d61
marturoch/Fundamentos-Informatica
/Pandas/Practica 8 - pandas/8.py
497
4.15625
4
#Ejercicio 8 #Realizá un programa que dado dos DataFrames genere otro # que contenga solo las columnas en común. import pandas as pd df1 = pd.DataFrame({1: ["a", "b", "c"], 2: ["d","e","f"]}) df2 = pd.DataFrame({0: [1, 2, 3], 1:[4,5,6], 2:[7,8,9]}) result = pd.concat([df1,df2], join="inner", ignore_index=True) print(df1) # 1 2 #0 a d #1 b e #2 c f print(df2) # 0 1 2 #0 1 4 7 #1 2 5 8 #2 3 6 9 print(result) # 1 2 #0 a d #1 b e #2 c f #3 4 7 #4 5 8 #5 6 9
false
698cdca3cc24fda8fab0d402054988b7e5cfd4fa
marturoch/Fundamentos-Informatica
/Expresiones regulares/Practica 3 - expesiones regulares/2.py
568
4.125
4
#2. Escribí un programa que verifique si un string tiene todos sus caracteres permitidos. Estos caracteres son a-z, A-Z y 0-9. import re def caracteres_permitidos(string): return not bool(re.search('[^a-zA-Z0-9]',string)) #Si alguno de los caracteres del string no cumple con esta condicion, esto me da verdadero print("el string" , "ABCDEFabcdef123450", "tienen todos los caracteres permitidos?") print(caracteres_permitidos("ABCDEFabcdef123450")) print("el string", "*&@#!}{", "tiene todos los caracteres permitidos?") print (caracteres_permitidos("*&@#!}{"))
false
c1299ae18682329ff5f07f9078b90927eef7d230
marturoch/Fundamentos-Informatica
/Pandas/Practica 8 - pandas/2.py
603
4.25
4
#Ejercicio 2 #Escribí un programa que guarde en una lista una columna # de un DataFrame. #Forma 1 import pandas as pd df = pd.DataFrame({1: [1, 4, 3, 4, 5], 2: [4, 5, 6, 7, 8], 3: [7, 8, 9, 0, 1]}) def columna(df, columna): for i in df.columns: if i == columna: print("columna " + str(i) + ":" + str(df[i].to_list())) columna(df,1) #Devuelve: #columna 1:[1, 4, 3, 4, 5] #forma 2 def columnas(df, columna): for i in df.columns: if i == columna: print("columna " + str(i) + ":" + str(df[i].tolist())) columnas(df,2) #Devuelve: # columna 2:[4, 5, 6, 7, 8]
false
3271292dc297f49f56840ba11b21f19b3339986e
7blink/ProjectEuler
/Euler009.py
566
4.3125
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import math def compute(): max = 1000 #create a loop within a loop within a loop to run every combination of a,b,c for b in range(1,max): for a in range(1,b): c = max - a - b if (a**2) + (b**2) == (c**2): return a*b*c if __name__ == "__main__": print(compute())
true
3f3c8f8d8abf68ace5139f9b0b8371bcde099ada
pieper-chris/practice
/Fundamentals/Searching/searching.py
1,569
4.25
4
# Basic search algorithms and their complexities # Linear search (ints) # pass in the element (int) to be found and an int list to search in (can be unsorted) # returns index of 1st-found element to match 'elt', returns -1 if DNE def linear_search(elt, lst): idx = 0 lst_size = len(lst) while((idx<lst_size) and (elt != lst[idx])): idx += 1 if (idx < lst_size): return idx else: return -1 # binary search (ints) # pass in the element (int) to be found and an int list to search in (must be unsorted) # returns index of 1st-found element to match 'elt', returns -1 if DNE def binary_search(elt, lst): lst_size = len(lst) l = 0 # left endpoint r = (lst_size - 1) # right endpoint while(l < r): midpoint = (l+r)//2 # need to specify floor division // in python3 if(elt > lst[midpoint]): l = midpoint + 1 else: r = midpoint if (elt == lst[l]): return l else: return -1 '''Example scripts for linear_search() below - uncomment to run''' # should return -1 # print(linear_search(5, [3,6,6,4,3,2,4,6])) # should return 2 ("third index", as 1st index is 0) # print(linear_search(5, [3,6,5,4,3,2,4,6])) '''Example scripts for binary_search() below - uncomment to run (Uses python3 sorted() function for passed parameters)''' # Note: python uses timesort (https://en.wikipedia.org/wiki/Timsort) # should return -1 # print(binary_search(5, sorted([3,6,6,4,3,2,4,6]))) # should return 5 ("6th index", as 1st index is 0) # print(binary_search(5, sorted([3,6,5,4,3,2,4,6])))
true
0ce9995df1dd11cb6b2beefae5eb06950f81eb71
Harishsowmy/python_learning
/home_1/homework3.py
434
4.15625
4
num_1=int(input("enter number 1: ")) num_2=int(input("enter number 2: ")) num_3=int(input("enter number 3: ")) num_4=int(input("enter number 4: ")) add=num_1+num_2 subtract=add-num_3 multiply=subtract*num_4 divide=float(multiply)/num_3 print("add: {add}".format(add=add)) print("subtract : {subtract}".format(subtract=subtract)) print("multiply :{multiply}".format(multiply=multiply)) print("divide: {divide}".format(divide=divide))
false
9b1883649a41d3e3bc67d4bf35bd0be1874e4521
quincoces23/Exercicios-Python
/Estrutura Sequencial/09FahrenCelsius.py
452
4.3125
4
# Faça um Programa que peça a temperatura em graus Fahrenheit, # transforme e mostre a temperatura em graus Celsius. temperatura_fahrenheit = float(input('Qual a temperatura em' ' Fahrenheit que deseja converter para ' 'graus Celsius? ').replace(' ', '')) print(f'{temperatura_fahrenheit} Fahrenheit em graus Celsius fica' f' {(temperatura_fahrenheit - 32)*(5/9):.2f}')
false
0f1d674a1e08bde99451aa919f2cbbb5a31d2c97
haoyuF996/AL-cs-homework-June-17-Monday-2019
/word count.py
2,273
4.15625
4
def extract_words_from_file(filename): '''Extract all words(split by space) in a .txt file and return a list of the words''' file = open(filename,'r') file_content = file.read() file.close() words = file_content.split() return words def find_element_binary(alist,item): '''Binary search to check whether an element is in a list''' if len(alist)<=1: return False elif alist[len(alist)//2] == item: return True elif alist[len(alist)//2] < item: return find_element_binary(alist[len(alist)//2:],item) else: return find_element_binary(alist[:len(alist)//2],item) def texts_to_words(text_list): '''Transfer all text into words(lowercased) and return a list with all the words''' words = [] for i in text_list: my_substitutions = i.maketrans( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\", "abcdefghijklmnopqrstuvwxyz ") cleaned_text = i.translate(my_substitutions) wds = cleaned_text.split() words += wds return words def uniquelize(alist): '''Return a list contain all the elements but with same elements''' alist = ' '.join(alist).split() alist = list(set(alist)) return alist def word_not_in_count(file,vocab): '''Find the number of words that are in file but not in vocab''' words = uniquelize(texts_to_words(extract_words_from_file(file))) words_not_in = [] vocab_list = extract_words_from_file(vocab) for i in words: if not find_element_binary(vocab_list,i): words_not_in.append(i) return len(words_not_in) if __name__ == '__main__': import time time_start = time.time() file = r'AL-cs-homework-June-17-Monday-2019-master\ALice in Wondeland.txt' vocab = r'AL-cs-homework-June-17-Monday-2019-master\Vocabulary1.txt' print(f'There are {len(texts_to_words(extract_words_from_file(file)))} words in Alice in Wonderland, only {len(uniquelize(texts_to_words(extract_words_from_file(file))))} words are unique.') print(f'There are {word_not_in_count(file,vocab)} not in vocabulary') print(f'It takes {round(time.time()-time_start,3)}s')
true
9deb690821b549cf6b02e82f603299dea1c68cee
ashishk123cliste/Text_to_speech
/Text_to_speech.py
2,644
4.15625
4
#03/02/2021 #wednesday #Following 3 modules you have to import in your system. from tkinter import * from gtts import gTTS from playsound import playsound window = Tk() #above line initiate the window. #window is the name of the window created in this project. #further all the happpening goingto occur in the window can only be accessed by it only. window.geometry("500x500") #above line set the dimensions of the window. window .configure(bg='ghost white') #above line make the window configurable and allow us to set the background color. window.title('project - Text to speech') #above line set the title of the window. Label(window, text = "TEXT_TO_SPEECH", font = "arial 20 bold", bg='white smoke').pack() #Label() widget is used to display one or more than one line of text that users can’t able to modify #window is the name which we refer to our window #text = which we display on the label. #font = in which the text is written. #pack = organize widget in block. Label(text ="project - Text to speech", font = 'arial 15 bold', bg ='white smoke' , width = '20').pack(side = 'bottom') Msg = StringVar() #Msg is a string type variable Label(window,text ="Enter Text", font = 'arial 15 bold', bg ='white smoke').place(x=20,y=60) entry_field = Entry(window, textvariable = Msg ,width ='50') #Entry() = it used to create an input text field. #textvariable = it is used to retrieve the current text to entry widget entry_field.place(x=20,y=100) #above line set's the dimension of the entry field. def Text_to_speech(): Message = entry_field.get() #above line will take the message from the entry field. speech = gTTS(text = Message) #text is the sentences or text to be read. speech.save('text.mp3') #speech.save(‘DataFlair.mp3’) will saves the converted file as DataFlair as mp3 file playsound('text.mp3') #playsound() used to play the sound def Exit(): window.destroy() #root.destroy() will quit the program by stopping the mainloop(). def Reset(): Msg.set("") #Reset function set Msg variable to empty strings. Button(window, text = "PLAY", font = 'arial 15 bold' , command = Text_to_speech ,width = '4').place(x=25,y=140) Button(window, font = 'arial 15 bold',text = 'EXIT', width = '4' , command = Exit, bg = 'OrangeRed1').place(x=100 , y = 140) Button(window, font = 'arial 15 bold',text = 'RESET', width = '6' , command = Reset).place(x=175 , y = 140) #Button() widget used to display button on the window window.mainloop() #window.mainloop() is a method that executes when we want to run our program.
true
110f309d33ed5130eaf1cae1d0d64885c3bffb39
CannonStealth/Notes
/Python/control-flow/if_statements.py
869
4.28125
4
# if it isn't raining I will go to the beach """ if True: print("oo") """ if 5 > 3: print("It is") # Let's use english and or not if 5 > 3 and 4 > 2: print("uwu") # uwu if 5 > 3 and 4 < 2: print("owo") # if 5 > 3 or 4 > 2: print("awa") # uwu if 5 > 3 or 4 < 2: print("ewe") # ewe credits = 120 gpa = 1.8 if not credits >= 120: print("You do not have enough credits to graduate.") if not gpa >= 2.0: print("Your GPA is not high enough to graduate.") if not (credits >= 120) and not (gpa >= 2.0): print("You do not meet either requirement to graduate!") # now let's see else if 5 < 3: print("It is") else: # placement matters and a lot print("It isn't") # elif = elseif if 5 < 3: print("5 > 3 is True") elif 4 > 2: print("5 > 3 is False but 4 > 2 is True") else: print("5 > 3 is False and 4 > 2 is False too")
false
329cb31ee6423a0c2a5f20577381d51739f0b831
CannonStealth/Notes
/Python/start/operators.py
1,803
4.625
5
#There are different types of operators print (10 + 8) #Sum print (10 - 8) #Substraction print (10 * 8) #Multiplication print (10 / 8) #Division print (10 % 5) #Modulus print (10 ** 5) #Exponentation print (10 // 8) #Floor divisions """ == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 "and" Returns True if both statements are true x < 5 and x < 10 "or" Returns True if one of the statements is true x < 5 or x < 4 "not" Reverse the result, returns False if the result is true not(x < 5 and x < 10) "is" Returns True if both variables are the same object x is y "is not" - compound operator of "is" and "not" Returns True if both variables are not the same object x is not y "in" Returns True if a sequence with the specified value is present in the object x in y "not in" - compound operator of "not" and "in" Returns True if a sequence with the specified value is not present in the object x not in y & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off """
true
b8d9a96f3a3c15e81486e3d370ef16a746d964b3
CannonStealth/Notes
/Python/loops/break.py
303
4.28125
4
# we use break to stop a loop for item in ["balloons", "flowers", "sugar", "watermelons"]: if item != "sugar": print("We want sugar not " + item) else: print("Found the sugar") break # Output: """ We want sugar not balloons We want sugar not flowers Found the sugar """
true
45d2b0f7c5d741a5829d4885d9b214380da2b945
Daniel-Benson-Poe/Intro-Python-I
/src/02_datatypes.py
836
4.5
4
""" Python is a strongly-typed language under the hood, which means that the types of values matter, especially when we're trying to perform operations on them. Note that if you try running the following code without making any changes, you'll get a TypeError saying you can't perform an operation on a string and an integer. """ x = 5 y = "7" # Write a print statement that combines x + y into the integer value 12 def int_val(): print(x + int(y)) # Write a print statement that combines x + y into the string value 57 def string_val(): print(str(x) + y) def error_proof(): try: x + y except(TypeError): print( """You received a type error! You can't add a string and an integer together.""") if __name__ == "__main__": error_proof() int_val() string_val()
true
8d74ec5f1fad7bbdc02eb49747872d77fce4077c
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 01 - Basics/All answers.py
1,943
4.15625
4
#001 print name name = input("What is your name? ") print("Hello", name) #002 print first and last name firstname = input("What is your first name? ") surname = input("What is your surname? ") print("Hello", firstname, surname) #003 print joke using 1 line of code print("What do you call a bear with no teeth?\nA Gummy Bear!") #004 Add 2 numbers num1 = int(input("Please enter a number ")) num2 = int(input("Please enter another number ")) print("Sum of these 2 numbers is ", num1 + num2) #005 Add 2 then multiple num1 = int(input("Please enter a number ")) num2 = int(input("Please enter another number ")) num3 = int(input("Please enter a third number which the sum of the first 2 numbers will be multiplied by ")) print("(", num1, "+", num2, ")*", num3, "=", (num1+num2)*num3) #006 Pizza Slices slices = int(input("How many slices of pizza did you start with ")) eat = int(input("How many slices of pizza have you eaten ")) print("You have ", slices - eat, " left") #007 Next birthday age name = input("What is your name? ") age = int(input("How old are you? ")) print(name, "next birthday you will be ", age + 1) #008 Restaurant Bill price = int(input("What is the total value of the bill? ")) diners = int(input("How many diners are there? ")) print("Each person should pay ", price/diners, " towards the cost of the meal") #009 Days into hours, minutes and seconds days = int(input("How many days have there been? ")) hours = days/24 minutes = hours/60 seconds = minutes/60 print(days, "days is the same as ", hours, " hours or ", minutes, " minutes or ", seconds, " seconds.") #010 KG into pounds kilograms = int(input("How many kilograms? ")) pounds = kilograms/2204 print(kilograms, " is equivalent to ", pounds) #011 number under 10 in number over 100 small = int(input("Please enter a number under 10")) large = int(input("Please enter a number over 100")) print(small, "goes into ", large, " ", large//small, " times")
true
6a7b622bf3465e20f9dd6a9f24771eb83ad1e3cf
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 01 - Basics/008 Restaurant bill.py
212
4.21875
4
#008 Restaurant Bill price = int(input("What is the total value of the bill? ")) diners = int(input("How many diners are there? ")) print("Each person should pay ", price/diners, " towards the cost of the meal")
true
1d38b65285304de02dc281d027cc7ab2bd052fb3
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 09 - Tuples, Lists and Dictionaries/079 List of numbers.py
498
4.125
4
#079 List of numbers nums = [] for i in range(0,3): nums.append(int(input("Please enter a number to add to the list: "))) print(nums) while input("Would you like to add another number to the list? Yes/No: ").lower() != "no": nums.append(int(input("Please enter a number to add to the list: "))) print(nums) if input("Are you sure you want to add this number to the list? Yes/No: ").lower() == "no": del nums[len(nums) - 1] print(nums) for i in nums: print(i)
true
235cf883da3dd773918be64db29e2f79d77a50d9
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 03 - Strings/023 print section of string.py
383
4.125
4
#023 Print section of string rhyme = input("Please enter the first line of a nursery rhyme: ") rhymeLength = len(rhyme) print("You've entered", rhymeLength, "characters") num1 = int(input("Please enter a number that is less than " + str(rhymeLength) + ": ")) num2 = int(input("Please enter a number between " + str(num1) + " and "+ str(rhymeLength) + ": ")) print(rhyme[num1:num2])
true
51442e7366f8a3e71b1983cd41b609ad5593f26e
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 05 - For loops/038 Display each letter on separate line, repeat X times.py
253
4.125
4
#038 Display each letter on separate line, repeat X times name = input("What is your name? ") num = int(input("How many times shall I display the name? ")) for i in range(0, num): for k in range(0, len(name)): print(name[k])
true
f04d883ba448c0ea982274317babf3a93fda6cf7
Natalia-oli/praticas-turma-VamoAI
/media-notas.py
287
4.125
4
nota1 = float(input(" Digite sua nota de matematica:")) nota2 = float(input(" Digite sua nota de portugues:")) nota3 = float(input(" Digite sua nota de ingles:")) media = ((nota1 + nota2 + nota3) / 3) if media >= 6: print("Voce esta aprovado :)") else: print ("Reprovado :/")
false
233d21b66d4870ee3ed065fd9a69a0c40ac0be42
gerrycfchang/leetcode-python
/tree/level/largest_value_in_tree_row.py
1,446
4.21875
4
# 515. Find Largest Value in Each Tree Row # # You need to find the largest value in each row of a binary tree. # # Example: # Input: # # 1 # / \ # 3 2 # / \ \ # 5 3 9 # # Output: [1, 3, 9] # Definition for a binary tree node. import collections class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def largestValues(self, root): """ :type root: TreeNode :rtype: List[int] """ dic, res = collections.defaultdict(list), [] def inorder(node, level, dic): if not node: return inorder(node.left, level+1, dic) dic[level].append(node.val) inorder(node.right, level+1, dic) inorder(root, 0, dic) for key in sorted(dic.keys()): res.append(max(dic[key])) return res if __name__ == '__main__': sol = Solution() """ # 1 # / \ # 3 2 # / \ \ # 5 3 9 """ root = TreeNode(1) node1 = TreeNode(3) node2 = TreeNode(2) node3 = TreeNode(5) node4 = TreeNode(3) node5 = TreeNode(9) root.left = node1 root.right = node2 node1.left = node3 node1.right = node4 node2.right = node5 assert (sol.largestValues(root) == [1, 3, 9])
true
585e8eba9850d99ff0dff2df5da7baa31a253625
gerrycfchang/leetcode-python
/sum/sum_of_two_integers.py
607
4.15625
4
""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ while b != 0: carry = ( a & b ) a = (a ^ b) % 0x100000000 b = (carry << 1) % 0x100000000 return a if a <= 0x7FFFFFFF else a | (~0x100000000+1) if __name__ == '__main__': sol = Solution() assert sol.getSum(1, 2) == 3 assert sol.getSum(-1, 1) == 0
true
c40e914dabb1cff875817ba5d819831fdf862d6c
gerrycfchang/leetcode-python
/medium/rotate_image.py
1,050
4.1875
4
# 48. Rotate Image # # You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Note: # You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. # DO NOT allocate another 2D matrix and do the rotation. # # Example 1: # # Given input matrix = # [ # [1,2,3], # [4,5,6], # [7,8,9] # ], # # rotate the input matrix in-place such that it becomes: # [ # [7,4,1], # [8,5,2], # [9,6,3] # ] class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix[::] = [[matrix[row][col] for row in range(len(matrix)-1, -1, -1)] for col in range(len(matrix[0]))] if __name__ == '__main__': sol = Solution() matrix = [ [1,2,3], [4,5,6], [7,8,9] ] exp = [ [7,4,1], [8,5,2], [9,6,3] ] sol.rotate(matrix) assert matrix == exp
true
2fe371ea4c2ae4dfeba268e20d36d9b2ed8c30c7
gerrycfchang/leetcode-python
/easy/string_compression.py
2,168
4.15625
4
# 443. String Compression # # Given an array of characters, compress it in-place. # The length after compression must always be smaller than or equal to the original array. # Every element of the array should be a character (not int) of length 1. # After you are done modifying the input array in-place, return the new length of the array. # # Example 1: # Input: # ["a","a","b","b","c","c","c"] # # Output: # Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] # # Explanation: # "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". # Example 2: # Input: # ["a"] # # Output: # Return 1, and the first 1 characters of the input array should be: ["a"] # # Explanation: # Nothing is replaced. # Example 3: # Input: # ["a","b","b","b","b","b","b","b","b","b","b","b","b"] # # Output: # Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. # # Explanation: # Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". # Notice each digit has it's own entry in the array.# class Solution(object): def compress(self, chars): """ :type chars: List[str] :rtype: int """ i = 1 while i < len(chars): count = 1 while i < len(chars) and chars[i] == chars[i-1]: count += 1 del chars[i] if count > 1: for n in str(count): chars.insert(i, n) i += 1 if i < len(chars) and chars[i] == chars[i-1]: i += 1 else: i += 1 return (chars) if __name__ == '__main__': sol = Solution() assert sol.compress(["a","a","b","b","c","c","c"]) == ['a', '2', 'b', '2', 'c', '3'] assert sol.compress(["a"]) == ['a'] assert sol.compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"]) == ['a', 'b', '1', '2'] assert sol.compress(["a","a","a","b","b","a","a"]) == ['a', '3', 'b', '2', 'a', '2'] assert sol.compress(["a","a","2","2","2"]) == ['a', '2', '2', '3']
true
532f8b61ef92562c5bcad102076c46f3935b7a6a
gerrycfchang/leetcode-python
/tree/min_abs_diff_in_binarytree.py
1,679
4.1875
4
# 530. Minimum Absolute Difference in BST # # refer to 783. Minimum Distance Between BST Nodes # Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. # # Example: # # Input: # # 1 # \ # 3 # / # 2 # # Output: # 1 # # Explanation: # The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ Solution.mindiff = float('inf') Solution.prev = None def inorder(node): if not node: return inorder(node.left) if Solution.prev: Solution.mindiff = min(Solution.mindiff, abs(node.val - Solution.prev.val)) Solution.prev = node inorder(node.right) inorder(root) return Solution.mindiff if __name__ == '__main__': sol = Solution() """ # 1 # \ # 3 # / # 2 """ root = TreeNode(1) node1 = TreeNode(3) node2 = TreeNode(2) root.right = node1 node1.left = node2 assert (sol.getMinimumDifference(root) == 1) """ # 5 # / \ # 4 7 """ root = TreeNode(5) node1 = TreeNode(4) node2 = TreeNode(7) root.left = node1 root.right = node2 assert (sol.getMinimumDifference(root) == 1)
true
eb620786f5bd650b45825c5e4ed3d7b5575527bb
gerrycfchang/leetcode-python
/google/power_of_three.py
1,010
4.25
4
""" Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? """ ### log3n = log10n / log103 class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if n == 0: return False while n != 1 and n !=0 : if n % 3 == 0: n = n/3 else: return False if n == 1: return True def isPowerOfThreeSol(self, n): if n <= 0: return False import math a = math.log10(n)/math.log10(3) return int(a) - a == 0 if __name__ == '__main__': sol = Solution() assert sol.isPowerOfThree(0) == False assert sol.isPowerOfThree(3) == True assert sol.isPowerOfThreeSol(3) == True assert sol.isPowerOfThreeSol(5) == False assert sol.isPowerOfThreeSol(-5) == False assert sol.isPowerOfThreeSol(81) == True
true
88c69cc0c3920ebc3473af0749072efd9061977a
gotjon05/pythoncrashcourse_exercises
/ch_6/6.7.py
691
4.40625
4
person_1 = { 'first_name': 'bob', 'last_name': 'grunk', 'age': 43, 'city': 'Chicago' } #print(person['first_name'].title()) #items() retuns a liust of key-value pairs #for key, value in person.items(): # print(key + ": " + str(value)) #make two dictionaries of different people, store all three dictionaires in a list called people person_2 = { 'first_name': 'bobby', 'last_name': 'jorgan', 'age': 23, 'city': 'Chicago' } person_3 = { 'first_name': 'sally', 'last_name': 'wether', 'age': 43, 'city': 'Chicago' } people = [person_1, person_2, person_3] for person in people: print(person)
false
52196159f21828f217519b1e993f663ae0968532
gotjon05/pythoncrashcourse_exercises
/ch_6/6.11.py
600
4.4375
4
#dictionary called cities; create a dictionary of each city --> dictionary in a dictionary cities = { 'Atlanta': { 'country':'USA', 'population':'10000', 'fact': 'bloop', }, 'NYC':{ 'country':'USA', 'population':'10000', 'fact': 'bloop', }, 'Boston':{ 'country':'USA', 'population':'10000', 'fact': 'bloop', } } for city, city_info in cities.items(): print(city + " " + str(city_info)) print(city_info['country'])
false
2808c0f2504c5c21ac8fb6abe7d7fa3c1cb71dba
laviniaclare/Toy-Problems
/num_to_string.py
949
4.34375
4
"""Write a function, num_to_string, which takes in an integer and returns a string representation of that integer with ',' at the appropriate groupings to indicate thousands places. >>> num_to_string(1234) '1,234' >>> num_to_string(10) '10' >>> num_to_string(999999) '999,999' """ def num_to_string(num): output = '' # convert num to string num_string = str(num) counter = 0 # for digit in number string (loop from end, reverse direction) for digit in reversed(num_string): # if the number is a multiple of 3 from the end add comma if not counter % 3 and not counter == 0 and not digit == "-": output += ',' # always add the digit output += digit counter += 1 # return final number string return output[::-1] if __name__ == "__main__": print import doctest if doctest.testmod().failed == 0: print "*** ALL TESTS PASSED ***" print
true
b9003432db649f5f948d0366566b7e7f09da699f
alexandretea/dev-fundamentals
/sort/quicksort.py
1,090
4.21875
4
#!/usr/bin/env python # Author: Alexandre Tea <alexandre.qtea@gmail.com> # File: /Users/alexandretea/Work/concepts/sort/bubble_sort.py # Purpose: TODO (a one-line explanation) # Created: 2017-06-10 18:49:20 # Modified: 2017-06-11 12:21:32 import sys def partition(array, start, end): pivot = array[(start + end) / 2] while True: i = start j = end while array[i] < pivot: i += 1 while array[j] > pivot: j -= 1 if j <= i: return j else: array[i], array[j] = array[j], array[i] # swap def rec_quicksort(array, start, end): if end - start > 1: pivot_i = partition(array, start, end) rec_quicksort(array, start, pivot_i) rec_quicksort(array, pivot_i, end) def quicksort(array): rec_quicksort(array, 0, len(array) - 1) return array def main(): if len(sys.argv) < 2: print("Usage: " + sys.argv[0] + "v1 v2... vn") return sorted_array = quicksort(map(int, sys.argv[1:])) print(sorted_array) if __name__ == "__main__": main()
false
8a9cc6d7880b2803c12ea70bbefa5cdfc08640b6
vicsho997/NumpyPractice
/numpy_arrayDatatype.py
2,817
4.15625
4
import numpy as np """Data Types in Python strings - used to represent text data, the text is given under quote marks. eg. "ABCD" integer - used to represent integer numbers. eg. -1, -2, -3 float - used to represent real numbers. eg. 1.2, 42.42 boolean - used to represent True or False. complex - used to represent a number in complex plain. eg. 1.0 + 2.0j, 1.5 + 2.5j """ """Data Types in NumPy Below is a list of all data types in NumPy and the characters used to represent them. i - integer b - boolean u - unsigned integer f - float c - complex float m - timedelta M - datetime O - object S - string U - unicode string V - fixed chunk of memory for other type ( void ) """ """______Checking_____ the ____Data Type____ of an Array The NumPy array object has a property called dtype that returns the data type of the array: Get the data type of an array object """ #Get the data type of an array object: arr = np.array([1, 2, 3, 4]) print(arr.dtype) #Get the data type of an array containing strings: arr = np.array(['apple', 'banana', 'cherry']) print(arr.dtype) """Creating Arrays With a Defined Data Type """ #Create an array with data type string: arr = np.array([1, 2, 3, 4], dtype='S') print(arr) print(arr.dtype) #For i, u, f, S and U we can define size as well. #Create an array with data type 4 bytes integer: arr = np.array([1, 2, 3, 4], dtype='i4') print(arr) print(arr.dtype) """What if a Value Can Not Be Converted? If a type is given in which elements can't be casted then NumPy will raise a ValueError. ValueError: In Python ValueError is raised when the type of passed argument to a function is unexpected/incorrect. A non integer string like 'a' can not be converted to integer (will raise an error): """ arr = np.array(['1', '2', '3'], dtype='i') """Converting Data Type on Existing Arrays The best way to change the data type of an existing array, is to make a copy of the array with the astype() method. The astype() function creates a copy of the array, and allows you to specify the data type as a parameter. The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the data type directly like float for float and int for integer. """ """v1 """ #Change data type from float to integer by using 'i' as parameter value: arr = np.array([1.1, 2.1, 3.1]) newarr = arr.astype('i') print(newarr) print(newarr.dtype) """v2 """ #Change data type from float to integer by using int as parameter value: arr = np.array([1.1, 2.1, 3.1]) newarr = arr.astype(int) print(newarr) print(newarr.dtype) """v3 """ #Change data type from integer to boolean: arr = np.array([1, 0, 3]) newarr = arr.astype(bool) print(newarr) print(newarr.dtype)
true
24af815b1d1288521ffe0eab3afff314a4084785
vicsho997/NumpyPractice
/numpy_arraySearchingSorted.py
1,586
4.65625
5
import numpy as np """Searching Sorted Arrays There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order. The searchsorted() method is assumed to be used on sorted arrays. """ #Find the indexes where the value 7 should be inserted: arr = np.array([6, 7, 8, 9]) x = np.searchsorted(arr, 7) print(x) #Example explained: The number 7 should be inserted on index 1 to remain the sort order. #The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value. """Search From the Right Side """ #By default the left most index is returned, but we can give side='right' to return the right most index instead. #Find the indexes where the value 7 should be inserted, starting from the right: arr = np.array([6, 7, 8, 9]) x = np.searchsorted(arr, 7, side='right') print(x) #Example explained: The number 7 should be inserted on index 2 to remain the sort order. #The method starts the search from the right and returns the first index where the number 7 is no longer less than the next value. """Multiple Values""" #To search for more than one value, use an array with the specified values. #Find the indexes where the values 2, 4, and 6 should be inserted: arr = np.array([1, 3, 5, 7]) x = np.searchsorted(arr, [2, 4, 6]) print(x) #The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted in the original array to maintain the order.
true
c95fac35c392b4b6b07124916a0a0b1020c6adc9
Schachte/Python-Development-Projects
/functions_area_temperature_conversion_python.py
1,121
4.15625
4
#Compute area of a triangle def triangle_area(base, height): area = .5 * base * height return area base = raw_input("What is the base?") base = int(base) height = raw_input("What is the height?") height = int(height) a = triangle_area(base, height) print 'Area is ' + str(a) #Convert F to C #F = c * 9/5 + 32 #C = (f - 32) * 5/9 def c_to_f(value): f = value * (9.0/5.0) + 32 return f def f_to_c(value): c = (value - 32) * 5.0/9.0 return c user_conversion = raw_input("Would you like to convert Fahrenheit to Celcius or Celcius to Fahrenheit?") user_conversion = user_conversion[0].lower() print user_conversion if (user_conversion == 'f'): fahr = raw_input("Enter the degree in Fahrenheit: ") fahr = int(fahr) new_temp = f_to_c(fahr) print str(fahr) + " degrees Fahrenheit is the same as " + str(new_temp) + " degrees Celcius." elif (user_conversion == "c"): cels = raw_input("Enter the degree in Celcius: ") cels = int(cels) new_temp = c_to_f(cels) print str(cels) + " degrees Celcius is the same as " + str(new_temp) + " degrees Fahrenheit." else: print 'You did not enter a valid value.'
true
0eb3b4286a4ae9bdcf87ab4000e1f61adfd54d79
tian142/P1.PaySplit
/main.py
1,403
4.25
4
# this script takes the user's inputs of meal price, tip paid, and the number of people splitting the meal to calculate the cost each individual has to pay # for commit 2nd commit # for 3rd commit # prompts the user to enter meal price: meal_price = int(input('Please enter the price of your meal: ')) # tax variable set to CA average of 7.5% tax = 7.5 # promots the user to enter tip paid: tip_paid = int(input('Please enter your tip paid: ')) # calculate how much tax is paid tax_paid = meal_price * (tax/100) # calculate how much the entire meal cost, store in total_meal_price variable total_meal_price = meal_price + tax_paid + tip_paid # prompts user to enter the number of people splitting the bill: split_between = int( input('Please enter the total number of people splitting this meal: ')) # calculates price per person: price_per_person = total_meal_price / split_between # constructs result string: with the summary of the meal: result = f"The meal was: ${meal_price}. \nWith Tax of {tax}%, tax paid: ${tax_paid} \nTips paid: ${tip_paid} \nGross cost of meal: {total_meal_price}\nSplitting between {split_between} people, each person pays: ${round(price_per_person, 2)}" # creates a line in the terminal for better visuals line_break = "-------------------------------------------------------" # prints the result with line_breaks print(line_break + "\n" + result + "\n" + line_break)
true
217e8bdb42abfa02a3c0339d7bad3e124335b4c6
radovanbacovic/leetcode.test
/python_recursion/05_02/quicksort.py
927
4.125
4
def quicksort(arr): if len(arr) <= 1: return arr else: pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) def quicksort_verbose(arr): print(f"Calling quicksort on {arr}") if len(arr) <= 1: print(f"returning {arr}") return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] print(f"left: {left}; ", end="") middle = [x for x in arr if x == pivot] print(f"middle: {middle}; ", end="") right = [x for x in arr if x > pivot] print(f"right: {right}") to_return = quicksort_verbose(left) + middle + quicksort_verbose(right) print(f"returning: {to_return}") return to_return data = [5, 2, 1, 6] # print(quicksort(data)) print(quicksort_verbose(data))
false
b1d59b91dbed633b244d7912ffe25a6a418e7fb1
radovanbacovic/leetcode.test
/python_recursion/04_01/multiple_recursive.py
534
4.4375
4
""" Python Recursion Video Course Robin Andrews - https://compucademy.net/ """ def multiply_recursive(n, a): if n == 1: return a else: return a + multiply_recursive(n - 1, a) assert multiply_recursive(5, 4) == 20 # 5 is the multiplier, 4 is the multiplicand assert multiply_recursive(5, -4) == -20 # 5 is the multiplier, -4 is the multiplicand assert multiply_recursive(1, 4) == 4 # 1 is the multiplier, 4 is the multiplicand assert multiply_recursive(7, 8) == 56 # 7 is the multiplier, 8 is the multiplicand
false
8204d50fffdca9754d45867a0a7290771a1c1ef4
radovanbacovic/leetcode.test
/python_recursion/06_03/binary_tree_traversal.py
1,561
4.53125
5
""" Python Recursion Video Course Robin Andrews - https://compucademy.net/ """ class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def preorder_print(root, path=""): """Root->Left->Right""" if root: path += root.data + '-' path = preorder_print(root.left, path) path = preorder_print(root.right, path) return path def inorder_print(root, path=""): """Left->Root->Right""" if root: path = inorder_print(root.left, path) path += root.data + '-' path = inorder_print(root.right, path) return path def postorder_print(root, path=""): """Left->Right->Root""" if root: path = postorder_print(root.left, path) path = postorder_print(root.right, path) path += root.data + '-' return path if __name__ == '__main__': # Set up tree: root = Node("F") root.left = Node("D") root.left.left = Node("B") root.left.left.left = Node("A") root.left.left.right = Node("C") root.left.right = Node("E") root.right = Node("I") root.right.left = Node("G") root.right.left.right = Node("H") root.right.right = Node("J") print("Preorder:", preorder_print(root)) print("Inorder:", inorder_print(root)) print("Postorder", postorder_print(root)) r""" ______F______ / \ __D__ __I__ / \ / \ B E G J / \ \ A C H """
true
fa1e4fee51443d2e0fe6c76522fc372095b671b7
Crmille/Python-Projects
/guessNumber.py
1,294
4.28125
4
# -*- coding: utf-8 -*- """ GUESS THE NUMBER """ import random def main(intro=True): if intro == True: print(""" Welcome to Guess the Number! Here are the rules: 1. A number is randomly generated. 2. You guess the number. 3. If your guess is correct, you win! """) minVal = 1 maxVal = 10 guesses = [] randomVal = random.randint(minVal,maxVal) print("The random value has been generated.") print("The number is between:",minVal,"and",maxVal) while True: try: guess = int(input("Please input your guess.")) except ValueError: continue else: if guess in guesses: print("I'm sorry, this guess has alreayd been used. Try agian.") continue elif guess < randomVal: print("I'm sorry, your guess is too low.") guesses.append(guess) elif guess > randomVal: print("I'm sorry, your guess is too high.") guesses.append(guess) elif guess > maxVal or guess < minVal: print("I'm sorry, your guess is out of bounds. Try again." ) if __name__== "__main__": main()
true
09c3bff8eae1423c7cb1bb868843c84aa84bc772
felipellima83/UniCEUB
/Semestre 01/LogicaProgramacao/Aula 04.01.2020/Exercício01.py
1,177
4.25
4
#Curso: Ciência da Computação #Professor: Antônio Barbosa Junior #Disciplina: Lógica de programação #Aluno: Felipe Ferreira Lima e Lima #Matrícula: 22001310 #Data: 01/04/2020 #Exercício 01 numeroMaior = 0.01 numeroMenor = 2.99 limite = 3 somaH = 0 somaM = 0 somaAltura = 0 print("Para encerrar o programa digite na altura o valor zero (0)!") while True: altura = float(input("Qual sua altura? ")) if altura == 0: break genero = input("Qual seu gênero (H ou M)? ").upper() if genero == "H": somaH += 1 elif genero == "M": somaM += 1 else: print("Você não digitou uma opção válida!") if altura >= numeroMaior: numeroMaior = altura limite = altura if altura <= numeroMenor: numeroMenor = altura somaAltura += altura percentagem = (somaH/(somaH+somaM))*100 media = ((somaAltura)/(somaM+somaH)) if limite == 3: print("Você não digitou nenhum dado válido!") else: print("A maior altura do grupo é {} m e a menor é {} e a média é {:.2f}.\nO grupo possui {} homem(ns) e {} mulher(es).\nE a percentagem de homem(ns) do grupo é {}%.".format(numeroMaior, numeroMenor, media, somaH, somaM, percentagem))
false
b99ee9adf83a7f3573f6274ab548f55f4a742319
felipellima83/UniCEUB
/Semestre 01/ProjetoIntegrador1/Aula 05.22.2020/l08e02inverso.py
1,600
4.71875
5
''' - 1. Leia trinta valores inteiros digitados pelo usuário e armazene-os numa lista. Gere a tela de saída com os valores armazenados na lista. - 2. Refaça o programa anterior, mostre os valores armazenados no vetor na ordem inversa da entrada de dados. - Obs.: Para simplificar os testes, substitua trinta por três. Prova P2: 28/05 <-------------------------------------------------------------------------- ''' l_valores = [ ] # Lista inicialmente vazia for i in range(0, 3): # repete 3 vezes # recebe um número do usuário e adiciona à lista num = int(input("Digite um número: ")) l_valores.append(num) # mostra todos os valores da lista em ordem inversa print ('Valores da lista') print (l_valores [ : : -1]) ''' Alterações: a. Mostre os valores armazenados na lista na ordem inversa na vertical, use o for com range. b. Mostre os valores armazenados na lista na ordem inversa na vertical, use o for com range. E suas respectivas posições. c Também é possível acessar valores em uma lista do fim para o começo utilizando índices negativos. Refaça o loop que mostra os valores utilizando essa funcionalidade. DICAS: for i in range(2, -1, -1): # a. print(l_valores [i]) for i in range(2, -1, -1): # b. print(i, " -> ", l_valores[i]) #print("[", i, "] : ", l_valores[i]) for i in range(-1, -4, -1): # c. print(i, " -> ", l_valores[i]) print("[", i, "] : ", l_valores[i]) '''
false
720b690d82cc8858c0f831de2db4549f64c7ba62
felipellima83/UniCEUB
/Semestre 01/ProjetoIntegrador1/Aula 05.29.2020/l08e05acimamedia.py
2,847
4.4375
4
''' - 4. Construa o programa que calcule a média aritmética de uma turma com trinta alunos, onde cada aluno realizou uma avaliação. Além da média da turma, mostre também a tela de saída tabular com o número e a nota dos alunos. l_notas = [ ] # lista de notas inicialmente vazia soma = 0 # valor da soma inicialmente zero for i in range(0, 3): # Repete 3 vezes valor = int(input("Digite a nota do aluno: ")) # recebe a nota l_notas.append(valor) # adiciona à lista soma = soma + valor # soma += valor # mostra a lista de notas print ('Número - nota') for i in range(0, 3): print(i, ":", l_notas[i]) # mostra a média media = soma / 3 print("A média é:", media) - 5. Refaça o programa anterior para mostrar também a quantidade de notas acima da média da turma. - Obs.: Para simplificar os testes, substitua trinta por três. ''' l_notas = [ ] # lista de notas inicialmente vazia soma = 0 # valor da soma inicialmente zero alunos = int(input("Quantos alunos tem na turma? ")) # define qnts elementos tem na lista # for para inserir as notas dos alunos for i in range(0, alunos): # Repete 3 vezes valor = int(input(f"Digite a nota do {i+1} aluno: ")) # recebe a nota l_notas.append(valor) # adiciona à lista soma = soma + valor # soma += valor print ('Aluno / Nota') # imprime cabeçalho # repetição para imprimir a posição e as notas dos alunos for i in range(0, alunos): # repete 3 vezes print(i, "/", l_notas[i]) # imprime posição do aluno na lista e sua nota media = soma / 3 # calcula a média da turma print(f"A média da turma, com {len(l_notas)} alunos, é:", media) # mostra a média da turma ct = 0 # contador das notas acima da média da turma # mostra quantas notas foram acima da média da turma for i in l_notas: # repete de acordo com a qnt de elementos da lista if i > media: # verifica se a nota é maior que a média ct+=1 # contador de notas acima da média da turma print(f"Foram {ct} notas acima da média da turma.") # imprime a qnt de notas acima da média da turma ''' Alterações: '''
false
6e15f97d4d1f74684851749f2588b93023964889
felipellima83/UniCEUB
/Semestre 01/ProjetoIntegrador1/Aula 04.24.2020/l06e32HexaAteF.py
627
4.1875
4
''' 32 Implemente o programa que mostre a sequência dos números hexadecimais até F. O sistema hexadecimal utiliza estes 16 símbolos: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E e F. ''' for i in range(16): if (i<10): print(i) elif(i==10): print('A') elif(i==11): print('B') elif(i==12): print('C') elif(i==13): print('D') elif(i==14): print('E') else: print('F') ''' a- Obtenha o mesmo resultado sem usar if, crie a lista R: for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']: print(i) '''
false
8baaa0c7c8f9a650b8c000359c2295f5e0503cc0
felipellima83/UniCEUB
/Semestre 01/ProjetoIntegrador1/Aula 04.24.2020/l06e37.fibonacci.py
486
4.21875
4
''' 37. A série de Fibonacci é formada pela seguinte sequência: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... etc. A fórmu-la de recorrência para essa série é n i = n i-1 + n i-2 para i ≥ 2 pois n 0 = n 1 = 1. Escreva o programa que gere a série de Fibonacci até o vigésimo termo. ''' p1 = 0 p2 = 1 print("1º termo da sequência: ", p2) for i in range(19): p3 = p1 + p2 print(f"{i+2}º termo da swquência: ", p3) p1 = p2 p2 = p3 ''' Alterações '''
false
46de44a17d095870eea0afa053265abb3671937e
felipellima83/UniCEUB
/Semestre 01/ProjetoIntegrador1/Aula 04.17.2020/l06e21serieusuario.py
623
4.21875
4
''' 21. Deixe o problema anterior flexível, permita que o usuário forneça a quantidade de termos da série. Sendo H = 1/1 + 1/2 + 1/3 + ... + 1/n Alterações a. Modifique o programa para que o usuário entre com o numerador da série # adicionar essa linha no início numerador_serie = int(input("Digite o numerador da série: ")) # modificar essa linha dentro do for soma += numerador_serie / i ''' numerador = int(input("Qual o valor numerador?")) denominador = int(input("Qual o valor denominador?")) soma=0 for i in range(1, denominador+1): soma+= numerador/i print("A soma é igual a {:.2f}.".format(soma))
false
1dda72084c0a5fcfa663348e79961dd4c3fce8ab
VitorEhrig-Fig/entra21
/python/entra21/aula12/good-pratices.py
1,581
4.21875
4
# o guia do mochileiro python # explicito é melhor que implicito def make_dict(*args): x, y = args return dict(**locals()) def make_dict_pro(x, y): return {'x': x, 'y': y} print(*make_dict_pro('x', 'y')) # esparso é melhor que denso if (1+1 == 51 + 35 - 37) and "uma coisa complexa" == "palavra"[0]: pass # do something condicao_um = (1+1 == 51 + 35 - 37) condicao_dois = "uma coisa complexa" == "palavra"[0] if condicao_um and condicao_dois: pass # do something # erros nunca devem passar silenciosamente def find_word(letter): words = ['ball', 'heart', 'edge'] for word in words: if letter in words: return word raise Exception("Palavra não encontrada!") try: find_word("o") except: pass # raise # os argumentos de funções devem ter uso intuitivo def sendMsg(nome, sobrenome="", *args, **kwargs): print(nome) print(sobrenome) print(args) print(kwargs) sendMsg("Bruno", "Sadoski", "blablablablab", "xD", title="Hello world", msg="You ate the best!") # se a implementação é dificil de explicar, é uma má ideia! # kung fu vs python! # somos todos usuários responsáveis # encapsulamento # manter um unico ponto de retorno das funções def make_choice(param1, param2, *args): if param1: return "something" if param2: return "other thing" the_thing = "no thing" if param1: the_thing = "something" if param1: the_thing = "other thing" return the_thing
false
172030981b61c5f09cba8ac7179e15bef423f2e8
u73535508/270201030
/lab3/example3.py
289
4.1875
4
gpa = float(input("Enter your GPA:")) nol = float(input("Enter your number of lectures:")) if gpa<2 : if nol<47 : print("Not enough number of lectures and GPA!") else: print("Not enough GPA!") elif nol<47: print("Not enough number of lectures!") else: print("GRADUATED!")
false
bf82def1b0a4bd29216a4b5b49cddd9d08216cde
chai1323/Data-Structures-and-Algorithms
/InterviewBit/Linked List/List Cycle.py
1,778
4.3125
4
# Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node # p jumps once and q twice def check_loop(self): p = q = self.head while(p and q and q.next): p = p.next q = q.next.next if(p==q): return p return None def start_loop(self): p = q = self.head p = self.check_loop() while(p != q): p = p.next q = q.next return p.data # Utility function to print the linked list def printList(self): temp = self.head while (temp): print(temp.data) temp = temp.next obj = LinkedList() obj.append(11) obj.append(8) obj.append(3) obj.append(4) obj.head.next.next.next.next = obj.head.next print(obj.check_loop()) print(obj.start_loop())
true
18dc87341247a30b5877c972116d80ae2122986b
chai1323/Data-Structures-and-Algorithms
/LeetCode/String/Valid Parentheses.py
1,434
4.125
4
''' Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Example 4: Input: s = "([)]" Output: false Example 5: Input: s = "{[]}" Output: true ''' ------------------------------------------------------------------------------------------------------------------------------------------------------------- class Solution: def isValid(self, s: str) -> bool: stack = [] for char in s: if char in ['(', '{', '[']: stack.append(char) else: if not stack: return False current_char = stack.pop() if current_char == '(': if char != ')': return False if current_char == '{': if char != '}': return False if current_char == '[': if char != ']': return False if stack: return False return True
true
fc5ea89086d69b46ba451b3ce24580786d165910
shribadiger/pythonStudy
/ProgramWeight.py
341
4.125
4
#Program to convert the Weight in KG or in LBS weight = int(input('WEIGHT : ')) # return value in string and converted to Integer unit = input('L(BS) or K(G)') if unit.upper() == "L": converted = weight*0.45 print(f"You are {converted} Kilos") else: converted=weight / 0.45 print(f"You are {converted} pounds")
true
462743e4b91495c1b6eca6df31e6e2b444ec1f2d
piotrmichna/python_egzamin_probny_1
/exercise_01.py
545
4.15625
4
def shorten(txt): """Creates an shorten from eny text. :param str: eny text :rtype: str :return: shortened """ sh_str = str(txt) words = sh_str.split(' ') sh_str = "" for word in words: sh_str += word[0] sh_str = sh_str.upper() return sh_str if __name__ == '__main__': shortened = shorten("Don't repeat yourself") print(shortened) shortened = shorten("Read the fine manual") print(shortened) shortened = shorten("All terrain armoured transport") print(shortened)
true
8314022439b07bd21ff0ccfb83fa07d0624d0e8c
richardvecsey/python-basics
/033-harmonic_mean.py
586
4.34375
4
""" Get the harmonic mean of numbers -------------------------------- Input: (list) numbers Output: (float) harmonic mean of numbers """ from statistics import harmonic_mean numbers = [20, 10, 5] mean_1 = harmonic_mean(numbers) print('original numbers: {}\nmean: {}'.format(numbers, mean_1)) numbers_2 = [20.0, 10.0, 5.0] mean_2 = harmonic_mean(numbers_2) print('\noriginal numbers: {}\nmean: {}'.format(numbers_2, mean_2)) numbers_3 = [10, 10, 10] mean_3 = harmonic_mean(numbers_3) print('\noriginal numbers: {}\nmean: {}'.format(numbers_3, mean_3))
true
3bc737194f3381cc76fdab0377bfd24ef432122d
richardvecsey/python-basics
/016-sum.py
479
4.15625
4
""" Return sum of iterable and start value -------------------------------------- Input: value optional: start value Return: sum of values """ numbers = [0, 1, 2, 3, 4, 5] print('numbers: {}\n sum: {}'.format(numbers, sum(numbers))) start_value = 10 print('numbers: {} + start value: {}\n sum: {}'.format(numbers, start_value, sum(numbers, start_value))) numbers = [0, 1, 2, 3, 4, 5, -10] print('numbers: {}\n sum: {}'.format(numbers, sum(numbers)))
true
c9be82922f9afbfc29ef14fe5da4cd36d822a1d9
richardvecsey/python-basics
/046-swapcase.py
400
4.5
4
""" Swap cases in a string ---------------------- Input: (string) any string Output: (string) swapped string, upper cases become lower cases and vice versa """ original_string = 'This is an "A" letter.' modified_string = original_string.swapcase() print('original string: {}\nswapped version: {}' .format(original_string, modified_string))
true
2de30d34711d0f08e8877d2f1be40ddf31307e64
richardvecsey/python-basics
/032-mean.py
757
4.3125
4
""" Get the arithmetic mean of numbers ---------------------------------- Input: (list) numbers Output: (number) arithmetic mean of numbers """ from statistics import mean numbers = [10, 5, 0, -5, -10] mean_1 = mean(numbers) print('original numbers: {}\nmean: {}'.format(numbers, mean_1)) numbers_2 = [10.0, 5.0, 0, -5.0, -10] mean_2 = mean(numbers_2) print('\noriginal numbers: {}\nmean: {}'.format(numbers_2, mean_2)) # How to calculate arithmetic mean without satistics.mean() function? numbers_3 = [20.0, 10, 0, -5.0, -10] sum_numbers = sum(numbers_3) count_numbers = len(numbers_3) mean_numbers = sum_numbers / count_numbers print('\noriginal numbers: {}\nmean without function: {}'.format(numbers_3, mean_numbers))
true
60d6208ef1c30ab58ba1022c6154a8f1905d64d3
richardvecsey/python-basics
/035-fmean.py
668
4.375
4
""" Get the arithmetic mean of numbers ---------------------------------- Input: (list) numbers Output: (float) arithmetic mean of numbers """ # fmean() is faster, than mean() and always returns with float # Python 3.8 is required from statistics import fmean numbers = [20, 5, 0, -5, -10] mean_1 = fmean(numbers) print('original numbers: {}\nmean: {}'.format(numbers, mean_1)) numbers_2 = [20.0, 5.0, 0, -5.0, -10] mean_2 = fmean(numbers_2) print('\noriginal numbers: {}\nmean: {}'.format(numbers_2, mean_2)) numbers_3 = [10, 10, 10] mean_3 = fmean(numbers_3) print('\noriginal numbers: {}\nmean: {}'.format(numbers_3, mean_3))
true
94be0f3423baca40dfd4817a41574d778c970987
richardvecsey/python-basics
/044-lower.py
376
4.53125
5
""" Return lowercase version of a string ------------------------------------ Input: (string) any string Output: (string) lowercase version of input string """ original_string = 'This is an "A" letter.' modified_string = original_string.lower() print(' Original string: {}\nLowercase version: {}' .format(original_string, modified_string))
true
5e3e70ba04ab93172833d10c6b9ea21500e0d832
vthavhiwa/myhackathon
/myhackathon/sorting.py
1,171
4.28125
4
def bubble_sort(items): """Return array of items, sorted in ascending order""" count = 0 for item in range(len(items)-1): if items[item] > items[item + 1]: items[item],items[item + 1] = items[item + 1],items[item] count += 1 if count == 0: return items else: return bubble_sort(items) def merge_sort(items): """Return array of items, sorted in ascending order""" if len(items) < 2: return items result = [] # moved! mid = int(len(items) / 2) y = merge_sort(items[:mid]) z = merge_sort(items[mid:]) while (len(y) > 0) and (len(z) > 0): if y[0] > z[0]: result.append(z[0]) z.pop(0) else: result.append(y[0]) y.pop(0) result += y result += z return result def quick_sort(items): """Return array of items, sorted in ascending order""" if len(items) == 0: return items p = len(items) // 2 l = [i for i in items if i < items[p]] m = [i for i in items if i == items[p]] r = [i for i in items if i > items[p]] return quick_sort(l) + m + quick_sort(r)
true
0f1b32d34e7a31a1e9216e8d8a5695fcce0f13c8
Geeky-har/Python-Files
/Practice_Set/capitalize.py
415
4.25
4
# the program is to capitalize the first letter of the word # Ex: harsh negi -> Harsh Negi import string def change(name): return string.capwords(name) def change2(name): # alternative method return name.title() if __name__ == "__main__": name = input("Write Your name: ") # new_name = change(name) # print(new_name) new_name2 = change2(name) # alternative method print(new_name2)
true
bf16d2b00bc6e682f6cac99c65ddd30eb6ead688
tbro28/intermediatepython
/python_intrm_supplemental_files/intrm_python_suppplemental_info/intro_python_suppplemental_info/python_reg_expression/Python_oop_examples/JEFF_EMPLOYEE.py
1,022
4.15625
4
class Employee: def __init__(self, lastName, firstName): self.lastName = lastName self.firstName = firstName def getLastName(self): return self.lastName def setLastName(self,newln): ##self.lastName = str(input("Enter Last Name: ")) self.lastName=newln def getFirstName(self): return self.firstName def setFirstName(self): self.firstName = str(input("Enter First Name: ")) def getName(self): name = self.getFirstName() + " " + self.getLastName() return str(name) def setName(self): self.setLastName() self.setFirstName() employee = Employee("Taylor","Jeff") e1= Employee("Smow","joe") e1.setLastName("smith") print("Employee Data") print("Employee Name: {:s}".format(e1.getLastName())) print("Employee Name: {:s}".format(employee.getName())) employee.setLastName() print("Employee Name: {:s}".format(employee.getName())) employee.setName() print("Employee Name: {:s}".format(employee.getName()))
false
28fc8b4aa58e28f796ec5b27adf86b9ccc4c191f
vigneshwarand/SeleniumPythonProjectNew
/First_Selenium/PythonLoops.py
435
4.1875
4
if 5>3: print("5 is greater than 3") num = 0 if num > 0: print("This is a positive num") elif num == 0: print("Num is zero") else: print("This is a negative num") num = [1,2,3,4,5] sum =0 for i in num: print(i) fruits = ["Apple","Oranges","Grapes"] for val in fruits: print(val) else: print("No fruits left") num = 5 sum = 0 i = 1 while i<num: sum = sum + i i = i + 1 print("Total is : ", sum)
true
c7c476f72825bc121061a9da328cb75fd5a0966b
JianxiangWang/python-journey
/leetcode/81_Search_in_Rotated_Sorted_Array_II.py
1,354
4.1875
4
# coding=utf-8 # # Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved # """ The 81_Search_in_Rotated_Sorted_Array_II file. Authors: Wang Jianxiang (wangjianxiang01@baidu.com) """ """ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true Example 2: Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false """ class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ lo, hi = 0, len(nums) - 1 while lo <= hi: while lo < hi and nums[lo] == nums[hi]: lo += 1 mid = (lo + hi) // 2 if nums[mid] == target: return True else: if nums[lo] <= nums[mid]: if nums[lo] <= target < nums[mid]: hi = mid - 1 else: lo = mid + 1 else: if nums[mid] < target <= nums[hi]: lo = mid + 1 else: hi = mid - 1 return False
true
e47500e0514c5243fb51023f83254d66770ad8ae
JianxiangWang/python-journey
/leetcode/206_Reverse_Linked_List.py
1,073
4.125
4
# coding=utf-8 # # Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved # """ The 206_Reverse_Linked_List file. Authors: Wang Jianxiang (wangjianxiang01@baidu.com) """ """ Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev, curr = None, head while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt return prev def reverseList_recurrent(self, head): def _helper(prev, curr): if curr: nxt = curr.next curr.next = prev return _helper(curr, nxt) else: return prev return _helper(None, head)
true
863fb82bc8556acbe32e004bf958e5347024da41
msviopavlova/HackerRankBasic-Python
/pyifelse.py
458
4.34375
4
#Given an integer, , perform the following conditional actions: #If n is odd, print Weird #If n is even and in the inclusive range of to , print Not Weird #If n is even and in the inclusive range of to , print Weird #If n is even and greater than , print Not Weird n = int(input().strip()) if n%2==0 and 2<=n<=5: print("Not Weird") elif n%2==0 and 6<= n <=20: print("Weird") elif n%2==0 and 20<n: print("Not Weird") else: print("Weird")
false
4033760f556a10bd30a5cb55851faa7fffe69958
naellenhe/practice_code_challenge
/interviewcake/merge_sort.py
825
4.28125
4
def merge_lists(lst1, lst2): """Use merge to sort lists. >>> list1 = [3, 4, 6] >>> list2 = [1, 5] >>> print merge_lists(list1, list2) [1, 3, 4, 5, 6] >>> list1 = [3, 4, 6, 10, 11, 12, 15, 20, 20] >>> list2 = [1, 5, 8, 12, 14, 19, 20] >>> print merge_lists(list1, list2) [1, 3, 4, 5, 6, 8, 10, 11, 12, 12, 14, 15, 19, 20, 20, 20] """ result = [] while lst1 and lst2: if lst1[0] < lst2[0]: result.append(lst1.pop(0)) else: result.append(lst2.pop(0)) if not lst1: result.extend(lst2) if not lst2: result.extend(lst1) return result if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. NICE STACKING!\n"
true
ae5e82ded1642f4a3cb9056812cccaf086527234
Allam2003/Python-Activities-
/Al Python Source Code/Thinking 1/lvl2thinking - Copy.py
320
4.3125
4
temperature= int(input("Please enter the temperature C.")) if temperature>12: print("The temperature is greater than average temperature C .") elif temperatue==12: print("The temperature is at the average temperature C.") else: print("The temperature is lower than average temperature C.")
true
4fa111e3b6806eafaa86a941a95956c0a6839d63
KishanSewnath/Python
/Lessen/Les 4/Practice problems/4.2.py
483
4.1875
4
weather = 'It will be a sunny day today' #print(weather.count('day')) #print(weather.find('sunny') print(weather.replace('sunny', 'cloudy')) #write Python statements corresponding to these assignments: # (a) To variable count, the number of occurrences of string 'day' in string forecast. # (b) To variable weather, the index where substring 'sunny' starts. # (c) To variable change, a copy of forecast in which every occurrence of substring #'sunny' is replaced by 'cloudy'.
true
d79600521bc0e43086088c1a01a775163a75a417
h3ic/cs102
/homework01/caesar.py
1,119
4.5
4
def encrypt_caesar(plaintext): """ Encrypts plaintext using a Caesar cipher. >>> encrypt_caesar("PYTHON") 'SBWKRQ' >>> encrypt_caesar("python") 'sbwkrq' >>> encrypt_caesar("Python3.6") 'Sbwkrq3.6' >>> encrypt_caesar("") '' """ ciphertext = '' for ch in plaintext: if not ch.isalpha(): ciphertext += ch elif ch.isupper(): ciphertext += chr((ord(ch) + 3 - 65) % 26 + 65) else: ciphertext += chr((ord(ch) + 3 - 97) % 26 + 97) return ciphertext def decrypt_caesar(ciphertext): """ Decrypts a ciphertext using a Caesar cipher. >>> decrypt_caesar("SBWKRQ") 'PYTHON' >>> decrypt_caesar("sbwkrq") 'python' >>> decrypt_caesar("Sbwkrq3.6") 'Python3.6' >>> decrypt_caesar("") '' """ plaintext = '' for ch in ciphertext: if not ch.isalpha(): plaintext += ch elif ch.isupper(): plaintext += chr((ord(ch) - 3 - 65) % 26 + 65) else: plaintext += chr((ord(ch) - 3 - 97) % 26 + 97) return plaintext
false
f1f7b1b1f1dd7337663436dde294bffaaed81802
toyinfa2884/parsel_tongue
/ABDULFATAI_FOLDER/functions/exercise.py
2,860
4.28125
4
# #write a python function to find the max of three numbers. def max_of_three_numbers(number1, number2, number3): number1 = int(input("Enter the first number")) number2 = int(input("Enter the second number")) number3 = int(input("Enter the third number")) max_number = number1 if number2 > max_number: max_number = number2 if number3 > max_number: max_number = number3 return max_number print(max_of_three_numbers()) # #write a python funtion to sum all the numbers in a list. def sum(numbers): total = 0 for j in numbers: total += j return total my_list = [] number1 = int(input()) number2 = int(input()) number3 = int(input()) my_list = number1 + number2 + number3 print(sum(my_list)) #write a python function to multiply all the numbers in list(sample: def multiply_list(list) : total = 1 for i in list: total = total * i return total my_list = [] number1 = int(input()) number2 = int(input()) number3 = int(input()) my_list = number1 * number2 *number3 print(my_list) print(multiply_list(my_list)) #write a python program to reverse a string, (sample: "1234abcd") def reverse_string(string): f="" for i in string: f=i+f return f string="1234abcd" print(reverse_string(string)) #write a python function to calculate the factorial of a number #(a non-negative integer). The function accepts the number as an argument def factorial_of_number(number): number = int(input("Enter a number")) Counter = 0 while number > 1: Counter += 1 def factorisation(n): fact = [] i = 2 while i<=n: if n%i==0: fact.append(i) n//= i else: i+=1 return fact #whether a number fall in a given range def range(): for i in range(): #write a python function that accepts a string and calculate the number #of upper case letters and lower case letter.Sample: 'The quick brow fox' def count_upper_case_letters(string): string = input("Enter a string:") count = 0 for character in string: if character.isupper(): count += 1 return count count = count_upper_case_letters('The quick Brow Fox') print("The numbers of upper case letters is:", count) def count_lower_case_letters(string): string = input("Enter a string:") Counter = 0 for charater in string: if charater.islower(): Counter += 1 return Counter Counter = count_lower_case_letters('The quick Brow Fox') print("The numbers of lower case letters is:", Counter) #even number def even_number(list =[]): for n in list: if n % 2 == 0: print(n, " ") #### def check_prime(n): if == 1: count = 2 return False if n == 2: return True for a in range:
true
37e01046a663d67a175c5845691dcf813671edf5
Cxiaojie91/python_basis
/python_basis/python_procedure/python_others/unicode_python.py
574
4.28125
4
print('包含文中的str') print(ord('A')) print(ord('中')) print(chr(66)) print(chr(25991)) print(len(b'ABCDE')) # 第一行告诉Linux/OS系统,这是一个Python可执行程序,Windows会忽略该注释 # 第二行是告诉Python解释器,按照UTF-8编码读取源代码,否则中文的输出有可能会乱码 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # -*- coding: utf-8 -*- s1 = 72 s2 = 85 r = (s2 - s1)/s1*100 #print(r) print('小明成绩提升:%.1f%%' % r) print('小明成绩提升:{0:.1f}%'.format(r)) print(f'小明成绩提升:{r:.1f}%')
false
098f8274803e6123457f16800e031f32a50e72b6
jhancock1229/PythonExercises
/Exercise3/exercise_3.py
1,485
4.34375
4
# Initial user input code user_input = raw_input("Please enter a speed in miles/hour: ") while True: try: user_input = float(user_input) except ValueError: user_input = (raw_input("MPH is a number, you dummy. Please enter an actual speed!: ")) continue else: break user_input_int = int(user_input) # Below, conversion values are assigned to variables meters_per_mile = 1609.34 hours_in_day = 24.0 barleycorn_per_meter = 117.647 barleycorn_per_mile = 378669.0 / 2.0 miles_furlongs = 8.0 # One mile is equal to 8 furlongs speed_of_sound_mph = 761.207051 feet_per_mile = 5280.0 speed_of_light_mph = 670616629.0 seconds_per_hour = 3600.0 days_in_week = 7.0 weeks_in_fortnight = 2.0 hours_to_fortnight = hours_in_day * days_in_week * weeks_in_fortnight # Below, variables are combined to produce results for the assignment barleycorn_per_day = user_input_int * barleycorn_per_mile * hours_in_day furlongs_per_fortnight = user_input_int * miles_furlongs * hours_to_fortnight mach_number = user_input_int / speed_of_sound_mph percent_speed_of_light = user_input_int / speed_of_light_mph # Execution of program print "Original speed in mph is: %s" % user_input print "Converted to barleycorn/day is: %s" % barleycorn_per_day print "Converted to furlongs/fortnight is: %s" % furlongs_per_fortnight print "Converted to Mach number is: %s" % mach_number print "Converted to the percentage of the speed of light is: %s" % percent_speed_of_light
true
ce1fb76bb556ac5236a369e1ea4d0598b54f0f02
robahall/algosds
/dataStructures/recursion/memoization.py
1,628
4.5625
5
from functools import wraps def fibonacci(n): """ Simple recursion example to compute fibonacci number Recurrence relation: F(n) = F(n-1) + F(n-2) Base Case: F(0) = 0 , F(1) = 1 Example: F(4) = F(3) + F(2) = F(F(2) + F(1)) + F(2) = F(F(1) + F(0) + F(1)) + F(F(1) +F(0)) = 1 + 0 + 1 + 1 + 0 :param n: (int) specified index for calculating a fibonacci number :return: fibonacci number at index n """ if n < 2: return n else: return fibonacci(n-1) + fibonacci(n-2) def memo_fibonacci(n): """ Add in memoization to cache already computed branches. :param n: (int) specified index for calculating a fibonacci number :return: fibonacci number at index n """ cache = {} def recur_fib(n): if n in cache: return cache[n] if n < 2: result = n else: result = recur_fib(n-1) + recur_fib(n-2) cache[n] = result return result return recur_fib(n) ## How to memoize with decorators: def cache(func): cache = {0: 0, 1: 1} def wrapper(idx): if idx in cache: return cache[idx] result = func(idx) cache[idx] = result return result return wrapper @cache def dec_fib(n): return dec_fib(n-1) + dec_fib(n-2) ## Python decorator internal cache from functools import lru_cache @lru_cache(maxsize=None) def lru_fib(n): if n <2: return n return lru_fib(n-1) + lru_fib(n-2) if __name__ == "__main__": #print(fibonacci(100)) print(memo_fibonacci(50)) print(dec_fib(50)) print(lru_fib(50))
false
7d56780ee3b485a656605396e9305671fd64b45c
taylor-stinson/cp1404practicals
/prac_01/loops.py
386
4.15625
4
""" CP1404/CP5632 - Practical For Loops """ for i in range(1, 21, 2): print(i, end=' ') print() for i in range(0, 101, 10): print(i, end=" ") print() for i in range(20, 0, -1): print(i, end=" ") print() number_stars = int(input("Number of stars: ")) for i in range(number_stars): print("*", end="") print() for i in range(0, number_stars + 1, 1): print(i * "*")
false
7db9f3b994e6eca642f1ae81960102b83180fded
Ayushd70/RetardedCodes
/python/dateTime.py
498
4.46875
4
# Python program showing how Python's built-in datetime module works from datetime import datetime dt = datetime.now() # Current date and time # Date day = dt.day # Current day month = dt.month # Current month year = dt.year # Current year # Hour hour = dt.hour # Current hour minute = dt.minute # Current minute second = dt.second # Current second microsecond = dt.microsecond # Current microsecond print(f"Current date: {day}/{month}/{year}") print(f"Current hour: {hour}:{minute}:{second}")
false
505123556b075311907b83adf9cc2c3c5dc4b261
Ayushd70/RetardedCodes
/python/kiloToMiles.py
310
4.5
4
# Program to convert Kilometers to Miles # Taking kilometers input from the user kilometers = float(input("Enter value in kilometers: ")) # conversion factor convFac = 0.621371 # calculate miles miles = kilometers * convFac print("%0.2f kilometers is equal to %0.2f miles" % (kilometers, miles))
true
2b008462f79eeb55ef04654e96ed001c518ce1b3
Ayushd70/RetardedCodes
/python/trimWhite.py
250
4.34375
4
# Python Program to Trim Whitespace From a String # Using strip() my_string = " Python " print(my_string.strip()) #Using regular expression #import re # #my_string = " Hello Python " #output = re.sub(r'^\s+|\s+$', '', my_string) # #print(output)
false
ddcb44925f0df6531fd92d5a9b590b4bfc835ae9
Ayushd70/RetardedCodes
/python/mergeDic.py
497
4.53125
5
# Python program to merge two dictionary # Method 1 # Using copy() and update() dict_1 = {1: 'a', 2: 'b'} dict_2 = {2: 'c', 4: 'd'} dict_3 = dict_2.copy() dict_3.update(dict_1) print(dict_3) # Method 2 # Using operator ** (Works only on Python 3.5 and above) # dict_1 = {1: 'a', 2: 'b'} # dict_2 = {2: 'c', 4: 'd'} # print({**dict_1, **dict_2}) # Method 3 # Using operator| (Works only on Python 3.9 and above) # dict_1 = {1: 'a', 2: 'b'} # dict_2 = {2: 'c', 4: 'd'} # print(dict_1|dict_2)
true
635c92df3b6ff504c009dd644951a508e8037341
ripfreeworld/Learn_Python_Workout
/lcy/exercise_3_pre.py
615
4.5
4
class MyClass: """A simple example class""" # https://docs.python.org/3/tutorial/classes.html i = 12345 def f(self): return 'hello world' sample = MyClass() print(sample.f()) class Complex: # When a class defines an __init__() method, # class instantiation automatically invokes __init__() # for the newly-created class instance. def __init__(self, realpart, imagpart): # 在类中定义的函数有一点不同,第一个参数永远是实例变量self self.r = realpart self.i = imagpart x = Complex(1, -1) print(f"the realpart of 'x' is {x.r}")
true
1184a36dabac3bb8c05cd77785ce1a76a25a2346
ripfreeworld/Learn_Python_Workout
/lxb/exercise2.py
1,302
4.4375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ''' *re-implementing functionality* The function takes a sequence of numbers, and returns the sum of those numbers. so if you were to invoke sum([1,2,3]), the result would be 6. The challenge here is to write a mysum function that does the same thing as the built-in sum function. However, instead of taking a single sequence. (The built-in sum function takes an optional second argument, which we're ignoring here.) (And in particular, you should think about the types of parameters functions can take in Python. In many languages, functions can be defined multiple times, each with a different type signature (i.e. number of parameters, and parameter types). In Python, only one function definition i.e., the last time that the function was defined) sticks. The flexibility comes from appropriate use of the different parameter types.) [arbitrary-argument-lists](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists) ''' def mysum(numberlist): sum1 = 0 for ele in numberlist: sum1 += ele return sum1 NumList = [] n = 0 while n <= 5: x = int(input('Please input a number in the list\n')) NumList.append(x) n += 1 mysum(NumList) print(mysum(NumList))
true
f7faa97e02db4267cb4ce7a50b512d40f11eaa52
marinamer/Code-Simplicity-Efficiency
/your-code/challenge-2.py
1,654
4.21875
4
""" The code below generates a given number of random strings that consists of numbers and lower case English letters. You can also define the range of the variable lengths of the strings being generated. The code is functional but has a lot of room for improvement. Use what you have learned about simple and efficient code, refactor the code. """ import string import random # we generate a random number from the max and min lengths given # with that length, we select a random string def RandomStringGenerator(a,b,n): length = random.randint(a, b) letters_and_numbers = list(string.ascii_lowercase + string.digits) r = list() while len(r) < n: r.append(''.join([random.choice(letters_and_numbers) for i in range(length)])) return r # by creating this function, we're storing every variable introduced, checking that it is an integrer and raising an error if it's not. def ChooseNumber(x): while True: try: a = int(input(x)) break except ValueError: print('You must input an integrer, try again') continue return a # we start with a minimum bigger than a maximum to ensure that the while loop always happens a = 100 b = 0 # the while loop ensures that the minimum is always lower than the maximum while a > b: a = ChooseNumber('Enter minimum string length: ') b = ChooseNumber('Enter maximum string length: ') if a > b: print('Your maximum string length is smaller than your minimum,please try again') n = ChooseNumber('How many random strings to generate? ') print(RandomStringGenerator(a,b,n))
true
cb23c30a12edd93d15dde6153fdcf2ca62c942b4
Sausageexpert/MrWiFiPy
/countTheString.py
427
4.125
4
whatIWasGoingToSay = input("No Quotations \"Whatever I Want\" Pls ") characterCount = 0 wordCount = 1 for i in whatIWasGoingToSay: characterCount = characterCount + 1 if(i == ' '): wordCount = wordCount + 1 print("Number Of Words You Were Going To Say 100% Accuracy") print(wordCount) print("Number of Characters You Were Probably Not Going To Say The E is Silent in Sure") print(characterCount)
true
6151218dc35b978e212be65cf2b00ef1e238773a
kanik9/Plotly-and-Dash
/Bar Plot/bar_chart.py
2,430
4.125
4
# Bar Chart : """ A bar chart presents Categorical data with rectangular bars with heights (or lengths) proportional to the values that they represent * Using Bar Charts, we can visualize categorical data * Typically the x-axis is the categories and the y-axis is the count(number of occurrences) in each category * However the y-axis can be any aggregation : count , sum ,average etc. """ #Importing Important libraies import pandas as pd import plotly.offline as pyo import plotly.graph_objs as go # Importing data by using pands data = pd.read_csv("/media/kanik/5DE14840704F5B09/Documents/Plotly-Dashboards-with-Dash-master/Data/2018WinterOlympics.csv") #print(data) # Bar Chart: trace = go.Bar(x=data["NOC"], y=data["Total"]) data_bar = [trace] layout_bar = go.Layout(title='Total Number of Medals') fig_bar = go.Figure(data=data_bar,layout=layout_bar) pyo.plot(fig_bar,filename='bar_chart.html') # Nested Bar Chart trace_gold = go.Bar(x=data["NOC"], y=data["Gold"], name='Gold', marker = {'color':'#FFD700'}) trace_silver = go.Bar(x=data["NOC"], y=data["Silver"], name='Silver', marker = {'color':'#9EA0A1'}) trace_bronze = go.Bar(x=data["NOC"], y=data["Bronze"], name='Bronze', marker = {'color':'#CD7F32'}) data_nested = [trace_gold,trace_silver,trace_bronze] layout_nested = go.Layout(title='Specific Bar Graph of gold , silver and bronze') fig_nested = go.Figure(data=data_nested,layout=layout_nested) pyo.plot(fig_nested,filename='nested_bar_chart.html') # Stacked Bar Chart trace1_gold = go.Bar(x=data["NOC"], y=data["Gold"], name='Gold', marker = {'color':'#FFD700'}) trace1_silver = go.Bar(x=data["NOC"], y=data["Silver"], name='Silver', marker = {'color':'#9EA0A1'}) trace1_bronze = go.Bar(x=data["NOC"], y=data["Bronze"], name='Bronze', marker = {'color':'#CD7F32'}) data_stacked = [trace1_gold,trace1_silver,trace1_bronze] layout_stacked = go.Layout(title='Specific Bar Graph of gold , silver and bronze in a single bar', barmode='stack') fig_stacked = go.Figure(data=data_stacked,layout=layout_stacked) pyo.plot(fig_stacked,filename='stacked_bar_chart.html')
true
df4500d4c6d13e8f5c1983b6bdb777f0368940e9
sunquan9301/pythonLearn
/thehardway/practice2.py
428
4.1875
4
#练习运算符,继续进行打印 def main(): print("I will now count my chickens") print("Hens", 25+30/6,20) print("Roosters", 100-25*3%4) print(3+2<5-7) x = "I am a boy, I am %d year old" % 10 print(x) print("."*10) print('''I 'd like "said" I am boy''') format = "%r %r %r %r" print(format % (1,2,3,4)) print(format % ("a","b",3,'d')) if __name__ == "__main__": main()
false
d3bdb92d2507bb04b8f42c0758457f775fd79835
iampsr8/Spectrum_intrn
/Spectrum_PythonDev/prgm9.py
242
4.1875
4
# nth smallest integer in the array a=[] x=int(input('Enter number of elements in array: ')) print('Enter elements in the array: ') for i in range(x): a.append(int(input())) a.sort() n=int(input('Enter integer n: ')) print(a[n-1])
true