blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2f5785f87b438aa89bcc88f403048f69545259ac
oscar7692/python_files
/agendaPyton.py
2,929
4.15625
4
#!/usr/bin/python3.7 def menu(): print('******Directorio de Contactos******') print('1- Crear nombre de la lista') print('2- Agregar Contacto') print('3- Buscar en directorio') print('4- Editar contactos') print('5- Mostrar contactos') print('6- Cerrar directorio') print() def menu2(): print('a- Buscar por nombre') print('b- Buscar por telefono') print('c- Buscar por direccion') def menu3(): print("Editar lista") print('1.- Eliminar un contacto') print('2.- Editar un contacto') directorio = [] telefonos = {} nombres = {} direcciones = {} apodos = {} opcionmenu = 0 menu() x=0 while opcionmenu != 6: opcionmenu = int(input("Inserta un numero para elegir una opcion: ")) if opcionmenu == 1: print('Ingrese el nombre de la lista:') nombre_de_lista=input() menu() elif opcionmenu == 2: print("Agregar Nombre, telefono, direccion y apodo") nombre = input("Nombre: ") telefono = input("Telefono: ") direccion = input("Direccion: ") apodo = input("Apodo: ") telefonos[nombre] = telefono nombres[telefono] = nombre direcciones[direccion] = nombre directorio.append([nombre, telefono, direccion, apodo]) menu() elif opcionmenu == 3: print("Busqueda") menu2() opcionmenu2 = input("Inserta una letra para elegir una opcion: ") if opcionmenu2=="a": nombre = input("Nombre: ") if nombre in telefonos: print("El telefono es", telefonos[nombre]) else: print(nombre, "no se encuentra") if opcionmenu2=="b": telefono = input("Telefono: ") if telefono in nombres: print("El Nombre es", nombres[telefono]) else: print(telefono, "no se encuentra") if opcionmenu2=="c": direccion = input("direccion: ") for linea in direcciones: linea = linea.rstrip() if not linea.startswith(direccion) : continue palabras = linea.split() print() else: print(direccion, "no se encuentra") menu() elif opcionmenu == 4: menu3() opcionmenu3 = input("Inserta un numero para elegir una opcion: ") if opcionmenu3=="1": nombre = input("Nombre: ") if nombre in directorio[0:10]: print('borrado') else: print(nombre, "no encontrado") else: menu() menu() elif opcionmenu == 5: print("\nNombre de la lista: ",nombre_de_lista) for e in directorio: print("\nLa lista es: ",directorio) menu() elif opcionmenu != 6: menu()
false
87324442d3dabfdcae8ef4bbea84f21f1586d663
drdiek/Hippocampome
/Python/dir_swc_labels/lib/menu/select_processing.py
1,109
4.125
4
def select_processing_function(): reply = '' # main loop to display menu choices and accept input # terminates when user chooses to exit while (not reply): try: print("\033c"); # clear screen ## display menu ## print 'Please select your processing function of interest from the selections below:\n' print ' 1) Conversion of .swc file(s)' print ' 2) Plotting of an .swc file' print ' 3) Creation of a morphology matrix file' print ' !) Exit' reply = raw_input('\nYour selection: ') ## process input ## if reply == '!': return('!') else: num = int(reply) if ((num > 0) & (num <= 3)): return(num) else: reply = '' except ValueError: print 'Oops! That was not a valid number. Please try again ...'
true
f77924a09f7f0fd2a7eafd266a54a653dd79d13b
dmikos/PythonExercises
/geekbrains.ru/lesson_7759-Интенсив по Python/gibbet.py
2,401
4.125
4
#!/usr/bin/python3 import random import turtle import sys # https://geekbrains.ru/lessons/7759 # 1:25:16 def gotoxy(x, y): #перемещаем курсор turtle.penup() turtle.goto(x, y) turtle.pendown() def draw_line(from_x, from_y, to_x, to_y): # gotoxy(from_x, from_y) turtle.goto(to_x, to_y) def draw_circle(x, y, r): gotoxy(x, y) turtle.circle(r) def draw_gibbet_element(step): if step == 1: draw_line(-160, -100, -160, 80) elif step == 2: draw_line(-160, 80, -80, 80) elif step == 3: draw_line(-160, 40, -120, 80) elif step == 4: draw_line(-100, 80, -100, 40) elif step == 5: draw_circle(-100, 0, 20) elif step == 6: draw_line(-100, 0, -100, -50) elif step == 7: draw_line(-100, -10, -120, -20) elif step == 8: draw_line(-100, -10, -80, -20) elif step == 9: draw_line(-100, -50, -120, -60) elif step == 10: draw_line(-100, -50, -80, -60) x = random.randint(1, 100) print(x) turtle.write("Загаданное число от 1 до 100. \n Попробуй угадать!", font=("Arial", 18, "normal")) ans = turtle.textinput("Хотите играть?", "y/n") if ans == 'n': sys.exit(13) ans = turtle.textinput("Давать подсказки?", "y/n") hints = ans == 'y' try_count = 0 turtle.speed(0) while True: number = turtle.numinput("Попробуй угадать", "Число", 0, 0, 100) if hints: gotoxy(230,200 - try_count*15) turtle.color('black') if number < x: turtle.write(str(number) + " - Загаданное число больше") elif number > x: turtle.write(str(number) + " - Загаданное число меньше") if number == x: gotoxy(-150, -200) turtle.color('green') turtle.write("Вы угадали", font=("Arial", 24, "normal")) break else: gotoxy(-150, 200) turtle.color('red') turtle.write("Неверно", font=("Arial", 20, "normal")) try_count += 1 draw_gibbet_element(try_count) if try_count == 10: gotoxy(-150, 150) turtle.color('brown') turtle.write("Вы проиграли!", font=("Arial", 25, "normal")) break input('Нажмите Enter')
false
f46893c5784cc16ad9c4bcaf19d47a126e1f02a5
Granbark/supreme-system
/binary_tree.py
1,080
4.125
4
class Node(): def __init__(self, value): self.value = value self.left = None self.right = None class BST(): def __init__(self): self.root = None def addNode(self, value): return Node(value) #returns a Node, see class def addBST(self, node, number): #node = current node, number is what you wish to add if node is None: return self.addNode(number) #go left elif number < node.value: node.left = self.addBST(node.left, number) #go right elif number > node.value: node.right = self.addBST(node.right, number) return node def printBST(self, node): #Print values from root #In order if node.left is not None: self.printBST(node.left) print(node.value) if node.right is not None: self.printBST(node.right) return if __name__ == "__main__": bst = BST() root = Node(50) bst.root = root bst.addBST(bst.root, 15) bst.addBST(bst.root, 99) bst.addBST(bst.root, 25) bst.addBST(bst.root, 56) bst.addBST(bst.root, 78) bst.printBST(bst.root)
true
6a5cf3421133b39a0108430efee4d3c9ba51933f
megnicd/programming-for-big-data_CA05
/CA05_PartB_MeganMcDonnell.py
2,112
4.1875
4
#iterator def city_generator(): yield("Konstanz") yield("Zurich") yield("Schaffhausen") yield("Stuttgart") x = city_generator() print x.next() print x.next() print x.next() print x.next() #print x.next() #there isnt a 5th element so you get a stopiteration error print "\n" cities = city_generator() for city in cities: print city print "\n" #list generator def fibonacci(n): """Fibonacci numbers generator, first n""" a, b, counter = 0, 1, 0 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 f = fibonacci(5) #yields the first 5 fibonacci lists as the programme calculates them print x, print #convert to celcius using list comprehension def fahrenheit(t): return ((float(9)/5)*t + 32) def celsius(t): return (float(5)/9*(t - 32)) temp = (36.5, 37, 37.5, 39) F = map(fahrenheit, temp) print F C = map(celsius, F) print C #max using reduce def max(values): return reduce(lambda a,b: a if (a>b) else b, values) print max([47, 11, 42, 13]) #min using reduce def min(values): return reduce(lambda a,b: a if (a<b) else b, values) print min([47, 11]) #add using reduce def add(values): return reduce(lambda a,b: a+b, values) print add([47, 11, 42, 13]) #subtract using reduce def sub(values): return reduce(lambda a,b: a-b, values) print sub([47, 11]) #multiply using reduce def mul(values): return reduce(lambda a,b: a*b, values) print mul([2,5]) #divide using reduce def div(values): return reduce(lambda a,b: a/float(b) if (b != 0 and a != 'Nan') else 'Nan', values) print div([47, 'Nan', 0, 11]) #find even numbers using filter def is_even(values): return filter(lambda x: x % 2 == 0, values) print is_even([47, 11, 42, 13]) #conversion using map def to_fahrenheit(values): return map(fahrenheit, values) print to_fahrenheit([0, 37, 40, 100]) #conversion using map def to_celsius(values): return map(celsius, values) print to_celsius([0, 32, 100, 212])
true
0c0de06a03d52d8cf86523b07153d27032dd3cb0
sedakurt/pythonProject
/venv/conditionals.py
786
4.21875
4
#comparison Operastors ''' print(1 < 1) print(1 <= 1) print(1 > 1) print(1 >= 1) print(1 == 1) print(1 != 1) ''' ##if, elif, else code block #if name = input("What is your name? ") if name == "Seda": print("Hello, nice to see you {}".format(name)) elif name == "Bayraktar": print("Hello, you are a surname!") elif name == "Kurt": print("Hi, {}, you are a second surname for Seda".format(name)) elif name != "Özcan": #en baştan conditionları çalıştırır yani bir order içerisinde akış devam edeceğinden ilk if e göre çalışır. Bu sorgu eğer koşullar arasında olmayan bir name değeri input olarak verirsem çalışacaktır. ''' What is your name? sdsdasda You are not Özcan! ''' print("You are not Özcan!") print("\nHave a nice day!")
false
4bb989ebaca1ed9e289611696a31e7db58cd04d1
tretyakovr/sobes-Lesson03
/Task-02.py
1,549
4.125
4
# Третьяков Роман Викторович # Факультет Geek University Python-разработки # Основы языка Python # Урок 3 # Задание 2: # Написать программу, которая запрашивает у пользователя ввод числа. На введенное число # она отвечает сообщением, целое оно или дробное. Если дробное — необходимо далее выполнить # сравнение чисел до и после запятой. Если они совпадают, программа должна возвращать # значение True, иначе False input_value = input('Введите число: ') if '.' in input_value: if input_value.count('.') == 1: if input_value.split('.')[0].isdigit() and input_value.split('.')[1].isdigit(): print('Введено число с плавающей точкой!') if input_value.split('.')[0] == input_value.split('.')[1]: print('Значения целой и дробной части совпадают!') else: print('Значения целой и дробной части отличаются!') else: print('В введенной строке присутствуют нечисловые символы!') else: print('Введено не числовое значение!') else: if input_value.isdigit(): print('Введено целое число!')
false
2d3fb98cd2c98c632c60fc9da686b6567c1ea68d
jaimedaniels94/100daysofcode
/day2/tip-calculator.py
402
4.15625
4
print("Welcome to the tip calculator!") bill = float(input("What was the total bill? $")) tip = int(input("What percentage tip would you like to give? 10, 12, or 15? ")) split = int(input("How many people will split the bill? ")) bill_with_tip = tip / 100 * bill + bill bill_per_person = bill_with_tip / split final_amount = round(bill_per_person, 2) print(f"Each person should pay ${final_amount})
true
17ec3f12074f33e8804dade2464a27e6c822602c
jaimedaniels94/100daysofcode
/day4/final.py
1,128
4.25
4
#Build a program to play rock, paper, scissors against the computer. import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' ascii = [rock, paper, scissors] print("READY TO ROCK, PAPER, SCISSORS?") player_num = int(input("Choose your weapon. \n0 for rock, 1 for paper, or 2 for scissors.\n")) if player_num > 2 or player_num < 0: print("Invalid entry. Play again.") else: print(f"You chose:\n{ascii[player_num]}") computer_num = random.randint(0, 2) print(f"Computer chose:\n{ascii[computer_num]}") if player_num == 0 and computer_num == 2: print("You win!") elif player_num == 2 and computer_num == 1: print("You win!") elif player_num == 1 and computer_num == 0: print("You win!") elif player_num == computer_num: print("It's a draw. Play again.") else: print("You lose. Hahah you lost to a computer.")
false
2b47e8987cc92f9069fa12915030329d764cf032
tomahim/project-euler
/python_solutions/problem3.py
780
4.125
4
from python_solutions.utils import timing @timing def compute_largest_prime_factor(value: int): denominator = 2 while denominator < value: disivion_result = value / denominator if disivion_result.is_integer(): value = disivion_result else: denominator += 1 return value if __name__ == '__main__': """ The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ example_value = 13195 example_answer = 29 assert example_answer == compute_largest_prime_factor(example_value) problem_value = 600851475143 result = compute_largest_prime_factor(problem_value) print(f'Largest prime factor of {problem_value} is : {result}')
true
c70b8b6d2966f6620ad280ca6cabd29bac4cadc1
Harrywekesa/Sqlite-database
/using_place_holders.py
562
4.1875
4
import sqlite3 #Get personal data from the user aand insert it into a tuple First_name = input("Enter your first name: ") Last_name = input("Enter your last name: ") Age = input("Enter your age: ") personal_data = (First_name, Last_name, Age) #Execute insert statement for supplied personal data with sqlite3.connect("place_holder.db") as conn: c = conn.cursor() c.execute("DROP TABLE IF EXISTS people") c.execute("CREATE TABLE people(First_name TEXT, Last_name TEXT, Age INT)") c.execute("INSERT INTO people VALUES(?, ?, ?)", personal_data)
true
19e67b26e33be4b1b1ee557c3c9cb8043c251ecd
cuitianfeng/Python
/python3基础/5.Python修炼第五层/day5预习/协程函数.py
2,905
4.28125
4
#yield: #1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器 #2:与ruturn功能类似,都可以返回值, # 但不同的是,return只能返回一次值,而yield可以返回多次值 #3:函数暂停与再继续运行的状态是有yield保存 # def func(count): # print('start') # while True: # yield count # count+=1 # # g=func(10) # # print(g) # print(next(g)) # print(next(g)) # # next(g) #yield的表达式形式的应用 # def eater(name): # print('%s 说:我开动啦' %name) # while True: # food=yield # print('%s eat %s' %(name,food)) # # alex_g=eater('alex') # # print(alex_g) # # next(alex_g) # print(next(alex_g)) # print('==========>') # next(alex_g) # # 用法 # def eater(name): # print('%s 说:我开动啦' %name) # food_list=[] # while True: # food=yield food_list # food_list.append(food) #['骨头','菜汤'] # print('%s eat %s' %(name,food)) # # alex_g=eater('alex') # # #第一阶段:初始化 # next(alex_g) #等同于alex_g.send(None) # print('========>') # # #第二阶段:给yield传值 # print(alex_g.send('骨头')) #1 先给当前暂停位置的yield传骨头 2 继续往下执行 ,直到再次碰到yield,然后暂停并且把yield后的返回值当做本次调用的返回值 # # print('========>') # print(alex_g.send('菜汤')) # print(alex_g.send('狗肉包子')) # # 函数上下切换运行 # def eater(name): # print('%s 说:我开动啦' %name) # food_list=[] # while True: # food=yield food_list # food_list.append(food) #['骨头','菜汤'] # print('%s eat %s' %(name,food)) # # def producer(): # alex_g=eater('alex') # #第一阶段:初始化 # next(alex_g) #等同于alex_g.send(None) # #第二阶段:给yield传值 # while True: # food=input('>>: ').strip() # if not food:continue # print(alex_g.send(food)) # # producer() #解决初始化问题 def init(func): def wrapper(*rags,**kwargs): g=func(*rags,**kwargs) next(g) return g return wrapper @init def eater(name): print('%s 说:我开动啦' %name) food_list=[] while True: food=yield food_list food_list.append(food) #['骨头','菜汤'] print('%s eat %s' %(name,food)) alex_g=eater('alex') #第一阶段:初始化 用init装饰器实现 就无需再next # next(alex_g) #等同于alex_g.send(None) print('========>') #第二阶段:给yield传值 print(alex_g.send('骨头')) #1 先给当前暂停位置的yield传骨头 2 继续往下执行 ,直到再次碰到yield,然后暂停并且把yield后的返回值当做本次调用的返回值 # print('========>')
false
b720f24465dda89e7ff7e6dd6f0fdde60fdb297d
vpreethamkashyap/plinux
/7-Python/3.py
1,594
4.21875
4
#!/usr/bin/python3 import sys import time import shutil import os import subprocess print ("\nThis Python script help you to understand Types of Operator \r\n") print ("Python language supports the following types of operators. \r\n") print ("Arithmetic Operators \r\n") print ("Comparison (Relational) Operators \r\n") print ("Assignment Operators \r\n") print ("Logical Operators \r\n") print ("Bitwise Operators \r\n") print ("Membership Operators \r\n") print ("Identity Operators \r\n") print ("Let us have a look on all operators one by one. \r\n") raw_input("Press enter to see how to aithrmetic operations occurs\n") var a = 50 var b = 20 var c c = a+b print("Addition of a & b is %d \r\n" %c) c = a-b print("Subtraction of a & b is %d \r\n" %c) c = a*b print("Multiplication of a & b is %d \r\n"%c) c = a/b print("Division of a & b is %d \r\n"%c) c = a%b print("Modulus of a & b is %d \r\n" %c) c = a**b print("Exponent of a & b is %d \r\n" %c) c = a//b print("Floor Division of a & b is %d \r\n" %c) raw_input("Press enter to see how to aithrmetic operations occurs\n") print("Python Comparison Operators\r\n") if(a == b): print(" a & b are same \r\n") if(a != b): print("a & b are not same\r\n") if(a > b): print("a is greater than b\r\n") if(a < b): print("b is greater than a\r\n") raw_input("Press enter to see how to Bitwise operations occurs\n") print ("\r\n Bit wise operator a&b %b \r\n" % (a&b)) print ("\r\n Bit wise operator a|b %b \r\n" % (a|b)) print ("\r\n Bit wise operator a^b %b \r\n" % (a^b)) print ("\r\n Bit wise operator ~a %b \r\n" % (~a))
true
f0054948c66568ce30cb8d9e94d723b5179de097
MrCat9/HelloPython
/list中替换元素.py
298
4.21875
4
#先删除,在添加==替换 #对list中的某一个索引赋值,就可以直接用新的元素替换掉原来的元素,list包含的元素个数保持不变。 L = ['Adam', 'Lisa', 'Bart'] print(L) #['Adam', 'Lisa', 'Bart'] #L[2] = 'Paul' L[-1] = 'Paul' print(L) #['Adam', 'Lisa', 'Paul']
false
db59ee60efb684c780262407c276487760cca73c
RoshaniPatel10994/ITCS1140---Python-
/Array/Practice/Beginin array in lecture.py
1,815
4.5
4
# Create a program that will allow the user to keep track of snowfall over the course 5 months. # The program will ask what the snowfall was for each week of each month ans produce a total number # of inches and average. It will also print out the snowfall values and list the highest amount of snow and the lowest amount of snow. # Declare variables snowfall = [0,0,0,0,0] index = int() one_month = float() total_inches = float() ave_inches = float() highest_inches = float() lowest_inches = float() ## #For loop ##for index in range(0, 5): ## #ask use for months snowfall ## one_month = float(input("Enter months of snowfall: ")) ## snowfall[index] = one_month ##print() snowfall = [10, 12, 14, 16, 18] for index in range(0, len(snowfall)): one_month = snowfall[index] print("Monthly snow fall : ", one_month) print() # Determin the total inches of snow fall for index in range(0, len(snowfall)): one_month = snowfall[index] total_inches = total_inches + one_month print(" total snowfall : ", total_inches) # average snowfall ave_inches = total_inches / (index + 1) print("Average snowfall: - " , ave_inches ) # Determine heighest value highest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month > highest_inches : highest_inches = one_month #endif print("highest snowfall: - " , highest_inches ) # Determine Lowest value lowest_inches = snowfall[0] for index in range(0, len(snowfall)): one_month = snowfall[index] if one_month < lowest_inches : lowest_inches = one_month print("lowest snowfall: - " , lowest_inches )
true
c3869c3a16815c7934e88768d75ee77a4bcc207d
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 5/LookingForDatesPython.py
1,479
4.40625
4
#Looking For Dates Program #Written by: Betsy Jenaway #Date: July 31, 2012 #This program will load an array of names and an array of dates. It will then #ask the user for a name. The program will then look for the user in the list. #If the name is found in the list the user will get a message telling them #the name was found and the person's birthdate. Otherwise they will get a #message telling them the name #was not found and to try again. NOTE: this #program differs from the Raptor program in that it continually asks the user #for a name until one is found in the list. #Declare Variables #Loading the array with names Friends = ["Matt", "Susan", "Jim", "Bob"] Dates = ["12/2/99", "10/15/95", "3/7/95", "6/24/93"] SearchItem = "nothing" FoundDate = "nothing" FoundIndex = 0 Index = 0 Flag = False #Look for the name and tell the user if the program found it #Keep asking the user for a name until one is found. while Flag == False: #Ask the user for the name to search for SearchItem = input("What is the name you are looking for? ") if SearchItem in Friends: #Find out what the index is for the Found Name FoundIndex = Friends.index(SearchItem) FoundDate = Dates[FoundIndex] Flag = True print("We found your name!") print(SearchItem, "'s Birthday is: ", FoundDate) else: print("Sorry we did not find your name. Please try again.") Flag = False
true
c4a91a468b3c96852d1365870230b15433f8007c
RoshaniPatel10994/ITCS1140---Python-
/Quiz's/quiz 2/chips.py
989
4.15625
4
# Roshani Patel # 2/10/20 # Chips # This program Calculate the cost of an order of chips. # Display program that will ask user how many bags of chips they want to buy. #In addition ask the user what size of bag. #If the bag is 8 oz the cost is 1.29 dollar if the bag is 16 oz then the cost is 3.59 dollars. #If bag is 32 oz then cost is $5.50. calculate the total cost of the order including tax at 6%. ## Declare Variable Size = 0 Qty = 0 Price = 0.0 Cost = 0.0 # Display Menu print("1 - 8 oz\t$1.29") print("2 - 16 oz\t$3.59") print("3 - 32 0z\t$5.50") # Bet Input Size = int(input("Enter size: ")) if Size == 1 or Size == 2 or Size == 3: Qty = int(input("Enter quantity: ")) # Calculate the COst if Size == 1: Price = 1.29 elif Size == 2: Price = 3.59 elif Size == 3: Price = 5.50 else: print("Enter 1, 2, or 3") Cost = Price * Qty * 1.06 # Display Cost print("Cost = $",format(Cost, '.2f'))
true
a95bdaa18d1b88eb8d178998f6af8f1066939c81
Lin-HsiaoJu/StanCode-Project
/stanCode Project/Wheather Master/weather_master.py
1,463
4.34375
4
""" File: weather_master.py Name: Jeffrey.Lin 2020/07 ----------------------- This program should implement a console program that asks weather data from user to compute the average, highest, lowest, cold days among the inputs. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ # This number controls when to stop the weather_master EXIT = -100 def main(): """ This program find and calculate the highest temperature, the lowest temperature, the average of daily temperature and the total days of cold day among the user inputs of everyday's temperature. """ print('stanCode "Weather Master 4.0"!') data = int(input('Next Temperature:(or '+str(EXIT)+' to quit)?')) if data == EXIT: print('No temperature were entered.') else: maximum = int(data) minimum = int(data) num = 1 sum = int(data) if maximum < 16: cold = 1 else: cold = 0 while True: data = int(input('Next Temperature:(or -100 to quit)?')) if data == EXIT: break else: sum += data num += 1 if data < 16: cold += 1 if data >= maximum: maximum = data if data <= minimum: minimum = data average = float(sum/num) print('Highest Temperature = ' + str(maximum)) print('Lowest Temperature = ' + str(minimum)) print('Average = ' + str(average)) print(str(cold) + ' cold day(s)') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
92e0031f054add61799cd4bfcd81a835e705af0d
ruthvika-mohan/python_scripts-
/merge_yearly_data.py
1,002
4.125
4
# Import required modules # Glob module finds all the pathnames matching a specified pattern # Pandas required to do merge operation # chdir() method in Python used to change the current working directory to specified path. from os import chdir from glob import glob import pandas as pdlib # Move to the path that holds our CSV files csv_file_path = 'C:\folder_containing_csv_files' chdir(csv_file_path) # List all CSV files in the working directory list_of_files = [file for file in glob('*.csv')] print(list_of_files) """ Function: Produce a single CSV after combining all files """ def produceOneCSV(list_of_files,file_out): # Consolidate all CSV files into one object result_obj = pdlib.concat([pdlib.read_csv(file,header = 0,encoding = 'cp1252') for file in list_of_files],ignore_index = True) # Convert the above object into a csv file and export result_obj.to_csv(file_out) file_out = "MergedOutput.csv" produceOneCSV(list_of_files,file_out)
true
a29e29d8f4e58d67a3d7cf38132b587cb8c27822
dinulade101/ECE322Testing
/command/cancelBookingCommand.py
2,224
4.3125
4
''' This file deals with all the commands to allow the user to cancel bookings. It will initially display all the user's bookings. Then the user will select the number of the booking displayed to cancel. The row of the booking in the db will be removed. The member who's booking was canceled will get an automated message as well. ''' import sqlite3 import re import sys from command.command import Command from book_rides.cancel_booking import CancelBooking class CancelBookingCommand(Command): def __init__(self, cursor, email): super().__init__(cursor) self.email = email self.cb = CancelBooking(cursor) def menu(self): print(''' Cancel bookings:\n Press Ctrl-c to return to menu\n''') rows = self.cb.get_member_bookings(self.email) if len(rows) == 0: print("You do not have any bookings!") return valid_bno = set() for row in rows: valid_bno.add(row[0]) print("\nYour bookings:\n") self.display_page(0, rows, valid_bno) def cancel_booking(self,bno): # delete the booking and create a message for the booker self.cb.cancel_booking(self.email, bno) print('Booking canceled successfully!') def display_page(self, page_num, rows, valid_bno): page = rows[page_num*5: min(page_num*5+5, len(rows))] for row in page: print("Booking No. {0} | User: {1} | Cost: {2} | Seats: {3} | Pick up: {4} | Drop off: {5}".format(row[0], row[1], row[3], row[4], row[5], row[6])) if (page_num*5+5 < len(rows)): user_input = input("To delete a booking, please enter the booking number. To see more bookings enter (y/n): ") if (user_input == 'y'): self.display_page(page_num+1, rows, valid_bno) return else: print() user_input = input("To cancel a booking, please enter the booking number: ") if user_input.isdigit() and int(user_input) in valid_bno: print("Canceled the following booking with bno: " + user_input) self.cancel_booking(user_input) else: print("Invalid number entered")
true
3735f2e08803537b4f8c1ba5fa4ad92e6109e16b
Jacalin/Algorithms
/Python/hash_pyramid.py
661
4.5
4
''' Implement a program that prints out a double half-pyramid of a specified height, per the below. The num must be between 1 - 23. Height: 4 # # ## ## ### ### #### #### ''' def hash_pyramid(): # request user input, must be num bewtween 1 - 23 n = int(input("please type in a number between 1 - 23: ")) # check if num is in bounds if n > 23 or n < 1: n = int(input("please type in a number between 1 - 23: ")) # if num in bounds, loop through usernum(n), and print properly formated pyramid. else: for i in range(1,n+1): print (((" " * ((n - (i-1)) - 1)) + ("#" * i) ) , " " , ("#" * i) )
true
31fc3087cab6005638007c911291d6c23ae293ee
kyledavv/lpthw
/ex24.py
1,725
4.125
4
print("Let's practice everything.") print('You\'d need to know \'bout escapes with \\ that do:') print('\n newlines and \t tabs.') poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print("--------") print(poem) print("--------") five = 10 - 2 + 3 - 6 print(f"This should be five: {five}") def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 1000 beans, jars, crates = secret_formula(start_point) #remember that this is another way to format a string print("With a starting point of: {}".format(start_point)) #it's just like with an f"" string print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.") start_point = start_point / 10 print("We can also do that this way:") formula = secret_formula(start_point) #this is an easy way to apply a list to a format string print("We'd have {} beans, {} jars, and {} crates.".format(*formula)) print("Now to practice with my work schedule and payment per week.") chad = 65 * 3 jacinda = 65 raina = 65 * 2 jrs = 25 * 12 syd = 65 payment = chad + jacinda + raina + jrs + syd print("\tThis is the gross amount that I earn from my private lessons and juniors.") print("===>", payment) print("This is the payment after the percentage is taken out.") actual_pmt = payment * .65 print("\t====>", actual_pmt) lost_pmt = payment - actual_pmt print(f"This is the amount I lost from the percentage taken out: {lost_pmt}") print("Country Club's really get you with what they take out. \n:-(")
true
aa673ad99e3adc6a02d9e49a1c7d6b9d82ad2d2d
rawswift/python-collections
/tuple/cli-basic-tuple.py
467
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # create tuple a = ("one", "two", "three") # print 'em print a # how many node/element we have? print len(a) # 3 # print using format print "Counting %s, %s, %s..." % a # iterate for x in a: print x # print value from specific index print a[1] # 'two' # create another tuple (using previous tuple) b = (a, "four") print b[1] # 'four' print b[0][2] # 'three' # how many node/element we have? print len(b) # 2
true
8829140909b516941d6ffc563cc083262210d3a0
v200510/Python_basics_and_application
/3.3 task-3.py
452
4.15625
4
# 3.3 Регулярные выражения в Python # Вам дана последовательность строк. # Выведите строки, содержащие две буквы "z", между которыми ровно три символа. # Sample Input: # zabcz # zzz # zzxzz # zz # zxz # zzxzxxz # Sample Output: # zabcz # zzxzz import re, sys [print(line.rstrip()) for line in sys.stdin if re.search(r'z.{3}z', line)]
false
5caf2defe75b91c024c097d908ce5ed20c0b02e5
RianMarlon/Python-Geek-University
/secao5_estruturas_condicionais/exercicios/questao19.py
428
4.25
4
""" 19) Faça um programa para verificar se um determinado número inteiro é divisível por 3 ou 5, mas não simultaneamente pelos dois. """ numero = int(input("Digite um número: ")) if numero % 3 == 0 and not (numero % 5 == 0): print("Divisível por 3.") elif numero % 5 == 0 and not(numero % 3 == 0): print("Divisível por 5.") else: print("Não divisível por 3 ou 5 / Não pode ser divisível pelos dois ")
false
d798a6cdfe7e3f785f44ceee8e19daf6f57693c2
RianMarlon/Python-Geek-University
/secao5_estruturas_condicionais/exercicios/questao2.py
386
4.15625
4
""" 2) Leia um número fornecido pelo usuário. Se esse númerro for positivo, calcule a raiz quadrada do número. Se o número for negativo, mostre uma mensagem dizendo que o número é inválido. """ numero = int(input("Digite um número: ")) if numero > 0: print(f"\n{numero ** 2}") elif numero < 0: print("\nNúmero inválido") else: print("\nNúmero igual a zero")
false
0d0a9b18fede86ea9b3afec3a588bc3920856e0e
RianMarlon/Python-Geek-University
/secao5_estruturas_condicionais/exercicios/questao11.py
592
4.125
4
""" 11) Escreva um programa que leia um número inteiro maior do que zero e devolva, na tela, a soma de todos os seus algarismos. Por exemplo, ao número 251 corresponderá o valor 8 (2 + 5 + 1). Se o número lido não dor maior do que zero, programa terminará com a mensagem 'Número inválido' """ numero = int(input("Digite um número inteiro maior que zero: ")) print() if numero > 0: numero = str(numero) soma = 0 for indice in range(len(numero)): soma += int(numero[indice]) print(f"A soma de seus algorismos é {soma}") else: print('Número inválido')
false
ddbad1dbb4c52686a837700662e562d5a10fe720
RianMarlon/Python-Geek-University
/secao3_introducao/recebendo_dados.py
973
4.15625
4
""" Recebendo dados do usuário input() -> Todo dado recebido via input é do tipo String Em Python, string é tudo que estiver entrw: - Aspas simples; - Aspas duplas; - Aspas simples triplas; - Aspas duplas triplas; Exemplos: - Aspas Simples -> 'Angelina Jolie' - Aspas duplas -> "Angelina Jolie" - Aspas simples tripla -> '''Angelina Jolie """ # - Aspas duplas triplas -> """Angelina Jolie""" # Entrada de dados nome = input("Qual o seu nome?") # Exemplo de print 'antigo' 2x # print("Seja bem-vindo %s" %(nome)) # Exemplo de print 'moderno' 3x # print("Seja bem-vindo {0}".format(nome)) # Exemplo de print 'mais atual' 3.7 print(f"Seja bem-vindo {nome}") idade = int (input("Qual sua idade?")) # Processamento # Saida # Exemplo de print 'antigo' 2x # print("O %s tem %d anos" %(nome, idade)) # Exemplo de print 'moderno' 3x # print("O {0} tem {1} anos".format(nome, idade)) # Exemplo de print 'mais atual' 3.7 print(f"O {nome} tem {idade} anos") print(f"O {nome} nasceu {2019 - idade}")
false
5f3b816c0dad6a85f6f79ed2f49a928aff9dc750
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios1/questao23.py
740
4.125
4
""" 23) Ler dois conjuntos de números reais, armazenando-os em vetores e calcular o produto escalar entre eles. Os conjuntos têm 5 elementos cada. Imprimir os dois conjuntos e o produto escalar, sendo que o produto escalar é dado por: x1 * y1 + x2 * y2 + ... + xn * yn """ lista1 = [] lista2 = [] for i in range(5): lista1.append(float(input("Digite um valor para o primeiro vetor: "))) print() for i in range(5): lista2.append(float(input("Digite um valor para o segundo vetor: "))) print(f"\nPrimeiro vetor: {lista1}") print(f"Segundo vetor: {lista2}") produto_escalar = 0 for i in range(5): produto_escalar += (lista1[i] * (i+1)) * (lista2[i] * (i+1)) print(f"Produto escalar dos dois conjuntos: {produto_escalar}")
false
a5ea00a5b2bb36240557f80633cf45fcbd83f9fa
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios1/questao7.py
391
4.1875
4
""" 7) Escreva um programa que leia 10 números inteiros e os armazene em um vetor. Imprima o vetor, o maior elemento e a posição que ele se encontra. """ lista = [] for i in range(10): lista.append(int(input("Digite um número: "))) print(f"\nVetor: {lista}") print(f"Maior elemento: {max(lista)}") print(f"Posição em que se encotra o maior elemento: {lista.index(max(lista))}")
false
87a50a44cff3abac564d6b98587beb4d73654016
RianMarlon/Python-Geek-University
/secao8_funcoes/exercicios/questao28.py
1,405
4.46875
4
""" 28) Faça uma função que receba como parâmetro o valor de um ângulo em grau e calcule o valor do cosseno desse ângulo usando sua respectiva série de Taylor: cos x = E(n=0) = (-1) ^ n / (2 * n)! * (x ^ 2 * n) = 1 - (x^2 / 2!) + (x^4 / 4!) - ... para todo x, onde x é o valor do ângulo em radianos. Considerar pi = 3.141593 e n variando de 0 até 5. """ from math import factorial def cosseno(angulo): """ Função que recebe o valor de um ângulo em graus, trasnforma o ângulo de graus para radianos e calcula o valor do seno do ângulo em radianos usando a série de Taylor. Retorna uma mensagem informando o resultado do calculo :param angulo: Recebe o valor do ângulo em graus :return: Retorna uma mensagem informando o valor do ângulo em radianos e o resultado do cálculo. Se o ângulo for negativo, retorna uma mensagem informando que o ângulo é inválido """ if angulo > 0: pi = 3.141593 x = angulo * pi / 180 cos = 0 for n in range(6): numerador = x ** (2 * n) denominador = factorial(2 * n) cos += (-1) ** n / denominador * numerador return f"{angulo}° em radianos: {x}" \ f"\nCosseno de {x}: {cos}" return "Valor inválido" angulo_em_graus = int(input("Digite o valor do ângulo em graus: ")) print(f"\n{cosseno(angulo_em_graus)}")
false
2b6fb7c8bed6f3e072a808a9b3ee9c5dce5d89f3
RianMarlon/Python-Geek-University
/secao8_funcoes/exercicios/questao27.py
1,388
4.375
4
""" 27) Faça uma função que receba como parâmetro o valor de um ângulo em graus e calcule o valor do seno desse ângulo usando sua respectiva serie de Taylor: sin x = E (n = 0) = (-1) ^ n / (2n + 1)! * x ^ 2n + 1 = x - (x ^ 3 / 3!) + (x ^ 5 / 5!) - ... para todo x, onde x é o valor do ângulo em radianos. Considerar r = 3.141593 e n variando de 0 até 5 """ from math import factorial def seno(angulo): """ Função que recebe um valor de um ângulo em graus, transforma o ângulo em graus para radianos e calcula o valor do seno do ângulo em radianos usando a série de Taylor. Retorna o resultado do calculo :param angulo: Recebe o valor do ângulo em graus :return: Retorna uma mensagem informando o valor do ângulo em radianos e o resultado do cálculo. Se o ângulo não for negativo, retorna uma mensagem informando que o ângulo é inválido. """ if angulo > 0: pi = 3.141593 x = angulo * pi / 180 sen = 0.0 for n in range(6): numerador = x ** (2 * n + 1) denominador = factorial(2 * n + 1) sen += (-1) ** n / denominador * numerador return f"{angulo}° em radianos: {x}" \ f"\nSeno de {x}: {sen}" return "Valor inválido" angulo_em_graus = int(input("Digite o valor do ângulo em graus: ")) print(f"\n{seno(angulo_em_graus)}")
false
6d586cda0717f45a710b3ad05c1a464ea024d040
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios1/questao31.py
574
4.21875
4
""" 31) Faça um programa que leia dois vetores de 10 elementos. Crie um vetor que seja a união entre os 2 vetores anteriores, ou seja, que contém os números dos dois vetores. Não deve conter números repetidos. """ vetor1 = [] vetor2 = [] for i in range(10): vetor1.append(int(input("Digite um elemento do primeiro vetor: "))) print() for i in range(10): vetor2.append(int(input("Digite um elemento do segundo vetor: "))) conjunto1 = set(vetor1) conjunto2 = set(vetor2) uniao = conjunto1.union(conjunto2) print(f"\nOs números dos dois vetores: {uniao}")
false
0b86829b854e0c4d7ee2a34513d96bcb4dac423c
RianMarlon/Python-Geek-University
/secao13_leitura_escrita_de_arquivos/seek_e_cursors.py
1,665
4.4375
4
""" Seek e Cursors seek() -> é utilizada para moviementar o cursor pelo arquivo arquivo = open('texto.txt', encoding='utf-8') print(arquivo.read()) # seek() -> A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela # recebe um parâmetro que indica onde queremos colocar o cursor # Movimentando o cursor pelo arquivo com a função seek() -> Procurar arquivo.seek(0) print(arquivo.read()) arquivo.seek(22) print(arquivo.read()) # readline() -> Função que lê o arquivo linha a (readline -> lê linha) ret = arquivo.readline() print(type(ret)) print(ret) print(ret.split(' ')) # readlines() linhas = arquivo.readlines() print(len(linhas)) # OBS: Quando abrimos um arquivo com a função open() é criada uma conexão entre o arquivo # no disco do computador e o seu programa. Esssa conexão é chamada de streaming. Ao finalizar # o trabalho com o arquivo devemos fechar a conexão. Para isso devemos usar a função close() Passos para se trabalhar com um arquivo 1 - Abrir o arquivo; 2 - Trabalhar o arquivo; 3 - Fechar o arquivo; # 1 - Abrir o arquivo arquivo = open('texto.txt', encoding='utf-8') # 2 - Trabalhar o arquivo print(arquivo.read()) print(arquivo.closed) # False Verifica se o arquivo está aberto ou fechado # 3 - Fechar o arquivo arquivo.close() print(arquivo.closed) # True Verifica se o arquivo está aberto ou fechado print(arquivo.read()) # OBS: Se tentarmos manipular o arquivo após seu fechamento, teremos um ValueError """ arquivo = open('texto.txt', encoding='utf-8') # Com a função read, pdoemos limitar a quantidade de caracteres a serem lidos no arquivo print(arquivo.read(50))
false
1e739098f5ed23750ecf47efd91e4f4d75c0ddc7
RianMarlon/Python-Geek-University
/secao13_leitura_escrita_de_arquivos/exercicio/questao7.py
1,425
4.53125
5
""" 7) Faça um programa que receba do usuário um arquivo texto. Crie outro arquivo texto contendo o texto do arquivo de entrada, mas com as vogais substituídas por '*' """ def substitui_vogais(txt): """Recebe um texto e retorna o mesmo com as vogais substituidas por '*'. Caso não seja passado um texto por parâmetro, retornará uma string vazia""" try: vogais = ['a', 'e', 'i', 'o', 'u'] for vogal in vogais: txt = txt.replace(vogal.lower(), "*") txt = txt.replace(vogal.upper(), "*") return txt except AttributeError: return "" if __name__ == "__main__": nome_arquivo = str(input("Digite o caminho do arquivo ou o seu nome " "(caso o arquivo esteja no mesmo local do programa): ")) nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt" try: with open(nome_arquivo, "r", encoding="utf-8") as arquivo: with open("arquivos/arq2.txt", "w", encoding="utf-8") as arquivo_novo: arquivo_novo.write(substitui_vogais(arquivo.read())) print("\nTexto inserido no arquivo com sucesso!") except FileNotFoundError: print("\nO arquivo não foi encontrado ou o programa não tem permissão para criar um diretório/pasta!") except OSError: print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
false
59ac398bcd634b7e5e4e8456fd8de56da39ae1ed
RianMarlon/Python-Geek-University
/secao8_funcoes/exercicios/questao14.py
1,181
4.40625
4
""" 14) Faça uma função que receba a distância em Km e a quantidade de litros de gasolina consumidos por um carro em um percurso, calcule o consumo em km/l e escreva uma mensagem de acordo com a tabela abaixo: | CONSUMO | (km/l) | MENSAGEM | menor que | 8 | Venda o carro! | entre | 8 e 12 | Econômico | maior que | 12 | Super econômico! """ def consumo_km_l(distancia, gasolina): """ Função que recebe a distância percorrida por um carro e a quantidade da gasolina consumida por um carro, e imprimi uma mensagem de acordo com a quantidade de quilometros por litros usado :param distancia: Recebe a distância em quilometros percorrida pelo carro :param gasolina: Recebe a quantidade de gasolina em litros """ consumo = distancia / gasolina print() if consumo < 8: print("Venda o carro!") elif (consumo >= 8) and (consumo <= 14): print("Econômico") elif consumo > 12: print("Super econômico!") distan = float(input("Digite a distância em km: ")) gasoli = float(input("Digite o consumo da gasolina consumida pelo carro: ")) consumo_km_l(distan, gasoli)
false
1063c487861ca1a0714420b887f4bc406225dc8f
RianMarlon/Python-Geek-University
/secao8_funcoes/exercicios/questao7.py
694
4.28125
4
""" 7) Faça uma função que receba uma temperatura en graus Celsius e retorne-a convertida em graus Fahrenheit. A fórmula de conversão é: F = C * (9.0/5.0) + 32.0, sendo F a temperatura em Fahrenheit e C a temperatura em Celsius. """ def converte_em_fahrenheit(celsius): """ Função que recebe uma temperatura em graus Celsius e retorna em graus Fahrenheit :param celsius: recebe os graus celsius :return: retorna o resultado da conversão de graus Celsius em Fahrenheit """ return celsius * (9.0/5.0) + 32.0 celsius1 = float(input("Digite a temperatura em graus Celsius: ")) print(f"\nTemperatura em graus Fahrenheit: {converte_em_fahrenheit(celsius1)}°F")
false
e632ec6cea6fbec7fe61eff27d85067309591f0b
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios2/questao12.py
717
4.1875
4
""" 12) Leia uma matriz de 3 x 3 elementos. Calcule e imprima a sua transposta. """ lista1 = [] for i in range(3): lista2 = [] for j in range(3): num = int(input("Digite um número: ")) lista2.append(num) lista1.append(lista2) print() lista_transposta = [] # Imprimindo a matriz escrita pelo usuário e adicionando os valores na matriz transposta for i in range(3): lista = [] for j in range(3): print(lista1[i][j], end=' ') lista.append(lista1[j][i]) print() lista_transposta.append(lista) print(f"\nLista transposta: {lista_transposta}") for i in range(3): for j in range(3): print(lista_transposta[i][j], end=' ') print()
false
3ac4d3fe40faded55b34fdb5d4ee7f4d96b46294
RianMarlon/Python-Geek-University
/secao13_leitura_escrita_de_arquivos/exercicio/questao2.py
746
4.15625
4
""" 2) Faça um programa que receba do usuário um arquivo texto e mostre na tela quantas linhas esse arquivo possui """ nome_arquivo = str(input("Digite o caminho do arquivo ou o nome do mesmo " "(caso o arquivo esteja no mesmo local do programa): ")) nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt" try: with open(nome_arquivo, "r", encoding='utf-8') as arquivo: texto = arquivo.read() quebra_de_linha = len(texto.splitlines()) print(f"\nO arquivo possui {quebra_de_linha + 1} linhas!") except FileNotFoundError: print("\nArquivo informado não encontrado!") except OSError: print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
false
05f3c2709b5ef395ec8a39d1160720d98592dfd2
RianMarlon/Python-Geek-University
/secao7_colecoes/exercicios2/questao14.py
847
4.15625
4
""" 14) Faça um prorgrama para gerar automaticamente números entre 0 e 99 de uma cartela de bingo. Sabendo que cada cartela deverá conter 5 linhas de 5 números, gere estes dados de modo a não ter números repetidos dentro das cartelas. O programa deve exibir na tela a cartela gerada. """ from random import randint lista1 = [] lista3 = [] while len(lista1) < 5: lista2 = [] while len(lista2) < 5: num = randint(0, 99) # Se o número aleatório não existir na lista3, adicione o valor na lista3 e adicione o valor na matriz lista2 # Assim, o número não irá se repetir em nenhuma matriz if num not in lista3: lista3.append(num) lista2.append(num) lista1.append(lista2) for i in range(5): for j in range(5): print(lista1[i][j], end=' ') print()
false
d1f57a43c27c0cfed1a993c42a06ca921968aa10
RianMarlon/Python-Geek-University
/secao13_leitura_escrita_de_arquivos/exercicio/questao6.py
1,464
4.40625
4
""" 6) Faça um programa que receba do usuário um arquivo texto e mostre na tela quantas vezes cada letra do alfabeto aparece dentro do arquivo. """ def qtd_letras(txt): """Recebe um texto e imprimi na tela cada letra do alfabeto e a quantidade de vezes que a mesma aparece no texto. Caso não seja passado um texto, a função imprimirá uma mensagem informando que o valor recebido por parâmetro não é um texto""" txt = txt.lower() letras = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] print() try: for letra in letras: print(f"A letra {letra} se repete {txt.count(letra)} vezes no texto") except AttributeError: print("O valor recebido por parâmetro não é um texto/string") if __name__ == "__main__": nome_arquivo = str(input("Digite o caminho do arquivo ou o seu nome " "(caso o arquivo esteja no mesmo local que do arquivo): ")) nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt" try: with open(nome_arquivo, "r", encoding="utf-8") as arquivo: texto = arquivo.read().lower() qtd_letras(texto) except FileNotFoundError: print("\nArquivo informado não encontrado!") except OSError: print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
false
05dbf2f6923071eccad18dc65d97a3e0baab3333
schlangens/Python_Shopping_List
/shopping_list.py
632
4.375
4
# MAKE sure to run this as python3 - input function can cause issues - Read the comments # make a list to hold onto our items shopping_list = [] # print out instruction on how to use the app print('What should we get at the store?') print("Enter 'DONE' to stop adding items.") while True: # ask for new items # if using python 2 change this to raw_input() new_item = input("Item: ") # be able to quit the app if new_item == 'DONE': break # add new items to our list shopping_list.append(new_item) # print out the list print("Here's your list:") for item in shopping_list: print(item)
true
ed5c9669052efef4d7003952c0a7f20437c5109d
alma-frankenstein/Rosalind
/RNA.py
284
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Transcribing DNA to RNA #Given: A DNA string t #Return: The transcribed RNA string of t . filename = 'rosalind_rna.txt' with open(filename) as file_object: contents = file_object.read() rna = contents.replace('T', 'U') print(rna)
true
6a8203f812ccc5b829b20e7698246d8c327ac3af
dudejadeep3/python
/Tutorial_Freecodecamp/11_conditionals.py
530
4.34375
4
# if statement is_male = True is_tall = False if is_male and is_tall: print("You are a tall male.") elif is_male and not is_tall: print("You are a short male") elif not is_male and is_tall: print("You are not a male but tall") else: print("You are not male and not tall") def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num3: return num2 else: return num3 print(max_num(4,1,10)) # we can compare strings also == is used for equal
true
dbfd05d60911bf8141c1bf910cad8229915e420a
dudejadeep3/python
/Tutorial_Freecodecamp/06_input.py
467
4.25
4
# Getting the input from the users name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + "! You are "+age) # Building a basic calculator num1 = input("Enter a number:") num2 = input("Enter another number:") result = float(num1) + float(num2); # we could use int() but it will remove decimal points print(result); # if we int() and pass number with decimal then we will get # an error and program will stop. # result = int(5.5)
true
0966afba7b408899717116feb36d960434974d7b
CODEREASYPYTHON/Calculator
/easy_calculator.py
661
4.21875
4
while True: number_one = input("Enter the first number:") query = input("Which arithmetic operation should be carried out? (+,-,/.,*):") number_two = input("Enter the second number:") Equal_1 = float(number_one) Equal_2 = float(number_two) if query == "+": print("Your result",Equal_1+Equal_2) if query == "-": print("Your result",Equal_1-Equal_2) if query == "*": print("Your result",Equal_1*Equal_2) if query == "**": print("Your result",Equal_1**Equal_2) if query == "/": print("Your result",Equal_1/Equal_2) if query == "//": print("Your result",Equal_1//Equal_2)
false
9b206c69562b967ae955947990826b5861a68255
franwatafaka/funciones_python
/ejemplos_clase/ejemplo_5.py
2,452
4.4375
4
# Funciones [Python] # Ejemplos de clase # Autor: Inove Coding School # Version: 2.0 # Ejemplos de parámetros ocultos en funciones conocidas def cantidad_letras(lista_palabras): for palabra in lista_palabras: cantidad_letras = len(palabra) print('Cantidad de letras de {}: {}'.format(palabra, cantidad_letras)) def ordenar_palabras(lista_palabras, operador): ''' Ordenar palabras alfabeticamente o por cantidad de letras de mayor a menor ''' if operador == 1: lista_palabras.sort(reverse=True) elif operador == 2: lista_palabras.sort(reverse=True, key=len) # lista_palabras.sort(reverse=True, key=cantidad_letras) else: print('Operador ingresado', operador, 'incorrecto, ingrese 1 o 2') print(lista_palabras) def max_max(lista_palabras): # Ejemplo de diferentes formas de utilizar max # Buscamos la palabra alfabéticamente mayor max_alfabeticamente = max(lista_palabras) print('La palabra alfabéticamente más grande:', max_alfabeticamente) # Buscamos la palabra con mayor cantidad de letras # Para eso cambiamos el criterio de búsqueda "key" # por búsqueda por cantidad de letras "len" max_tamaño = max(lista_palabras, key=len) print('La palabra más larga:', max_tamaño) # Con count podemos contar cuantas veces # aparece "te" en la lista de palabras cantidad_max = lista_palabras.count('te') print('La palabra "te" aparece {} veces'.format(cantidad_max)) # Buscamos la palabra que más se repite en la lista # cambiando el criterio de búsqueda "key" por el función # count que se aprovechó antes. max_repeticiones = max(lista_palabras, key=lista_palabras.count) print('La palabra con más repetición en la lista es "{}"'.format(max_repeticiones)) if __name__ == '__main__': print("Bienvenidos a otra clase de Inove con Python") lista_palabras = ['vida', 'te', 'inove', 'dia', 'te'] # Cuantas letras tiene cada palabra en la lista? cantidad_letras(lista_palabras) # Ordenar las palabras de mayor a menor por orden alfabético ordenar_palabras(lista_palabras, 1) # Ordenar las palabras de mayor a menor por cnatidad de letras ordenar_palabras(lista_palabras, 2) # Ingresar mal el operador ordenar_palabras(lista_palabras, 56) # Parámetros ocultos por defecto de la función max max_max(lista_palabras)
false
cf717c597321786c758d22056fd1c90eb8d4b175
lima-oscar/GTx-CS1301xIV-Computing-in-Python-IV-Objects-Algorithms
/Chapter 5.1_Objects/Burrito5.py
1,764
4.46875
4
#In this exercise, you won't edit any of your code from the #Burrito class. Instead, you're just going to write a #function to use instances of the Burrito class. You don't #actually have to copy/paste your previous code here if you #don't want to, although you'll need to if you want to write #some test code at the bottom. # #Write a function called total_cost. total_cost should take #as input a list of instances of Burrito, and return the #total cost of all those burritos together as a float. # #Hint: Don't reinvent the wheel. Use the work that you've #already done. The function can be written in only five #lines, including the function declaration. # #Hint 2: The exercise here is to write a function, not a #method. That means this function should *not* be part of #the Burrito class. #If you'd like to use the test code, paste your previous #code here. #Write your new function here. def total_cost(burrito_list): total_cost = 0 for burrito_n in burrito_list: total_cost += burrito_n.get_cost() return total_cost #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. Note that these lines #will ONLY work if you copy/paste your Burrito, Meat, #Beans, and Rice classes in. # #If your function works correctly, this will originally #print: 28.0 #burrito_1 = Burrito("tofu", True, "white", "black") #burrito_2 = Burrito("steak", True, "white", "pinto", extra_meat = True) #burrito_3 = Burrito("pork", True, "brown", "black", guacamole = True) #burrito_4 = Burrito("chicken", True, "brown", "pinto", extra_meat = True, guacamole = True) #burrito_list = [burrito_1, burrito_2, burrito_3, burrito_4] #print(total_cost(burrito_list))
true
09c67cc5a452e5af7021221d589c49e17f37d7b6
panhboth111/AI-CODES
/pandas/4.py
394
4.34375
4
#Question: Write a Pandas program to compare the elements of the two Pandas Series. import pandas as pd ds1 = pd.Series([2, 4, 6, 8, 10]) ds2 = pd.Series([1, 3, 5, 7, 10]) print("Series1:") print(ds1) print("Series2:") print(ds2) print("Compare the elements of the said Series:") print("Equals:") print(ds1 == ds2) print("Greater than:") print(ds1 > ds2) print("Less than:") print(ds1 < ds2) #
true
2bf7cbe5bcecf17ebaf46be2f5420ebbde0163b0
panhboth111/AI-CODES
/pandas/16.py
530
4.28125
4
"""Question: Write a Pandas program to get the items of a given series not present in another given series. Sample Output: Original Series: sr1: 0 1 1 2 2 3 3 4 4 5 dtype: int64 sr2: 0 2 1 4 2 6 3 8 4 10 dtype: int64 Items of sr1 not present in sr2: 0 1 2 3 4 5 dtype: int64 """ import pandas as pd sr1 = pd.Series([1, 7, 3, 4, 5]) sr2 = pd.Series([2, 4, 6, 8, 10]) print("Original Series:") print("sr1:") print(sr1) print("sr2:") print(sr2) print("\nItems of sr1 not present in sr2:") result = sr1[~sr1.isin(sr2)] print(result)
true
e133ba7d9f305a476985d6d2659aefb7b91ddb51
MariinoS/projectEuler
/problem1.py
571
4.125
4
# Project Euler: Problem 1 Source Code. By MariinoS. 5th Feb 2016. """ # task: If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # # My Solution: """ list = range(1000) def sum_of_multiples(input): total = 0 for i in input: if i % 3 == 0 or i % 5 == 0: total = total + i return total print sum_of_multiples(list) """ # The script finishes in O.O37s. # The answer = 233168 """
true
4ede0c5bea3a9e14b82675234a3f43f5512d4a8f
datascience-bitacademy/python-basics
/03/04.object_copy.py
766
4.28125
4
# 레퍼런스 복사 import copy a = 1 b = a a = [1, 2, 3] b = [4, 5, 6] x = [a, b, 100] y = x print(x) print(y) print(x is y) # 얕은(swallow) 복사 a = [1, 2, 3] b = [4, 5, 6] x = [a, b, 100] y = copy.copy(x) print(x) print(y) print(x is y) print(x[0] is y[0]) # 깊은(deep) 복사 a = [1, 2, 3] b = [4, 5, 6] x = [a, b, 100] y = copy.deepcopy(x) print(x) print(y) print(x is y) print(x[0] is y[0]) # 깊은복사가 복합객체만을 생성하기 때문에 # 복합객체가 한개만 있는 경우에는 # 얕은복사와 깊은복사는 별 차이가 없다. a = ['hello', 'world'] b = copy.copy(a) print(a) print(b) print(a is b) print(a[0] is b[0]) a = ['hello', 'world'] b = copy.deepcopy(a) print(a) print(b) print(a is b) print(a[0] is b[0])
false
2834050573db40f828573a3a5e88137c4851382e
P-RASHMI/Python-programs
/Functional pgms/QuadraticRoots.py
979
4.3125
4
''' @Author: Rashmi @Date: 2021-09-17 19:10:01 @Last Modified by: Rashmi @Last Modified time: 2021-09-17 19:36:03 @Title : A program that takes a,d,c from quadratic equation and print the roots” ''' import math def deriveroots(a,b,c): """to calculate roots of quadratic equation parameter : a,b,c return value : roots""" #To find determinent detrimt = b * b - 4 * a * c sqrt_val = math.sqrt(abs(detrimt)) if detrimt > 0: print("real and different") root1 = (-b + sqrt_val)/(2*a) root2 = (-b - sqrt_val)/(2*a) print("roots are: ", root1 , root2 ) elif detrimt == 0: print("roots are real and same") print("root is", -b /(2*a)) else: print("roots are complex") a = int(input("enter the x* x coefficient")) b = int(input("enter the x coefficient")) c = int(input("enter the constant")) if (a == 0): print("give the corect quadratic equation") else: deriveroots(a,b,c)
true
a40e98c3231f4f3a16e86dfe2eeb9951ae29b05d
P-RASHMI/Python-programs
/oops_sample/Innerclass.py
764
4.5
4
''' @Author: Rashmi @Date: 2021-09-20 17:10 @Last Modified by: Rashmi @Last Modified time: 2021-09-20 17:17 @Title : sample program to perform Concept of inner class and calling inner class values,inner class ''' class Student: def __init__(self,name,rollno): self.name = name self.rollno = rollno self.lap = self.Laptop() def show(self): print(self.name,self.rollno) class Laptop: def __init__(self): self.brand = 'Dell' self.cpu = 'i5' self.ram = 8 print(self.brand,self.cpu,self.ram) s1 = Student('Rashmi',1) s2 = Student('Ravali',2) s1.show() s1.lap.brand #other way lap1 = s1.lap lap2 = s2.lap #calling inner class lap1 = Student.Laptop()
false
2af7aa31f51f43d8d4cdaaaf245833f3c215e9cf
P-RASHMI/Python-programs
/Logicalprogram/gambler.py
1,715
4.3125
4
''' @Author: Rashmi @Date: 2021-09-18 23:10 @Last Modified by: Rashmi @Last Modified time: 2021-09-19 2:17 @Title : Simulates a gambler who start with $stake and place fair $1 bets until he/she goes broke (i.e. has no money) or reach $goal. Keeps track of the number of times he/she wins and the number of bets he/she makes. ''' import random def gambler(stake,goal,number): """Description :to calculate wins, loss and percentage of wins,loss parameter : stake,goal,number(amount he had,win amount,bets) printing value : wins loss percentages and wins""" win_count = 0 loss_count = 0 counter = 0 while (stake > 0 and stake < goal and counter < number): try: counter+=1 randum_generated = random.randint(0,1) #if suppose randint(0,1,78) given three parameters generating type error exception if (randum_generated == 1): win_count = win_count + 1 stake = stake + 1 else: loss_count = loss_count + 1 stake = stake - 1 except TypeError as e: print("error found ", e ) #to find type of exception type(e).__name__ percent_win = (win_count/number)*100 percent_loss = 100-percent_win print("Number of wins",win_count) print("win percentage :",percent_win) print("loss percentage :",percent_loss ) print("Number of times betting done",counter) if __name__ == '__main__': stake = int(input("Enter the stake amount :")) goal = int(input("Enter how much money want to win")) number = int(input("Enter number of times he want to get involved in betting")) gambler(stake,goal,number)
true
65d56039fe3688d16aeb6737fbcd105df044155a
pranshulrastogi/karumanchi
/doubleLL.py
2,884
4.40625
4
''' implement double linked list ''' class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class doubleLL: def __init__(self): self.head = None # insertion in double linked list def insert(self,data,pos=-1): assert pos >=-1, "make sure to give valid pos argument" # get the new node new_node = Node(data) # insertion when list is empty if not self.head: if pos > 0: print("list is empty, can't insert node at defined location") else: self.head = new_node else: # insertion when list is not empty # 1. insertion at beginning if pos == 0: new_node.next = self.head self.head = new_node # 2. insertion at middle elif pos > 0: i=0 n=self.head while(i<pos and n.next ): i+=1 n=n.next new_node.next = n new_node.prev = n.prev n.prev.next = new_node n.prev = new_node else: #3. insertion at last (default) n=self.head while(n.next): n=n.next new_node.prev = n n.next = new_node # deletion in double linked list def delete(self,pos=-1): # by default deletes the last node n = self.head # check empty if not n: print("Can't perform delete on empty list!!") return False # deletion of head node if pos==0: n.next.prev = None self.head = n.next n.next = None # deletion at certain position elif pos > 0: i=0 while ( i<=pos and n.next ): i+=1 n=n.next if i<pos: print("not valid positon to delete") return False n.prev.next = n.next n.next.prev = n.prev n.next = None else: while(n.next): n = n.next n.prev.next = None n.prev = None # display def printLL(self): n = self.head while(n.next): print(n.data,end=' <-> ') n = n.next print(n.data) # driver if __name__ == '__main__': #insert in dll dll = doubleLL() for i in range(2,33,2): dll.insert(i) dll.printLL() print("inserting at 0") dll.insert(1,0) dll.printLL() print("inserting at 2") dll.insert(3,2) dll.printLL() print("inserting at last") dll.insert(34) dll.printLL()
true
0765b7bc193f7bc799aa0b713b32b9c97ce7b3eb
maheshganee/python-data
/13file operation.py
2,798
4.65625
5
""" file operation:python comes with an inbuilt open method which is used to work with text files //the text files can operated in three operation modes they are read write append //open method takes atleast one parameter and atmost two parameters //first parameter represents the file name along with full path and second parameter represents operation modes //operation modes represents with single carrcter they are r for read w for write a for append //open method returns a file pointer object which contains file name and operation mode details read operation mode-------use second parameter r to open the the file in read operation mode //when a file opened in read mode we can only perform read operations so read operation will applicable only when the file exit syntax-----open('file name,'mode) ex------fp = open('data.txt','r') read functions 1 read 2 readline 3 readlines read----this method will return the file data in a string format //this method takes atmost one parameter that is index position //the default value of index position is always length of the file syntax-----fp.read(index position) note ------all the read operation function will cause a shifting of file pointer courser to reset the file pointer courser we can use seek method seek------this method takes exactly one parameter that is index position to reset syntax-----fp.seek(index position) readline-------this method will return one line of the file at a time //this method takes atmost one parameter that is index position and default value is first line of file syntax-----fp.readline(index position) readlines--------this method will return list of lines in given files //no parameters required //output is always list syntax-----fp.readlines() 2.write operation mode------use w as second parameter in open function to work with the files in write operation //w o m will always creates new file with given name //in write operation mode we can use two functions they are write writelines write-------this method is used to write one string into the given file //write method take exactly one parameter that is one string syntax-----fp.write() writelines-------this method is used to add multipule strings to given file //this method takes exactly one parameter list r tuple syntax-----fp.writelines() 3.append operation mode-------use a as second parameter in open function to work with the files in append o m //to work with a o m the file should exit in the system //we can perform two functions in a o m which are similar to write operation mode they are write writelines rb --------read + binary(read + append) rb+---------read + append/write wb----------write +read wb+---------write+raed+append """ fp = open('/home/mahesh/Desktop/data.txt','w') fp.write('hi')
true
1e171d3183670dd0bac6ab179a3b7c13c42f834c
rronakk/python_execises
/day.py
2,705
4.5
4
print "Enter Your birth date in following format : yyyy/mm/dd " birthDate = raw_input('>') print" Enter current date in following format : yyyy/mm/dd " currentDate = raw_input('>') birth_year, birth_month, birth_day = birthDate.split("/") current_year, current_month, current_day = currentDate.split("/") year1 = int(birth_year) month1 = int(birth_month) day1 = int(birth_day) year2 = int(current_year) month2 = int(current_month) day2 = int(current_day) def daysBetweenDates(year1, month1, day1, year2, month2, day2): # Counts total number of days between given dates days = 0 assert(dayBeforeNext(year1, month1, day1, year2, month2, day2) > 0) while (dayBeforeNext(year1, month1, day1, year2, month2, day2)): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def nextDay(year, month, day): # Helper function to return the year, month, day of the next day. if (day < daysInMonth(month, year)): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def dayBeforeNext(year1, month1, day1, year2, month2, day2): # Validates if user has not entered future date before past date if (year1 < year2): dbn = True elif(year1 == year2): if(month1 < month2): dbn = True elif(month1 == month2): if(day1 < day2): dbn = True else: dbn = False else: dbn = False else: dbn = False return dbn def daysInMonth(month, year): # Calculate days in a given month and year # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month if (month == 2): days = 28 + isLeapYear(year) else: days = 31 - (month - 1) % 7 % 2 return days def isLeapYear(year): # Determine if give year is lear year or not. # Algorithm used for reference : http://www.dispersiondesign.com/articles/time/determining_leap_years """ if ((year % 4 == 0) or ((year % 100 == 0) and (year % 400 == 0))): leapYear = 1 else: leapYear = 0 return leapYear """ if (year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): leapYear = 1 else: leapYear = 0 else: leapYear = 1 else: leapYear = 0 return leapYear print "=============================================================== \n Your age in days is : %d " % daysBetweenDates(birth_year, birth_month, birth_day, current_year, current_month, current_day)
true
f9baac6271366884fbb8caaf201ccb6b4e53e254
sunilmummadi/Trees-3
/symmetricTree.py
1,608
4.21875
4
# Leetcode 101. Symmetric Tree # Time Complexity : O(n) where n is the number of the nodes in the tree # Space Complexity : O(h) where h is the height of the tree # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Approach: To check for symmetry of a tree, check if the extremes of a sub tree i.e. left child of # left subtree and right child of right subtree are same. And if middle elements i.e. right child of # left subtree and left child of right subtree are same. If the condition is not satisfied at any node # then the tree is not symmetric. If the entire tree can be recurrsively verified for this condition then # the tree is symmetric. # Your code here along with comments explaining your approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: # BASE if root == None: return True return self.helper(root.left, root.right) def helper(self, left, right): # Leaf Node if left == None and right == None: return True # Un symmetric if left == None or right == None or left.val != right.val: return False # recurssive call for left and right extremes and # recurssive call for left and right middle elements to check for symmetry return self.helper(left.left, right.right) and self.helper(left.right, right.left)
true
d908a2daa4ce12ec185d64cd232d1475598582a2
dltech-xyz/Alg_Py_Xiangjie
/.history/第2章/2-2/neizhi_20171113104609.py
561
4.375
4
car = ['奥迪', '宝马', '奔驰', '雷克萨斯'] #创建列表car print(len(car)) #输出列表car的长度 tuple2 = ('5', '4', '8') #创建元组tuple2 print(max(tuple2)) #显示元组tuple2中元素的最大值 tuple3 = ('5', '4', '8') #创建元组tuple3 print(min(tuple3)) #显示元组tuple3中元素的最小值 list1= ['Google', 'Taobao', 'Toppr', 'Baidu'] #创建列表list1 tuple1=tuple(list1) #将列表list1的值赋予元组tuple1 print(tuple1) #再次输出元组tuple1中的元素
false
4e1bc4ed86486ee94c63f439d96d7f663df5587c
mcfarland422/python101
/loops.py
277
4.21875
4
print "Loops file" # A for loop expects a starting point, and an ending point. # The ending poin (in range) is non-inclusive, meaning, it will stop when it gets there # i (below) is going to be the number of the loop it's on for i in range(1,10): if (i == 5): print
true
4df919c2b292cf09bf210ea8337023dea1c63bbf
Rosswell/CS_Exercises
/linked_list_manipulation.py
2,673
4.15625
4
'''Prompt: You have simple linked list that specifies paths through a graph. For example; [(node1, node2), (node2, node3)] node 1 connects to node 2 and node 2 connects to node 3. Write a program that traverses the list and breaks any cycles. So if node 1 links to both node 2 and node 2374, one link should be broken and reset. Give the first link formed priority. You can use helper methods .get(index) and .set(index, (new_value)) to get and set new links in the list or write your own ''' '''Explanation: Given the constraints, there are basically two cases that we want to control for: cycles and multiple links. Will be maintaining 2 lists in addition to the original: one to store previously seen values, one to return. 1. Iterate through the list of edges, check if the source node (n1 in (n1, n2)) is already in the seen nodes dict 2. If it's not in the seen nodes dict, add it to the dict and make sure n1's pointer doesn't create a cycle or is the second edge from that node. If those are both true, append the edge to the return list 3. If it is in the dict, check if there is a cycle by comparing to the previous edge. If a cycle is present, append an edge containing (n1, n4), where original two edges were [(n1, n2)(n3, n4)], effectively skipping the node creating the cycle 4. All other cases are skipped, as they are not the original edges from a particular source node ''' from operator import itemgetter class linked_list(object): def __init__(self, edge_list): self.edge_list = edge_list def get(self, index): return self.edge_list[index] def set(self, index, new_value): self.edge_list[index] = new_value return self.edge_list def list_iter(self): ret_list = [] seen_dict = {} for i, edge in enumerate(self.edge_list): node_from, node_to = itemgetter(0, 1)(edge) if node_from not in seen_dict: # new node addition to seen dict seen_dict[node_from] = True if node_to not in seen_dict: # source and destination nodes are unique and create no cycles ret_list.append(edge) else: prev_node_from, prev_node_to = itemgetter(0, 1)(self.edge_list[i-1]) if prev_node_to == node_from: # cycling case - skips the cycled node to preserve path continuity ret_list.append((prev_node_from, node_to)) return sorted(list(set(ret_list))) input_list = [('n1', 'n2'), ('n2', 'n3'), ('n3', 'n1'), ('n1', 'n4'), ('n4', 'n5'), ('n1', 'n123')] x = linked_list(input_list) print(x.list_iter())
true
41585c6dca2b0c40fbdd86fecbedecfa663e306a
Shadow-Arc/Eleusis
/hex-to-dec.py
1,119
4.25
4
#!/usr/bin/python #TSAlvey, 30/09/2019 #This program will take one or two base 16 hexadecimal values, show the decimal #strings and display summations of subtraction, addition and XOR. # initializing string test_string1 = input("Enter a base 16 Hexadecimal:") test_string2 = input("Enter additional Hexadecimals, else enter 0:") # printing original string print("The original string 1: " + str(test_string1)) print("The original string 2: " + str(test_string2)) # using int() # converting hexadecimal string to decimal res1 = int(test_string1, 16) res2 = int(test_string2, 16) # print result print("The decimal number of hexadecimal string 1 : " + str(res1)) print("The decimal number of hexadecimal string 1 : " + str(res2)) basehex = test_string1 sechex = test_string2 basehexin = int(basehex, 16) sechexin = int(sechex, 16) sum1 = basehexin - sechexin sum2 = basehexin + sechexin sum3 = basehexin ^ sechexin print("Hexidecimal string 1 subtracted from string 2:" + hex(sum1)) print("Hexidecimal string 1 added to string 2:" + hex(sum2)) print("Hexidecimal string 1 XOR to string 2:" + hex(sum3))
true
50d3d8fe9a65b183a05d23919c255b71378c7af5
alejandrox1/CS
/documentation/sphinx/intro/triangle-project/trianglelib/shape.py
2,095
4.6875
5
"""Use the triangle class to represent triangles.""" from math import sqrt class Triangle(object): """A triangle is a three-sided polygon.""" def __init__(self, a, b, c): """Create a triangle with sides of lengths `a`, `b`, and `c`. Raises `ValueError` if the three length values provided cannot actually form a triangle. """ self.a, self.b, self.c = float(a), float(b), float(c) if any( s <= 0 for s in (a, b, c) ): raise ValueError('side lengths must all be positive') if any( a >= b + c for a, b, c in self._rotations() ): raise ValueError('one side is too long to make a triangle') def _rotations(self): """Return each of the three ways of rotating our sides.""" return ((self.a, self.b, self.c), (self.c, self.a, self.b), (self.b, self.c, self.a)) def __eq__(self, other): """Return whether this triangle equals another triangle.""" sides = (self.a, self.b, self.c) return any( sides == rotation for rotation in other._rotations() ) def is_similar(self, triangle): """Return whether this triangle is similar to another triangle.""" return any( (self.a / a == self.b / b == self.c / c) for a, b, c in triangle._rotations() ) def is_equilateral(self): """Return whether this triangle is equilateral.""" return self.a == self.b == self.c def is_isosceles(self): """Return whether this triangle is isoceles.""" return any( a == b for a, b, c, in self._rotations() ) def perimeter(self): """Return the perimeter of this triangle.""" return self.a + self.b + self.c def area(self): """Return the area of this triangle.""" s = self.perimeter() / 2.0 return sqrt(s * (s - self.a) * (s - self.b) * (s - self.c)) def scale(self, factor): """Return a new triangle, `factor` times the size of this one.""" return Triangle(self.a * factor, self.b * factor, self.c * factor)
true
5e4c5593c59e8218630172dd9690da00c7d8fc1c
CostaNathan/ProjectsFCC
/Python 101/While and for loops.py
1,090
4.46875
4
## while specify a condition that will be run repeatedly until the false condition ## while loops always checks the condition prior to running the loop i = 1 while i <= 10: print(i) i += 1 print("Done with loop") ## for variable 'in' collection to look over: ## the defined variable will change each iteration of the loop for letter in "Giraffe academy": print(letter) ## the loop will print each letter individualy for the defined variable ## letter will correspond to the first, than the second, than ... each iteration friends = ["Jim", "Karen", "Jorge"] for name in friends: print(name) for index in range(10): print(index) ## range() = will count up to the design value, but without it ## in the above example, index will correspond to 0,1,2,...,9 for each iteration for index in range(3,10): print(index) ## an example of for loop to loop through an array for index in range(len(friends)): print(friends[index]) for index in range(5): if index == 0: print("Begin iteration!") elif index == 4: print("Iteration complete!")
true
959aae8e60bcc42ea90447dc296262c791e18d8c
CostaNathan/ProjectsFCC
/Python 101/Try & Except.py
298
4.21875
4
## try/except blocks are used to respond to the user something when an error occur ## best practice to use except with specific errors try: number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print(err) except ValueError: input("Invalid input")
true
1a4bc19b9deb798a2b3e18fabb62b53babd7e101
fernandorssa/CeV_Python_Exercises
/Desafio 63.py
1,077
4.15625
4
'''# Pede quantos termos da sequência Fibonacci n = int(input('Digite quantos termos da sequência: ')) # O contador foi definido como 4 pois n0, n1 e n2 não entram no WHILE. Dessa forma, o programa roda 3 vezes a menos cont = 4 n1 = n2 = 1 # Se o usuário pede 5 termos, o cont vai rodar 2 vezes, somado ao n0, n1 e n2: totalizando os 5 termos while cont <= n: # Essas quatro linhas são usadas para imprimir os 3 primeiros números da sequência if n1 == 1 and n2 == 1: print(n1 - n2) print(n1) print(n2) # Daqui em diante são calculados os próximos termos da sequência, depois de 0, 1, 1... resultado = n1 + n2 # Aqui será impresso o próximo termo da sequência Fibonacci print(resultado) n2 = n1 n1 = resultado cont += 1''' # Meu programa funciona mas a lógica é complicada n = int(input('Quantos termos: ')) t1 = 0 t2 = 1 print('{} -> {}'.format(t1, t2), end='') cont = 3 while cont <= n: t3 = t1 + t2 print(' -> {} '.format(t3), end='') t1 = t2 t2 = t3 cont += 1 print('-> FIM')
false
df3955f45591745ac7c20b87d71d01a16f774cf1
OlivierParpaillon/Contest
/code_and_algo/Xmas.py
1,504
4.21875
4
# -*- coding:utf-8 -* """ Contest project 1 : Christmas Tree part.1 Olivier PARPAILLON Iliass RAMI 17/12/2020 python 3.7.7 """ # Python program to generate branch christmas tree. We split the tree in 3 branches. # We generate the first branch of the christmas tree : branch1. # We will use the same variables for the whole code : only values will change. # nb_blank represents the number of blanks between the "*" ; # star_top represents the number of "*" on the top of the tree ; # and nb_branch defines the number of times we repeat the operation. def branch1(): nb_blank = 15 star_top = 1 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 1 star_top += 2 # We generate the middle branch of the christmas tree. # Same variables but we add 4 to star_top and we remove 2 from nb_blank def branch2(): nb_blank = 14 star_top = 3 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 2 star_top += 4 # We generate the last branch of the christmas tree. # We use the same variables but we remove 3 from nb_blank and we add 6 to star_top def branch3(): nb_blank = 13 star_top = 5 nb_branch = 4 for i in range(nb_branch): print(" " * nb_blank, "*" * star_top) nb_blank -= 3 star_top += 6 # Main function to start the program. def main(): branch1(), branch2(), branch3() main()
true
23bd8f9abc8622a7fba3ec85097241eacd9f3713
DLLJ0711/friday_assignments
/fizz_buzz.py
1,486
4.21875
4
# Small: add_func(1, 2) --> outputs: __ # More Complex: add_func(500, 999) --> outputs: __ # Edge Cases: add_func() or add_func(null) or add_func(undefined) --> outputs: ___ # Take a user's input for a number, and then print out all of the numbers from 1 to that number. #startFrom = int(input('Start From (1-10): ')) not needed #x = 1 # endOn = int(input('End On (any number): ')) # while(x <= endOn): # print(x) # x +=1 # For any number divisible by 3, print 'fizz' # for i in range(lower, upper+1): # if((i%3==0): # print(i) # For any number divisible by 5, print 'buzz' # for i in range(lower, upper+1): # (i%5==0)): # print(i) # For any number divisible by 3 and 5, print 'fizzbuzz' # for i in range(lower, upper+1): # if((i%3==0) & (i%5==0)): # print(i) #print 1 to user's input NOT NEEDED # while(x <= endOn): # print(x) # x += 1 # HAD TO COMBINE CODE AND REPLACE SYNTAX AND ORDER OF EVALUATION #Starting range x = 1 #user's input endOn = int(input('End On (any number): ')) #for loop and if statment for x in range(x, endOn +1): if x % 3 == 0 and x % 5 == 0: print('fizzbuzz') elif x % 3 == 0: print("fizz") elif x % 5 == 0: print("buzz") else: print(x) #had continue after each statement replaced with else to end.
true
27908f6c8668a493e416fc1857ac8fa49e7bb255
s3rvac/talks
/2017-03-07-Introduction-to-Python/examples/22-point.py
353
4.25
4
from math import sqrt class Point: """Representation of a point in 2D space.""" def __init__(self, x, y): self.x = x self.y = y def distance(self, other): return sqrt((other.x - self.x) ** 2 + (other.y - self.y) ** 2) a = Point(1, 2) b = Point(3, 4) print(a.distance(b)) # 2.8284271247461903
true
7baaca13abcd7fc98fd5d9b78de0bc62557f4b83
s3rvac/talks
/2020-03-26-Python-Object-Model/examples/dynamic-layout.py
666
4.34375
4
# Object in Python do not have a fixed layout. class X: def __init__(self, a): self.a = a x = X(1) print(x.a) # 1 # For example, we can add new attributes to objects: x.b = 5 print(x.b) # 5 # Or even new methods into a class: X.foo = lambda self: 10 print(x.foo()) # 10 # Or even changing base classes during runtime (this is just for illustration, # I do not recommend doing this in practice): class A: def foo(self): return 1 class B(A): pass class C: def foo(self): return 2 b = B() print(b.foo(), B.__bases__) # 1 (<class '__main__.A'>,) B.__bases__ = (C,) print(b.foo(), B.__bases__) # 2 (<class '__main__.C'>,)
true
42b39efbe438ae62a818b8487aedeb5d71d4cf58
lafleur82/python
/Final/do_math.py
1,022
4.3125
4
import random def do_math(): """Using the random module, create a program that, first, generates two positive one-digit numbers and then displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Ensure your program conducts error-checking on the answer and notifies the user whether the answer is correct or not.""" a = random.randint(1, 9) b = random.randint(1, 9) op = random.randint(1, 3) answer = 0 if op == 1: print("What is", a, "+", b, "?") answer = a + b elif op == 2: print("What is", a, "-", b, "?") answer = a - b elif op == 3: print("What is", a, "*", b, "?") answer = a * b user_input = float(input()) if user_input == answer: print("Correct!") else: print("Incorrect.") if __name__ == '__main__': while True: do_math() print("Another? (y/n)") user_input = input() if user_input != 'y': break
true
074f936e918b85a0b3ed669bb60f0d02d7a790db
daniel-reich/ubiquitous-fiesta
/PLdJr4S9LoKHHjDJC_22.py
909
4.3125
4
# 1-> find if cube is full or not, by checking len of cube vs len of current row. ​ # 2-> calculate the missing parts in current row, by deducting the longest len of row vs current row. ​ # 3-> if we have missing parts return it. ​ # 4-> if we don't have missing parts, but our len of cube is smaller than our longest row. then that means we have a non-full cube. ​ def identify(*cube): totalMissingParts = 0 for row in range(len(cube)): maxLengthOfaRow = len(max([i for i in cube])) # Non-Full is True if len(cube) < maxLengthOfaRow or len(cube[row]) < maxLengthOfaRow: currentMissingParts = maxLengthOfaRow - len(cube[row]) totalMissingParts += currentMissingParts if totalMissingParts: return "Missing {}".format(totalMissingParts) else: if len(cube) < maxLengthOfaRow and not totalMissingParts: return "Non-Full" else: return "Full"
true
2950192f84c4b16ace89e832e95300b7b58db078
daniel-reich/ubiquitous-fiesta
/ZdnwC3PsXPQTdTiKf_6.py
241
4.21875
4
def calculator(num1, operator, num2): if operator=='+': return num1+num2 if operator=='-': return num1-num2 if operator=='*': return num1*num2 if operator=='/': return "Can't divide by 0!" if num2==0 else num1/num2
true
57fc2b657fc291816c34c85760c6a8b57c3d6677
daniel-reich/ubiquitous-fiesta
/suhHcPgaKdb9YCrve_24.py
311
4.1875
4
def even_or_odd(s): evenSum=0 oddSum=0 for i in s: if int(i)%2==0: evenSum+=int(i) else: oddSum+=int(i) if evenSum>oddSum: return "Even is greater than Odd" if evenSum<oddSum: return "Odd is greater than Even" if evenSum==oddSum: return "Even and Odd are the same"
false
c202ed548a40661673c3724e07d5807c440748a3
daniel-reich/ubiquitous-fiesta
/ZdnwC3PsXPQTdTiKf_12.py
286
4.25
4
def calculator(num1, operator, num2): if operator == "/": if not num2 == 0: return num1/num2 else: return "Can't divide by 0!" elif operator == "*": return num1*num2 elif operator == "+": return num1+num2 elif operator == "-": return num1-num2
false
7e8131e9fa9aaf0b419635a8f06519d48571a49d
daniel-reich/ubiquitous-fiesta
/ZwmfET5azpvBTWoQT_9.py
245
4.1875
4
def valid_word_nest(word, nest): while True: if word not in nest and nest != '' or nest.count(word) == 2: return False nest = nest.replace(word,'') if word == nest or nest == '': return True
true
39e97b4115d1bf32cfdb2dabf4c794fd1e44b4e7
daniel-reich/ubiquitous-fiesta
/suhHcPgaKdb9YCrve_16.py
237
4.34375
4
def even_or_odd(s): even=sum(int(x) for x in s if int(x)%2==0) odd=sum(int(x) for x in s if int(x)%2) return 'Even is greater than Odd' if even>odd else \ 'Odd is greater than Even' if odd>even else 'Even and Odd are the same'
false
9ce16fc28b4678e0b58aa237f496897100f851a9
daniel-reich/ubiquitous-fiesta
/mHRyhyazjCoze5jSL_8.py
298
4.15625
4
def double_swap(string,chr1,chr2): new_string = "" for char in string: if char == chr1: new_string = new_string + chr2 elif char == chr2: new_string = new_string + chr1 else: new_string = new_string + char return new_string
false
b7b5dc1ec31ac738b6ed4ef5f0bf7d383bc54fb2
daniel-reich/ubiquitous-fiesta
/MvtxpxtFDrzEtA9k5_13.py
496
4.15625
4
def palindrome_descendant(n): ''' Returns True if the digits in n or its descendants down to 2 digits derived as above are. ''' str_n = str(n) if str_n == str_n[::-1] and len(str_n) != 1: return True ​ if len(str_n) % 2 == 1: return False # Cannot produce a full set of pairs ​ return palindrome_descendant(int(''.join(str(int(str_n[i]) + int(str_n[i+1])) \ for i in range(0, len(str_n), 2))))
true
b2cea9d9a6e9442f4ff3877a211ea24b8072d821
daniel-reich/ubiquitous-fiesta
/hzs9hZXpgYdGM3iwB_18.py
244
4.15625
4
def alternating_caps(txt): result, toggle = '', True for letter in txt: if not letter.isalpha(): result += letter continue result += letter.upper() if toggle else letter.lower() toggle = not toggle return result
true
08bd018bc3a79c324debfcd9c473c44be6454778
daniel-reich/ubiquitous-fiesta
/BpKbaegMQJ5xRADtb_23.py
1,028
4.125
4
def prime_factors(n): ''' Returns a list of the prime factors of integer n as per above ''' primes = [] for i in range(2, int(n**0.5) + 1): ​ while n % i == 0: primes.append(i) n //= i ​ return primes + [n] if n > 1 else primes ​ def is_unprimeable(n): ''' Returns 'Unprimeable', 'Prime Input' or a list of primes in ascending order for positive integer n as per the instructions above. ''' if n > 1 and len(prime_factors(n)) == 1: return 'Prime Input' ​ str_num = str(n) primes = [] # to store found primes in ​ for i, digit in enumerate(str_num): for val in range(10): if int(digit) != val: num = int(str_num[:i] + str(val) + str_num[i + 1:]) if num % 2 == 1 or num == 2: if len(prime_factors(num)) == 1: primes.append(num) # prime number found ​ return 'Unprimeable' if len(primes) == 0 else sorted(set(primes))
false
48d9d502b12feb2a2c6c637cc5050d353a6e45d0
daniel-reich/ubiquitous-fiesta
/tgd8bCn8QtrqL4sdy_2.py
776
4.15625
4
def minesweeper(grid): ''' Returns updated grid to show how many mines surround any '?' cells, as per the instructions. ''' def mines(grid, i, j): ''' Returns a count of mines surrounding grid[i][j] where a mine is identified as a '#' ''' count = 0 locs = ((i-1,j-1), (i-1,j), (i-1,j+1),(i,j-1), (i,j+1), (i+1,j-1), (i+1,j), (i+1,j+1)) # possible neighbours ​ for r, c in locs: if 0 <= r < len(grid) and 0 <= c < len(grid[0]): if grid[r][c] == '#': count += 1 ​ return str(count) ​ return [[mines(grid,i,j) if grid[i][j] == '?' else grid[i][j] \ for j in range(len(grid[0]))] for i in range(len(grid))]
true
e07c8e937363164c6a83778de6812098453d9fbe
daniel-reich/ubiquitous-fiesta
/JzBLDzrcGCzDjkk5n_21.py
268
4.1875
4
def encrypt(word): #Step 1: Reverse the input: "elppa" rword = word[::-1] rword = rword.replace('a','0') rword = rword.replace('e','1') rword = rword.replace('o','2') rword = rword.replace('u','3') rword = rword+'aca' return rword
false
17608253348421e9e8efeceef37697702b9e49b2
daniel-reich/ubiquitous-fiesta
/FSRLWWcvPRRdnuDpv_1.py
1,371
4.25
4
def time_to_eat(current_time): #Converted hours to minutes to make comparison easier breakfast = 420; lunch = 720; dinner = 1140; full_day = 1440; #Determines if it's morning or night morning = True; if (current_time.find('p.m') != -1): morning = False; #Splits the time from the A.M/P.M Callout num_time = current_time.split(' '); #Splits hours and minutes hours_minutes = num_time[0].split(':',1); #Converts hours to minutes and adds 12 hours if afternoon if (morning == False): hours = (int(hours_minutes[0]) + 12) * 60; elif (morning == True and int(hours_minutes[0]) == 12): hours = 0; else: hours = int(hours_minutes[0]) * 60; ​ #Totals up minutes and hours minutes_total = int(hours_minutes[1]) + hours; print(minutes_total); if (minutes_total < breakfast): diff_minutes = breakfast - minutes_total; elif (minutes_total > breakfast and minutes_total < lunch): diff_minutes = lunch - minutes_total; elif (minutes_total > lunch and minutes_total < dinner): diff_minutes = dinner - minutes_total; else: diff_minutes = full_day - minutes_total + breakfast; #conversion back to list diff_hours = int(diff_minutes / 60); diff_minutes_remain = abs((diff_hours * 60) - diff_minutes); answer = [diff_hours,diff_minutes_remain] return answer
true
88b08f253f89079d2055ca809f990b4bba66c970
daniel-reich/ubiquitous-fiesta
/kgMEhkNNjRmBTAAPz_19.py
241
4.125
4
def remove_special_characters(txt): l = [] for item in txt: if item in ['-','_',' '] or 'A'<=item<= 'Z'or 'a'<=item<='z' or '0'<=item<='9' : l.extend(item) print(l) return ''.join([item for item in l])
false
811e24a79e0ef363810682b9430e7e06fe1ac388
daniel-reich/ubiquitous-fiesta
/suhHcPgaKdb9YCrve_17.py
255
4.28125
4
def even_or_odd(s): e = 0 o = 0 for i in s: i = int(i) if i%2==0: e += i else: o += i if e > o: return "Even is greater than Odd" if o > e: return "Odd is greater than Even" return "Even and Odd are the same"
false
280b845a106c503186334374f3b8a19f9b335d58
daniel-reich/ubiquitous-fiesta
/dcX6gmNguEi472uFE_12.py
232
4.34375
4
def factorial(num): fact = 1 while num > 0: fact = fact*num num -= 2 return fact def double_factorial(num): print(num) if num == 0 or num == 1 or num == -1: return 1 else: return num * factorial(num-2)
false
f2cb2449e31eac8a7f3001a503cf34bb953440db
daniel-reich/ubiquitous-fiesta
/NNhkGocuPMcryW7GP_6.py
598
4.21875
4
import math ​ def square_areas_difference(r): # Calculate diameter d = r * 2 # Larger square area is the diameter of the incircle squared lgArea = d * d # Use the diameter of the circle as the hypotenuse of the smaller # square when cut in half to find the edges length # When the legs are equal length (because it's a square), you just # divide the hypotenuse by the sqrt of 2 # Smaller square area is the legs squared smLeg = d / math.sqrt(2) smArea = smLeg * smLeg # We then return the difference between the large area and small area return lgArea - round(smArea)
true
2163c89bda23d7bb9c02adc2729b3b678a695785
daniel-reich/ubiquitous-fiesta
/gJSkZgCahFmCmQj3C_21.py
276
4.125
4
def de_nest(lst): l = lst[0] #Define 'l' so a while loop can be used while isinstance(l,list): #repeat until l is not a list l = l[0] #This is a neat little trick in recursion, you can keep diving #into list by just taking the 0 index of itself! return l
true
701687d9659a7c7e4373ed7159096bf1b1f18a85
daniel-reich/ubiquitous-fiesta
/QuxCNBLcGJReCawjz_7.py
696
4.28125
4
def palindrome_type(n): decimal = list(str(n)) == list(str(n))[::-1] # assess whether the number is the same read forward and backward binary = list(str(bin(n)))[2:] == list(str(bin(n)))[2:][::-1] # assess whether the binary form of the number is the same read forward and backward ​ if((decimal) and (binary)): # if both decimal and binary forms of the number are palindromes return "Decimal and binary." ​ if(decimal): # if only the decimal form of the number is a palindrome return "Decimal only." ​ if(binary): # if only the binary form of the number is a palindrome return "Binary only." ​ return "Neither!" # if neither forms of the number are palindromes
true
13a03a6d6d627d8f0c36bb4b295a9b89cd8dd36e
lavakiller123/python-1
/mtable
333
4.125
4
#!/usr/bin/env python3 import colors as c print(c.clear + c.blue + 'Mmmmm, multiplication tables.') print('Which number?') number = input('> ' + c.green) print('table for ' + number) for multiplier in range(1,13): product = int(number) * multiplier form = '{} x {} = {}' print(form.format(number,multiplier,product))
true
177034604e43405fc616b4ea8c4017f96e8bacea
aliasghar33345/Python-Assignment
/Assignment_5/ASSIGNMENT_5.py
2,975
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: """ Answer # 1 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(n): num = 1 while n > 0: num *= n n -= 1 return num print(factorial(1)) # In[2]: """ Answer # 2 Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. """ def caseCLC(string): uppers = 0 lowers = 0 for char in string: if char.islower(): lowers += 1 elif char.isupper(): uppers += 1 return uppers, lowers print(caseCLC("Hello Ali Asghar! are you ready to be called as Microsoft Certified Python Developer after 14 December?")) # In[3]: """ Answer # 3 Write a Python function to print the even numbers from a given list. """ def evenIndex(nums): li = [] for num in range(0,len(nums)): if nums[num] % 2 == 0: li.append(nums[num]) return li print(evenIndex([114,26,33,5,63,7,445,6,74,64,45.5,102.2,44])) # In[ ]: """ Answer # 4 Write a Python function that checks whether a passed string is palindrome or not. Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam """ def palindromeTEST(word): reverse = ''.join(reversed(word)) if word == reverse and word != "": return "You entered a palindrome." else: return "It is'nt palindrome." check_palindrome = input("Enter any word to test if it is pelindrome: ") print(palindromeTEST(check_palindrome)) # In[ ]: """ Answer # 5 Write a Python function that takes a number as a parameter and check the number is prime or not. """ def isprime(): nums = int(input("Enter any number to check if it is prime or not: ")) return prime(nums) def prime(nums): if nums > 1: for num in range(2,nums): if (nums % num) == 0: print("It is not a prime number.") print(num,"times",nums//num, "is", nums) break else: print("It is a prime number.") isprime() # In[ ]: """ Answer # 6 Suppose a customer is shopping in a market and you need to print all the items which user bought from market. Write a function which accepts the multiple arguments of user shopping list and print all the items which user bought from market. (Hint: Arbitrary Argument concept can make this task ease) """ def boughtITEM(): cart = [] while True: carts = input("\nEnter an item to add it in your cart: \nor Press [ENTER] to finish: \n") if carts == "": break cart.append(carts) item_list = "" for item in range(0,len(cart)): item_list = item_list + cart[item].title() + "\n" print("\nItems you have bought is:\n"+item_list) boughtITEM() # In[ ]:
true
7a5bf78bc03f1008220e365be65e95273686d56f
erik-kvale/HackerRank
/CrackingTheCodingInterview/arrays_left_rotation.py
2,412
4.4375
4
""" ------------------ Problem Statement ------------------ A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. FOr example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. ------------------ Input Format: ------------------ The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform). The second line contains n space-separated integers describing the respective elements of the array's initial state. ------------------ Constraints ------------------ 1 <= n <= 10^5 1 <= d <= n 1 <= a(sub i) <= 10^6 ------------------ Output Format ------------------ Print a single line of n space-separated integers denoting the final state of the after performing d left rotations. ============================ Solution Statement ============================ After reading in the necessary inputs, we need to simulate a left rotation on the array (Python list). For each rotation 'd' we need to pop off the first element of the array and append it at the last-index position of the array, this will simulate a left or counter-clockwise rotation. Visualizing the array as circle with its elements on the face of a clock can be helpful. When I pop off the first element (index=0), I store that value. My array is now length n - first element at which point I append the popped element to the end, effectively causing each element to shift one index to the left from its initial state. """ def array_left_rotation(num_of_elements, elements, num_of_rotations): for rotation in range(num_of_rotations): # O(n) first_element = elements.pop(0) # O(1) elements.append(first_element) # O(1) return elements # O(1) n, d = map(int, input().strip().split()) # O(1) a = list(map(int, input().strip().split())) # O(n) answer = array_left_rotation(n, a, d) # O(n) = O(n) + O(1) + O(1) + O(1) print(*answer, sep=' ') # O(1)
true
756347df8759c2befdb80feabcb255431be085d8
saiyampy/currencyconverter_rs-into-dollars
/main.py
898
4.28125
4
print("Welcome to rupees into dollar and dollar into rupees converter") print("press 1 for rupees into dollar:") print("press 2 for dollar into rupees:") try:#it will try the code choice = int(input("Enter your choice:\n")) except Exception as e:#This will only shown when the above code raises error print("You have entered a string") def dollars_into_rupees(): dollars = int(input("enter the amount of dollar to convert into rupees\n")) dollar_input = dollars*73.85 print(f"{dollars} dollars converted into rupees resulted {dollar_input} rupees") def rs_into_dollar(): op = int(input("enter the amount of rupees to convert into dollar\n")) value = op/73.85 print(f"{op} Rupees converted into dollars resulted {value}$ dollars ") if choice == 1: rs_into_dollar() if choice == 2: dollars_into_rupees() print("Thanks For Using This Code")
true
2d6ceb13782c1aa23f2f1c9dce160b7cb51cb5f3
nguya580/python_fall20_anh
/week_02/week02_submission/week02_exercise_scrapbook.py
2,398
4.15625
4
# %% codecell # Exercise 2 # Print the first 10 natural numbers using a loop # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 x = 0 while x <= 10: print(x) x += 1 # %% codecell # Exercise 3: # Execute the loop in exercise 1 and print the message Done! after # Expected output: # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Done! x = 0 while x <= 10: print(x) x += 1 if x > 10: print("Done!") # %% codecell # Exercise 4: # Print the numbers greater than 150 from the list # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 157 # 178 # 189 list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number > 150: print(number) # %% codecell # Exercise 5: # Print the number that is even and less than 150 # list = [12, 15, 47, 63, 78, 101, 157, 178, 189] # Expected output: # 12 # 78 # Hint: if you find a number greater than 150, stop the loop with a break list = [12, 15, 47, 63, 78, 101, 157, 178, 189] for number in list: if number < 150 and number % 2 == 0: print(number) # %% codecell # Exercise 6: # This will be a challenging! # Write a while loop that flips a coin 10 times # Hint: Look into the random library using: # https://docs.python.org/3/library/random.html # https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python import random head_count = [] tail_count = [] def flip_coin(): """this function generates random value 0-1 for coin 1 is head 0 is tail""" coin = random.randrange(2) if coin == 1: print(f"You got a head. Value is {coin}") head_count.append("head") else: print(f"You got a tail. Value is {coin}") tail_count.append("tail") def flip(): """this function generate flipping coin 10 times""" for x in range(10): flip_coin() print(f"\nYou flipped HEAD {len(head_count)} times, and TAIL {len(tail_count)} times.\n") again() def again(): """ask user if they want to flip coint again.""" ask = input("Do you want to flip coint again? \nEnter 'y' to flip, or 'n' to exit.\n") if ask == "y": #clear lists output to remains list length within 10 del head_count[:] del tail_count[:] #run flipping coin again flip() elif ask == "n": print("\nBye bye.") #call function flip()
true
d64a03f26d7dfd8bb4a7899770f29ce560b22381
Juahn1/Ejercicios-curso-de-python
/ejercicio_1_ecuacion.py
519
4.21875
4
#pasar la ecuacion a una expresion algoritmica (c + 5)(b ^2 -3ac)a^2 # ------------------ # 4a def ecuacion(a,b,c): x=((c+5)*((b**2)-3*a*c)*(a**2))/(4*a) print(f"El resultado es {x}") try: a=float(input("Ingrese la variable A: ")) b=float(input("Ingrese la variable B: ")) c=float(input("Ingrese la variable C: ")) ecuacion(a,b,c) except: ValueError print("Ingrese un numero valido")
false
63d67329e94978a29fcdf6bd2ee3a1d200660cbf
pyjune/python3_doc
/2_4.py
555
4.125
4
# 사칙연산 a = 3 b = 5 print(a+b) print(a+10) print(a-b) print(a*b) print(b*6) print(a/b) print(a/10) # 정수형 나눗셈 print(3//2) print(5//2) # 모드 연산 print(a%2) #a를 2로 나눈 나머지 print(b%a) #b를 a로 나눈 나머지 # 거듭 제곱 print(a**2) print(a**3) print(b**a) # 비교연산 a = 3 b = 5 print(a>0) print(a>b) print(a>=3) print(b<10) print(b<=5) print(a==3) #a에 들은 값과 3이 같으면 True print(a==b) #a와 b에 들어있는 값이 같으면 True print(a!=b) #a와 b에 들어있는 값이 다르면 True
false
471bb7458f78b94190321bdcbaa0dce295cdb3f9
contactpunit/python_sample_exercises
/ds/ds/mul_table.py
1,088
4.21875
4
class MultiplicationTable: def __init__(self, length): """Create a 2D self._table of (x, y) coordinates and their calculations (form of caching)""" self.length = length self._table = { (i, j): i * j for i in range(1, length + 1) for j in range(1, length + 1) } print(self._table) def __len__(self): """Returns the area of the table (len x* len y)""" return self.length * self.length def __str__(self): return '\n'.join( [ ' | '.join( [ str(self._table[(i, j)]) for j in range(1, self.length + 1) ] ) for i in range(1, self.length + 1) ] ) def calc_cell(self, x, y): """Takes x and y coords and returns the re-calculated result""" try: return self._table[(x, y)] except KeyError as e: raise IndexError() m = MultiplicationTable(3) print(m)
true
d727cc2970a57f8343b1d222cae1a626727431ad
helong20180725/CSCE580-Projects
/machinelearning/helloTest.py
753
4.125
4
#note #1. Strings """ print("helloworld") capital="HI, YOU ARE CAPITAL LETTERS" print(capital.lower()) print(capital.isupper()) print(capital[4]) print(capital.index("T")) print(capital.replace("ARE","is")) print("\"") """ #2. numbers """ a =10 b = 3 c = -19 d = 4.23 print(10%3) #error print("the number is "+a) print("the number is "+str(a)) print(pow(a,b)) print(abs(c)) print(max(a,b,c)) # min() print(round(d)) """ """ from math import * print(ceil(3.1)) print(sqrt(4)) """ #3.input """ a = input("Please input something: ") print(a+" right!") """ #4. build a basic calculator """ numberOne= int(input("The first number: ")) numberTwo= int(input("The second number: ")) result = float(numberOne) + numberTwo print(result) """ #5. mad libs
false