blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a720339b1e5f7b8d4f99790f75bcc9ff265d40e1
evaristrust/Courses-Learning
/SecondProgram/pytbasics/CHALLENGES/Edabit/Title string.py
879
4.375
4
# Check if a string txt is a title text or not. # A title text is one which has all the words in # the text start with an upper case letter. def my_text(text): if text == text.title(): print("The text is title") else: print("The text is not title") my_text("World Health Organization") my_text("World of Economy") # or use istitle() print("**" * 40) # using the function and user_name! full_name = input("Enter your name: ") def your_text(text): text = full_name if text.istitle(): print("Your name format is a Title!") else: print("Your name needs to be Capitalized") your_text(full_name) print("--" * 40) my_name = "People Of Rwanda" def is_title(str): # if str.istitle(): if str == str.title(): return ("You are right!") else: return ("You are wrong!") print(is_title(my_name))
true
ae655fe0d0f0af55f777970f9d78beef11452b99
evaristrust/Courses-Learning
/SecondProgram/pytbasics/challenge_dict_join.py
2,147
4.3125
4
# Modify the program in the join file so that # so that the exits is a dictionary rather than a list # with the keys being the numbers of the locations and the values # being dictionaries holding the exits (as they do at present). # No change should be needed to the actual code # # once that is working, create a nother dictionary that contains words # that players may use. These words will be the keys, and thteir # values will be a single letter that the program can use to # determine which way to go #creating a dictionaries for locations for each exit locations = {0: "You are standing outside of the building", 1: "You are heading to the best supermarket", 2: "You are heading to the ShineBest Bar", 3: "You are headed to the Hotel of the city", 4: "You will reach to the lake of the city"} # creating a list for exits, putting dictionaries inside exits = {0: {"Q": 0}, 1: {"W": 1, "E": 4, "S": 3, "N": 2, "Q": 0}, 2: {"N": 2, "Q": 0}, 3: {"W": 1, "Q": 0}, 4: {"N": 2, "W": 1, "Q": 0}, 5: {"W": 1, "S": 3, "Q": 0}} # creating a dictionary of vocabularies or words that the player can use vocabs = {"NORTH": "N", "SOUTH": "S", "WEST": "W", "EAST": "E", "QUIT": "Q"} # initializi5g loc loc = 1 while True: # Accessing the available exits in the exit list and printing the matching locations available_exits = " , ".join(exits[loc].keys()) print(locations[loc]) # if the loc is 0, we are going to break the loop if loc == 0: break direction = input("choose from these available exits: {} ".format(available_exits)).upper() print() #parse the user input, using our vocabs dictionary if len(direction) > 1: # if it is more than one letter for word in vocabs: # check all the words that are in the vocabs if word in direction: # did the user put the word we know? direction = vocabs[word] if direction in exits[loc]: loc = exits[loc][direction] else: print("Sorry! We are unable to find that location")
true
84f271a644134c6c3d8818c9cc95e6861ed3fc1b
evaristrust/Courses-Learning
/SecondProgram/pytbasics/CHALLENGES/Edabit/prime.py
668
4.15625
4
# print the prime number from 0 and 100 # # start = 0 # end = 100 # for num in range(start, end): # if num == int(num): # nbers need to be positive! # for x in range(2, num): # if num % x == 0: # break # else: # print(num, end= " ") my_number = int(input("Enter your number: ")) if my_number > 0: # loop the positive integers for x in range(2, my_number): if (my_number % x) == 0: print("It's not a prime number") break else: print("It's a prime number") else: # 0 or a negative number isn't a prime print("it's less or equal to zero.. so not a prime")
true
ee7e75e0ae58f7cad82cdccabf8098739d7f87ff
evaristrust/Courses-Learning
/SecondProgram/intro_list_range_tuples/challenge3.py
1,599
4.375
4
# Given the tuple below that represents the Imelda May album # "More Maythem", Write a code to print the album details, followed by a # listing of all the tracks in the album. # Indent the tracks by a single tab stop when printing them # remember that you can pass more than one item to the print function # separated with a comma imelda = "More Maythtem", "Imelda May", 2011, \ ((1, "Pulling the Rug"), (2, "Maythem"), (3, "Pscho"), (4, "Kentish Town waltz")) name, artist, year, tracks = imelda print('Name of album: {}'.format(name)) print('Artist\'s name: {}'.format(artist)) print('Year of publication: {}'.format(year)) # print("\t",t1, "\t", t2, "\t", t3, "\t", t4) # the above can work, but also I am going to use for loop for song in tracks: number, title = song print("\t the track no. {} is {}".format(number, title)) # print("\t",song) # Then the challenge is done and it's done well' # if you want to buy other tracks on the album for example, # you would never be able cos the tuple can't be changed # however, we can store a list in a tuple and the elements of the list only can change imelda = "More Maythtem", "Imelda May", 2011, \ [(1, "Pulling the Rug"), (2, "Maythem"), (3, "Pscho"), (4, "Kentish Town waltz")] imelda[3].append((5, "Halleluya")) name, artist, year, tracks = imelda tracks.append((6, "Dance dance")) print(name) print(artist) print(year) # print("\t",t1, "\t", t2, "\t", t3, "\t", t4) # the above can work, but also I am going to use for loop for song in tracks: number, title = song print("\t the track no. {} is {}".format(number, title))
true
e3f22f939b1ea3bf144c9eb0cf9f2069e72e4a60
lambdaJasonYang/DesignPatterns
/DependencyInversion.py
2,113
4.21875
4
class ConcreteWheel: def turn(self): print("Using Wheel") return "Using Wheel" ## Car ---DEPENDS---> ConcreteWheel class Car: def __init__(self, ObjectThisDependsOn): self.Wheel = ObjectThisDependsOn self.turning = True def getState(self): if self.turning == True: self.Wheel.turn() return 0 testCar = Car(ConcreteWheel()) testCar.getState() #The problem with tight coupling is new objects with different specifications # "newturn" instead of "turn" class NewConcreteWheel: def newturn(self): print("Using new Wheel") return "Using new Wheel" try: testCar = Car(NewConcreteWheel()) #breaks testCar.getState() except Exception: print("Failed due to new object having different specification 'newturn'") #REFACTOR from abc import ABC, abstractmethod class AbstractWheel(ABC): #ABC as argument tells us this is an abstract class #also make an abstract method @abstractmethod def turn(self): pass #refactor the class to implement the abstract class/Interface #python passes the abstract class for implementation class ConcreteWheel(AbstractWheel): #ConcreteWheel ---Implements---> AbstractWheel def turn(self): print("Using Wheel") return "Using Wheel" #Car ---DEPENDS---> AbstractWheel , The Abstraction weakens the tight coupling class Car: def __init__(self, WheelInterfaceImplementation): self.Wheel = WheelInterfaceImplementation self.turning = True def getState(self): if self.turning == True: self.Wheel.turn() return 0 testCar = Car(ConcreteWheel()) testCar.getState() #What dependency inversion does, is force the new class to implement "turn" class NewConcreteWheel(AbstractWheel): #NewConcreteWheel ---Implements---> AbstractWheel def newturn(self): print("Using new Wheel") return "Using new Wheel" def turn(self): #FORCES "turn" implementation print("Using new Wheel") return "Using new Wheel" testCar = Car(NewConcreteWheel()) testCar.getState()
true
b1c1656f44ee332458a08db1b5123d2379834291
delphinevendryes/coding-practice
/left_view_binary_tree.py
2,493
4.3125
4
''' Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. ''' class Node(): def __init__(self, val, left=None, right=None): self.value = val self.left = left self.right = right def insertLeft(self, val): assert not self.left self.left = Node(val) def insertRight(self, val): assert not self.right self.right = Node(val) class BinaryTree(): def __init__(self, root): self.root = Node(root) def __repr__(self): s = str() root = self.root stack = [root] while len(stack) > 0: c = stack.pop() s += ' ' + str(c.value) if c.left: stack.append(c.left) s += ' L --> ' + str(c.left.value) if c.right: stack.append(c.right) s += ' R --> ' + str(c.right.value) return s def insertLeft(self, element, node = None): if node: c = self.root stack = [c] while len(stack) > 0: c = stack.pop() if c.value == node: break if c.left: stack.append(c.left) if c.right: stack.append(c.right) if (len(stack) == 0) & (c.value != node): print('No such node') return c.insertLeft(element) else: self.root.insertLeft(element) def print_left_path(self): c = self.root s = str(c.value) while c.left: c = c.left s += ' --> ' + str(c.value) print(s) def insertRight(self, element, node = None): if node: c = self.root stack = [c] while len(stack) > 0: c = stack.pop() if c.value == node: break if c.left: stack.append(c.left) if c.right: stack.append(c.right) if (len(stack) == 0) & (c.value != node): print('No such node') return c.insertRight(element) else: self.root.insertRight(element) bt = BinaryTree(2) bt.insertLeft(3) bt.insertRight(5) bt.insertLeft(4, 3) bt.insertLeft(6, 4) bt.print_left_path() # Should print: 2 --> 3 --> 4 --> 6
true
51ccceadf4a071b2d1bc4faa2c84ab3053d14347
jamesdeepak/dsp
/python/q8_parsing.py
1,213
4.375
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. import csv with open('football.csv', newline='') as csvfile: myreader = csv.reader(csvfile, delimiter=',', quotechar='|') next(myreader,None) #ignoring the header mainTuple = [] for row in myreader: team = row[0] gs = int(row[5]) ga = int(row[6]) diff = gs-ga #print(diff) tup = (team,diff) mainTuple.append(tup) def getKey(item): return item[-1] #index number for the tuple -1 means last mainTuple.sort(key=getKey) reqList = mainTuple[0] #Getting the first value of multielement tuple #getting the first element of the tuple print(reqList[0] +' had the smallest difference in for and against ' \ 'goals. Their difference was ' + str(reqList[1]))
true
423e2b1109d627342c9256a60b880641014917a0
Tere1980/aprendiendo-python-2
/Capitulo 03/015_Otros_metodos_especiales_de_clase.py
1,468
4.40625
4
#!/usr/bin/python #coding=utf-8 print "\n### Programacion Orientada a Objetos: Metodos especiales ###" ## Clase de ejemplo con varios métodos especiales class Ejemplo(object): # Método de inicializacion (NO constructor) def __init__(self, atr1, atr2): self.atr1 = atr1 self.atr2 = atr2 print "Init" # Método constructor de clase de nuevo estilo, # tiene prioridad ante Init """ def __new__(cls, atr1, atr2): print "New" """ # Método destructor con tareas de limpieza # Se ejecuta automáticamente al finalizar el programa y libera memoria def __del__(self): print "Del" # Método string que devuelve una cadena representado el objeto def __str__(self): return "arg1=" + str(self.atr1) + " arg2=" + str(self.atr2) # Método length que devuelve la longitud del objeto en número entero def __len__(self): return self.atr1 + self.atr2 # Método que implementa comparativas de un objeto == != < > >= <= # Debe devolver negativo si nuestro objeto es menor, cero si son iguales y # positivo si es mayor def __cmp__(self, other): #compara las longitudes if len(self) > len(other) : return 1 elif len(self) < len(other) : return -1 else : return 0 e = Ejemplo(3,5) print e print len(e) f = Ejemplo(3,8) ## ¿Son del mismo tipo? print e == f print e < f
false
092bac2f42cc1325e20107ceda331bf7740ec253
Tere1980/aprendiendo-python-2
/Capitulo 05/023_Excepciones.py
1,478
4.15625
4
#!/usr/bin/python #coding=utf-8 print "\n### Excepciones ###\n" ## Lista completa con todos los tipos de excepciones que puede lanzar Python ## http://docs.python.org/library/exceptions.html ## Lanzar una excepción def dividir(a,b): return a/b # ZeroDivisionError: integer division or modulo by zero # dividir(5,0) # Capturar y tratar excepciones # Abrir un fichero que no existe try: f = file("archivo.txt") except: print "El archivo no existe" ## Tratar varias excepciones por bloque try: # Parsear un entero incorrecto num = int("3a") # Imprimir una variable que no existe print no_existe except NameError: print "La variable no existe" except ValueError: print "El valor no es un numero" ## Cláusula con else ## La cláusula finally siempre se ejecuta try: print "Bloque try" 8 / 0 print "Try después de error" # Nunca debería llegar aquí except ZeroDivisionError: print "Bloque exception division por cero" finally: # el bloque finally se ejecuta siempre una vez lanzada cualquiera excepcion print "Bloque finally" ## Crear nuestras propias excepciones class MyError(Exception): def __init__(self, value): # Necesitan un método init self.value = value def __str__(self): # Y un str para devolver el error return repr(self.value) try: raise MyError(2*2) # Con raise podemos lanzar la excepción except MyError as e: print 'Excepcion MyError lanzada, valor:', e.value
false
0fed16fe780b8ec9abf7e3114a8c44d7359bfd7e
huiba7i/Mycode
/python/class code/code4.22/2.ListTest.py
2,257
4.5
4
# 1.创建list对象 a = list() # 创建一个空的列表 a = list("hello") # 将一个序列对象(String,tuple,list,range)转换成一个list对象 a = list((1, [1, 2])) a = list([1, 2, [3, 4]]) b = range(10) # 创建一个 range对象 0-9 a = list(b) print(a) # 2. 切片 操作 和string相同 不会修改原有的list对象的 a = list(range(10)) b = a[2:] print(b) print(a) # 3.新增数据 会修改原有的list对象中的元素 extend 数据类型(list,tuple,string) a = list() print(a) a.append(1) print(a) a.extend([2, 3, 4]) # 将list中的元素 一个个的新增到一个新的list中 print(a) a.append([2, 3, 4]) # 将list对象当成一个元素 新增到一个list中 print(a) a.extend("123456") print(a) a.insert(0,['a','b']) # 在指定位置插入新的元素 print(a) # 4. 修改列表中的元素 a = [1, 2, 3, 4, 5] # 通过下标直接修改 a[0] = 10 # a[5] = 19 索引取值不能超出范围 print(a) # 切片修改 a[0:3] = [2, 3, 4] print(a) a = [1, 2, 3, 4, 5] a.reverse() # 反向list中的元素 print(a) a.sort() # 升序排列 print(a) a.sort(reverse=True) # 降序排列 print(a) # 5. 删除元素 # 5.1 删除变量 del a = "123" print(a) del a a = [1, 2, 3, 4, 5] del a[0] # 删除第一个元素 print(a) del a[2:] # 切片删除 print(a) # 5.2 方法删除 a = [1, 2, 3, 4, 5, 10] b = a.pop() # 删除最后一个元素 堆栈结构 print(b, ",", a) b = a.pop(0) # 删除第一个元素 print(b, ",", a) a = [1, 2, 3, 4, 5, 10, 1] a.remove(1) # 移除指定对象 print(a) # 5.3 其他操作 """ list.count(obj)统计某个元素在列表中出现的次数 list.index(obj)从列表中找出某个值第一个匹配项的索引位置 list.copy()复制列表 """ a = [1, 2, 3, 4, 5, 1] print(a.count(1)) print(a.index(1)) a = [1, 2, 3, 4, [1, 2, 3]] b = a.copy() # 复制一个列表 内容和a相同的 print(a) print(b) print(a == b) # == 比较两个对象中的内容是否相同 print(a is b) # is 比较两个对象是否是同一个对象 print(a[0] is b[0]) a[0] = 10 print(a, b) # a变 b不会变 a[4][0] = 10 print(a, b) # a和b都会发生改变 # a = 10 # b = 10 # print(a is b) # a = "abc" # b = "abc" # print(a is b) # a = [1] # b = [1] # print(a is b)
false
53e6351efa68672a423961055e6e5c3eb462f8f6
joelson91/my-old-projects
/password-file.py
885
4.15625
4
print('Diário pessoal') nome = input("Digite sua senha: ") while nome != "ask12": nome = input("Digite novamente ou saia: ") print ("Fim da execução") print ("Acesso liberado") print ("") print ("Diário pessoal") print ("escolha uma vítma") print ("digite 1 para Fulano") print ("digite 2 para Ciclano") vitima = float(input("Digite aqui: ")) if vitima == 1: print ("Você escolheu Fulano") print ("") senha = float(input("Digite a senha: ")) if senha == 123: print ("Acesso liberado") print ("") print ("Ele gosta de goiaba fresca.") else: print ("Você não tem permição para acessar") if vitima == 2: print ("Você escolheu Ciclano") print ("") senha = float(input("Digite a senha: ")) if senha == 321: print ("Acesso liberado") print ("") print ("Ele brinca com bonecas.")
false
06714b34733bb48d3ba92d38470c89bc13b40224
anamarquezz/Data-Structures-and-Algorithms-The-Complete-Masterclass
/BigONotation/01 Why we Need O Notations/NotBigO/question1_forLoop.py
456
4.125
4
''' Write a program to calculete sum of n natural numbers. For example, we will take n as 100 -> Using For Loop -> Using While Loop ''' import time time.time() timestamp1 = time.time() ###python Program to find Sum of N natural Numbers ### number = 100 total = 0 for value in range(1, number + 1): total = total + value print("The sum is", total) ### Program Completed ### timestamp2 = time.time() print((timestamp2 - timestamp1))
true
d8bbbc389e98c4c1bbd6524388726e8593b51cc1
bjoesa/minitools
/link_checker.py
1,415
4.125
4
#!/usr/bin/python3 """Check a Website (URL) for broken links. This little helper program was made to check website and link status on a given Website. Typical usage example: Simply execute the whole code. You'll be asked to provide an URL. Website and link status will be printed. """ from bs4 import BeautifulSoup import urllib3 import certifi http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) url = input('Type your URL: ') website = http.urlopen('GET', url) # try if url startswidth: 'http' else: raise exception soup = BeautifulSoup(website.data, "lxml") print('-------------------') sitestatus = website.status if sitestatus == 200: print('Website status OK (', sitestatus,')') elif sitestatus > 399: print('Website status: ', sitestatus,' (unauthorized)') else: print('Website status: ', sitestatus,' (sth. is strange `O.o´)') ''' processing : 102 ok : 200 unauthorized: 401 not_found : 404 ''' print('-------------------') print('Link list and connection test: ') for link in soup.findAll('a'): print('----------\nlink address:', link.get('href')) try: r = http.request('GET', link.get('href')) print('status: ', r.status) except: # if Exception is raised print('no connection test...') print('\n---- FINISH ----')
true
e7bf1c78f8a77a260760466350af187c6c6de0dd
eevlogieva/HackBulgaria_Programming101
/Problem_set_1/counting_vowels.py
237
4.125
4
def count_vowels(string): string = string.lower() vowels = ['a', 'i', 'e', 'o', 'u', 'y'] count = 0 for letter in string: if letter in vowels: count += 1 return count print(count_vowels("Python"))
false
c99f5031e44ad629b01e55ee62b1dbfd16b53e16
devam6316015/all-assignments
/assign 17 twinker GUI.py
1,992
4.40625
4
# print("Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface.") # import tkinter # from tkinter import * # import sys # def exit(): # print("Hello World") # sys.exit() # root=Tk() # b=Button(root,text="EXIT",width=20 ,command=exit) # b.pack() # root.mainloop() # print("\nQ2. Write a python program to in the same interface as above and create a action when the button is click it will display some text.") # import tkinter # from tkinter import * # import sys # def prnt(): # print("YoYo") # root=Tk() # b=Button(root,text="click!!!" ,width=10,height=2,bg="#111",fg="#777",command=prnt) # b.pack() # root.mainloop() # print("\nQ3. Create a frame using tkinter with any label text and two buttons.One to exit and other to change the label to some other text.") # import tkinter # from tkinter import * # import sys # def exit(): # sys.exit() # def change(): # label.config(text='chai pilo') # root=Tk() # root.title("window") # root.geometry("300x300") # label=Label(root,text='hello fraands') # label.pack() # f1=Frame(root) # f1.pack() # b1=Button(f1,text="exit",width=10,height=2,bg="#777",fg="#111",command=exit) # b1.grid(row=0,column=0) # b2=Button(f1,text="change",width=10,height=2,bg="#AAA",fg="#DDD",command=change) # b2.grid(row=1,column=0) # root.mainloop() # print("\nQ4. Write a python program using tkinter interface to take an input in the GUI program and print it.") # import tkinter # from tkinter import * # import sys # def show(): # print(listbox.get(ACTIVE)) # root=Tk() # def exit(): # sys.exit() # listbox=Listbox(root) # listbox.insert(1,'delhi') # listbox.insert(2,'chandigarh') # listbox.insert(3,'goa') # listbox.insert(4,'mumbai') # listbox.pack() # b1=Button(root,text="enter",width=10,height=2,bg="#AAA", fg="#EEE",command=show) # b1.pack() # b2=Button(root,text="exit",width=10,height=2,bg="#AAA", fg="#EEE",command=exit) # b2.pack() # root.mainloop()
true
178e21e0dc3e6f48565301bd039ec2ee1ea09829
TheAnand/Data_Structure
/Linkedlist basic operations.py
1,580
4.21875
4
class node : # creating a node class def __init__(self,data) : self.data = data self.next = None class linkedList : # creating a linkedlist class def __init__(self) : self.start = None # for view of the linked list def viewList(self) : # if node is empty then execute the if scope if self.start is None : print("Linked list is empty") # when node is not empty then execute the else scope else : temp = self.start while (temp): print(temp.data,end=' ') temp = temp.next # insertlist is written for insert node in linkedlist def insertList(self , value) : newNode = node(value) # linkedlist is empty then execute the if scope otherwise else scope if self.start is None : self.start = newNode else : temp = self.start while temp.next is not None : temp = temp.next temp.next = newNode # This function is wriiten for delete elements from the linkedlist def deleteList(self) : temp = self.start if temp.next is None : print("Linkedlist is empty") else : self.start = self.start.next # This function is written for count of nodes in linkedlist def getCount(self) : temp = self.start count = 0 while temp : count +=1 temp = temp.next return count mylist = linkedList() mylist.insertList(10) mylist.insertList(20) mylist.insertList(30) mylist.insertList(40) mylist.insertList(50) print(mylist.getCount(), end='\n') mylist.viewList() print("\n______________") mylist.deleteList() mylist.deleteList() mylist.viewList() print("\n______________") print(mylist.getCount())
true
28b55fbd9d9bcbb8a16e09969827287bd950af60
Day-bcc/estudos-python
/06-exercicios/exercicio-05.py
649
4.3125
4
''' Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato. ''' produto1 = float(input('Valor do produto 1: ')) produto2 = float(input('Valor do produto 2: ')) produto3 = float(input('Valor do produto 3: ')) if produto1 < (produto2 and produto3): print(f'Compra o produto1, olha o preço {produto1}') elif produto2 < (produto1 and produto3): print(f'Compra o produto2, olha o preço {produto2}') elif produto3 < (produto1 and produto2): print(f'Compra o produto3, olha o preço {produto3}') else: print("Você digitou algo errado!!!")
false
c181fb04234b575f8539abf1647be1543ddb3021
isaacrael/python
/Code Cademy/average_numbers_dict_challenge_exercise_practice.py
868
4.375
4
"""Written By: Gil Rael The following python program demonstrates the use of a function called average that takes a list of numbers as input and then prints out the average of the numbers. Algorithm: Step 1: Create list of numbers called lst = [80,90] Step 2: total_values equals the length of the list Step 3: total_homework equals the sum of the homework scores Step 4: average_homework = float(total_homework / total_values) Step 5: Define function called average """ # Initialize Variables # Define Functions lst = [80,90] def average(lst): for number in (lst): total_values = float(len(lst)) total_homework = float(sum(lst)) average_homework = float(total_homework / total_values) print "Lloyd's average homework score equals", average_homework return average_homework average(lst)
true
d647f46125b4bed90bf42ec5f46442a8d0672afd
isaacrael/python
/Code Cademy/for_loop_list.py
267
4.21875
4
"""Written By: Gil Rael The following python program demonstrates the use of the for loop with a list""" # Initialize Variables # Define Functions my_list = [1,9,3,8,5,7] for number in my_list: new_num = number * 2 # Your code here print new_num
true
1b1136eccad94ad29b159d7f64c01f171821dd0d
isaacrael/python
/Code Cademy/grocery_store_loop_determine_inventory_value.py
1,543
4.28125
4
"""Written By: Gil Rael The following python program demonstrates the use of a function to calculate the value of inventory in a grocery store and print the result""" """Algorithm: Step 1: Create grocery_store_inventory_value function - Done Step 2: Pass dictionaries prices, stock - Done Step 3: Print prices & stock - Done Step 4: Loop through prices - Done Step 5: Print key & values in prices - Done Step 6: Loop through stock - Done Step 7: Print key & values in stock - Done Step 8: Initialize inventory_value = 0 - Done Step 9: Create nested for loops - Done Step 10: Multiply price by stock to get inventory_value = price * stock - Done Step 11: Sum inventory_value - Done Step 12: Print "The value of inventory equals", inventory_value - Done """ # Initialize Variables # Define Functions prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } def grocery_store_inventory_value(prices,stock): print prices print stock print inventory_value = 0 for key in prices: for key in stock: print key, "stock : " + str(stock[key]) print key, "prices : " + str(prices[key]) inventory_value = inventory_value + (stock[key] * prices[key]) break print print "The value of inventory in your grocery store equals", inventory_value grocery_store_inventory_value(prices,stock)
true
af3a71e7e14e40fdda72d8ac9c3bb8933327e83f
rajivnagesh/pythonforeverybodycoursera
/assignment7.1.py
322
4.5625
5
# Write a program that prompts for a file name, then opens that file and reads through the file,and print the contents of the file in upper case. #Use the file words.txt to produce the output below. fname=input('Enter file name:') fhand=open(fname) for ab in fhand: bc=ab.rstrip() print(bc.upper())
true
653bb16ca399e7bb704b9a8ad1f13fefa22d1caf
Nyarko/Intro_To_Python
/RadiusSurfAreaVolume.py
262
4.21875
4
import math radius = int(input("Input the radius: ")) def surface(): ans = radius**2 *math.pi * 4 return ans def volume(): vol = radius**3 *math.pi*4/3 return vol print ("The surface area is: ", surface()) print ("The volume is: ", volume())
true
e7e3f7d9a762c66b6e99bb6a593c04c848622f1e
draftybastard/DraftyJunk
/pre_function_exc.py
874
4.28125
4
# Function has a single string parameter that it checks s is a single word starting with "pre" # # Check if word starts with "pre" # Check if word .isalpha() # if all checks pass: return True # if any checks fail: return False # Test # get input using the directions: *enter a word that starts with "pre": * # call pre_word() with the input string # test if return value is False and print message explaining not a "pre" word # else print message explaining is a valid "pre" word # # [ ] create and test pre_word() def pre_word(user_word): if user_word.isalpha(): if user_word.lower()[0:3] == "pre": return True else: return False def test(): if pre_word(user_word): print("nailed it!") else: print("nah") user_word = input("Like the usual, gimme a word") test()
true
80f0837dcc9768d491dab8129ea8a40c1b38cf55
atashi/LLL
/algorithm/Reverse-Integer.py
922
4.28125
4
# Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # # Input: 123 # Output: 321 # # Example 2: # # Input: -123 # Output: -321 # # Example 3: # # Input: 120 # Output: 21 # # Note: # Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. class Solution: def reverse(self, x): """ :type x: int :rtype: int """ sign = 1 if x > 0 else -1 result = sign * int("".join(reversed(str(sign * x)))) if result > 2**31 - 1 or result < -2**31: return 0 return result if __name__ == "__main__": s = Solution() print(s.reverse(123)) print(s.reverse(-123)) print(s.reverse(-120)) print(s.reverse(12345678890888548375827))
true
00a6d007b2baa298b778683bf9f5b3dc3f1a0036
atashi/LLL
/python/fluentPython/1/1-2.py
1,018
4.1875
4
from math import hypot class Vector: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): """ __repr__ 方法返回的字符串应该是准确,无歧义的。 __str__的区别在于,__str__ 是用str()函数的时候被使用,或者是print函数的时候调用str函数。str对 终端用户友好。 当无str函数的时候,解析器将会用repr替代。 https://stackoverflow.com/questions/1436703/difference-between-str-and-repr Alex Martelli """ return 'Vector ({}, {})'.format(self.x, self.y) def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __mul__(self, scale): x = self.x * scale y = self.y * scale return Vector(x, y) a = Vector(1, 1) b = Vector(2, 3) print(a + b) print(a * 2)
false
4c8a2419bcfc76d92cc2be4485abc68a270fdb19
atashi/LLL
/algorithm/Reverse-Linked-List.py
1,829
4.34375
4
# Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could you implement both? # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: h = head p = None while h: if p is None: p = ListNode(h.val) h = h.next else: temp = ListNode(h.val) temp.next = p p = temp h = h.next return p def reverseList1(self, head: ListNode) -> ListNode: if head is None: return None self.reverseUtil(head, None) return head def reverseUtil(self, curr, prev): # If last node mark it head if curr.next is None: self.head = curr # Update next to prev node curr.next = prev return # Save curr.next node for recursive call next = curr.next # And update next curr.next = prev self.reverseUtil(next, curr) def reverseList2(self, head: ListNode) -> ListNode: prev = None curr = head while curr is not None: next = curr.next curr.next = prev prev = curr curr = next return prev def printNodes(h): while h: print(h.val, end="->") h = h.next if __name__ == "__main__": h = ListNode(1) h.next = ListNode(2) h.next.next = ListNode(3) h.next.next.next = ListNode(4) h.next.next.next.next = ListNode(5) s = Solution() printNodes(s.reverseList2(h))
true
3c22676065cf4299c683802351281b728b0a71d6
atashi/LLL
/python/interfaces_in_python.py
1,575
4.25
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # from link http://masnun.rocks/2017/04/15/interfaces-in-python-protocols-and-abcs/ # informal interfaces: Protocols / Duck typing class Team(object): def __init__(self, members): self._members = members def __len__(self): return len(self._members) def __contains__(self, member): return member in self._members def __str__(self): return " ".join(self._members) __repr__ = __str__ # formal interfaces: ABCs import abc class Bird(metaclass=abc.ABCMeta): @abc.abstractmethod def fly(self): pass class Parrot(Bird): def fly(self): print("flying") class Aeroplane(metaclass=abc.ABCMeta): @abc.abstractmethod def fly(self): pass class Boeing(Aeroplane): def fly(self): print("flying") # virtual subclass @Bird.register class Robin: pass def main(): # Protocols team = Team(["batman", "wonder woman", "flash"]) print(team) print(len(team)) print("batman" in team) print("="*50) # Duck typing ducks = [team, ["abc", "cde"]] for duck in ducks: print("the duck is", duck) print(len(duck)) print("batman" in duck) print("="*50) # ABCs p = Parrot() print(isinstance(p, Bird)) print(isinstance(p, Parrot)) b = Boeing() print(isinstance(b, Parrot)) print("="*50) # virtual subclass r = Robin() print(isinstance(r, Robin)) print(isinstance(r, Bird)) print("="*50) if __name__ == '__main__': main()
false
0bd7ce5e366a0578aa88aee81c908b443db28d76
AllenHongjun/cs61a
/lab/61a-su20-mt-solution/q6/q6.py
2,749
4.15625
4
email = 'example_key' def copycat(lst1, lst2): """ Write a function `copycat` that takes in two lists. `lst1` is a list of strings `lst2` is a list of integers It returns a new list where every element from `lst1` is copied the number of times as the corresponding element in `lst2`. If the number of times to be copied is negative (-k), then it removes the previous k elements added. Note 1: `lst1` and `lst2` do not have to be the same length, simply ignore any extra elements in the longer list. Note 2: you can assume that you will never be asked to delete more elements than exist >>> copycat(['a', 'b', 'c'], [1, 2, 3]) ['a', 'b', 'b', 'c', 'c', 'c'] >>> copycat(['a', 'b', 'c'], [3]) ['a', 'a', 'a'] >>> copycat(['a', 'b', 'c'], [0, 2, 0]) ['b', 'b'] >>> copycat([], [1,2,3]) [] >>> copycat(['a', 'b', 'c'], [1, -1, 3]) ['c', 'c', 'c'] """ def copycat_helper(lst1, lst2, lst_so_far): if len(lst1) == 0 or len(lst2) == 0: return lst_so_far if lst2[0] >= 0: lst_so_far = lst_so_far + [lst1[0] for _ in range(lst2[0])] else: lst_so_far = lst_so_far[:lst2[0]] return copycat_helper(lst1[1:], lst2[1:], lst_so_far) return copycat_helper(lst1, lst2, []) # ORIGINAL SKELETON FOLLOWS # def copycat(lst1, lst2): # """ # Write a function `copycat` that takes in two lists. # `lst1` is a list of strings # `lst2` is a list of integers # It returns a new list where every element from `lst1` is copied the # number of times as the corresponding element in `lst2`. If the number # of times to be copied is negative (-k), then it removes the previous # k elements added. # Note 1: `lst1` and `lst2` do not have to be the same length, simply ignore # any extra elements in the longer list. # Note 2: you can assume that you will never be asked to delete more # elements than exist # >>> copycat(['a', 'b', 'c'], [1, 2, 3]) # ['a', 'b', 'b', 'c', 'c', 'c'] # >>> copycat(['a', 'b', 'c'], [3]) # ['a', 'a', 'a'] # >>> copycat(['a', 'b', 'c'], [0, 2, 0]) # ['b', 'b'] # >>> copycat([], [1,2,3]) # [] # >>> copycat(['a', 'b', 'c'], [1, -1, 3]) # ['c', 'c', 'c'] # """ # def copycat_helper(lst1, lst2, lst_so_far): # if len(lst1) == 0 or len(lst2) == 0: # return lst_so_far # if lst2[0] >= 0: # lst_so_far = lst_so_far + [lst1[0] for _ in range(lst2[0])] # else: # lst_so_far = lst_so_far[:lst2[0]] # return copycat_helper(lst1[1:], lst2[1:], lst_so_far) # return copycat_helper(lst1, lst2, [])
true
a1446fd759d59326a85e4e6d374ba46de3f516a7
avdata99/programacion-para-no-programadores
/code/01-basics/strings-03.format.py
689
4.21875
4
""" Opciones para concatenar strings con variables """ nombre = 'Pedro' pais = 'Chile' print("Hello world {} de {}!".format(nombre, pais)) # Hello world Pedro de Chile! # valores enumerados print("Valores enumerados. Hello world {0} de {1} ({0}-{1})!".format(nombre, pais)) # Valores enumerados. Hello world Pedro de Chile (Pedro-Chile)! # valores con nombre print("Valores con nombre. Hello world {name} de {country}!".format(name=nombre, country=pais)) # Valores con nombre. Hello world Pedro de Chile! # Estilo C print("Estilo C. Hello world %s de %s !" % (nombre, pais)) # Estilo C. Hello world Pedro de Chile ! # Nueva opcion desde python 3.6 print(f"Hello world {nombre} de {pais}!") # Hello world Pedro de Chile!
false
ce7e7328205e73974542567363d64d0295c88b8b
avdata99/programacion-para-no-programadores
/code/01-basics/tp-02-fraccion-ejercicio/fracciones-ema-corregido.py
1,945
4.125
4
class Fraccion: def __init__(self, numerador, denominador): self.num = numerador self.den = denominador self.validar() def __str__(self): return f'{self.num}/{self.den}' def validar(self): if self.den == 0: raise ValueError('El denominador de la fraccion no debe ser 0') def __add__(self, otro): if type(otro) != Fraccion: raise ValueError('Solo se puede sumar una Fraccion') self.validar() otro.validar() if self.den != otro.den: nuevoDen = self.den * otro.den nuevoNum = self.num * otro.den + self.den * otro.num else: nuevoNum = self.num + otro.num nuevoDen = self.den return Fraccion(nuevoNum, nuevoDen) def __eq__(self, otro): self.validar() otro.validar() f1 = self.num / self.den f2 = otro.num / otro.den return f1 == f2 print(Fraccion(3,5) + Fraccion(4,3)) print(Fraccion(29,15)) assert Fraccion(3, 5) + Fraccion(4, 3) == Fraccion(29, 15) assert Fraccion(1, 2) + Fraccion(1, 4) == Fraccion(6, 8) assert Fraccion(1, 3) + Fraccion(2, 4) == Fraccion(10, 12) print("Todo Ok!") """ # Primera version sin __add__ class Fraccion: def __init__(self, numerador, denominador): self.num = numerador self.den = denominador def __str__(self): return f'{self.num}/{self.den}' def __add__(self, otro): if type(otro) != Fraccion: raise ValueError('Solo se puede sumar un Fraccion') def suma(fr1, fr2): if fr1.den != fr2.den: nuevoDen = fr1.den * fr2.den nuevoNum = fr1.num * fr2.den + fr1.den * fr2.num else: nuevoNum = fr1.num + fr2.num nuevoDen = fr1.den return Fraccion(nuevoNum, nuevoDen) fraccion1 = Fraccion(4,2) fraccion2 = Fraccion(2,9) resultado = suma(fraccion1, fraccion2) print(resultado) """
false
f4c071400f9be450a8601f90082849c6e21dc1f2
cs50Mu/wonderland
/cs61a/cs61a2014/www-inst.eecs.berkeley.edu/~cs61a/su14/lecture/exceptions.py
331
4.3125
4
## Commented out so that the entire file doesn't error # ValueError('Andrew made a ValueError') ## Break the program by raising the actual error # raise ValueError('Andrew made a ValueError') while True: try: x = int(input('Type in an Integer: ')) print(x+10) except ValueError: print('Not a valid integer! :(')
true
c94b3229da293b56f9a8ba689105e77078dedbe7
pavankat/python-fun
/python-review-quiz.py
2,167
4.25
4
# 1. # make a variable called a, set it to 2 # make a variable called b, set it to 3 # add the variables together a = 2 b = 3 print(a+b) c = a+b print(c) # 2. # write a conditional statement that prints out hello if b is greater than a # 3. # add an else to the previous conditional statement so that it prints bye if the first conditional is not met if b > a: print("hello") else: print("bye") # 4. write a function that takes in a string argument # and returns the string with the letter a added to it def add_a(str): return str+"a" def add_a(str): c = str + "a" return c # optional user_input = input('give me a word') print(add_a(user_input)) # 3:03 # 5. how would you get the first element of a list named animals animals[0] # 6. how would you get the last element of a list named animals animals[-1] animals[len(animals)-1] # 7. how would you get the 3rd element of a list named animals animals[2] # 8. initialize a variable named nums to a list # and then loop from 1 to 5 and add each number to the nums list # then print out the nums # 3:13 nums = [] for i in range(1,6): nums.append(i) print(nums) # 9. write a function that takes in a string and reverses it and returns the reversed string # dog -> god # cat -> tac # 3:23 def reverse_string(str): rev = "" for s in str: rev = s + rev return rev def reverse_string(str): str_list = list(str) str_list.reverse() return ''.join(str_list) def reverse_string(str): str_list = list(str) rev = str_list[::-1] return ''.join(rev) print(reverse_string("dog")) #god # rev = "" # rev = "d" + "" # rev = "d" # rev = "o" + "d" # rev = "od" # rev = "g" + "od" # rev = "god" fibonacci: 1,1,2,3,5,8,13,21 write a function that takes a number and returns that many numbers in the fibonacci sequence 0 -> [] 1 -> [1] 2 -> [1,1] 3 -> [1,1,2] -> 0th + 1st -> 2nd 4 -> [1,1,2,3] -> 1st + 2nd -> 3rd def fib(n): fib_list = [1,1] if n==0: return [] elif n==1: return [1] elif n== 2: return fib_list else: # do more here for i in range(2,n+1): next_num = fib_list[-1] + fib_list[-2] fib_list.append(next_num) return fib_list
true
808df9c219bb52dd19445b29c6440fba0be174a6
TheCaptainFalcon/DC_Week1
/nested_dictionary.py
811
4.4375
4
ramit = { 'name': 'Ramit', 'email': 'ramit@gmail.com', 'interests': ['movies', 'tennis'], 'friends': [ { 'name': 'Jasmine', 'email': 'jasmine@yahoo.com', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': 'jan@hotmail.com', 'interests': ['movies', 'tv'] } ] } #Write a python expression that obtains the email address of Ramit print (ramit["email"]) #Write a python expression that get the first interests of Ramit print (ramit["interests"][0]) #Write a python expression that gets the email address of Jasmine for x in ramit["friends"]: if x["email"] == "jasmine@yahoo.com": print(x["email"]) #Write a python expression that gets the second of Jan's two interests for x in ramit["friends"]: if x["name"] == "Jan": print(x["interests"][1])
false
02cd606aafa075ca5fc14e5be35db18621d42e47
TheCaptainFalcon/DC_Week1
/python_banner.py
292
4.1875
4
# string = input("Enter a string: ") # print ("*") * (len(string)+6) # print ("* ") + string + (" *") # print ("*") * (len(string)+6) string = input('Enter any string: ') add_string = (len(string) + 6) print ('*') + add_string print ('* ') + string + (' *') print ('*') + len(string)+6
false
a4f336d0e32f811e30239a26cde94d5f7884674a
TheCaptainFalcon/DC_Week1
/tip_calc2.py
949
4.25
4
#Conversion of input into float as base bill_amount = float(input("What is your total bill amount?")) #str() not required - but helps with organization service_level = str(input("Level of service? ('good', 'fair', 'bad') ")) if service_level == "good": #bill_amount input is converted to float -> tip_amount = float too #think of it as float * float tip_amount = .20 * bill_amount elif service_level == "fair": tip_amount = .15 * bill_amount elif service_level == "bad": tip_amount = .10 * bill_amount #now total_bill_amount -> float total_bill_amount = tip_amount + bill_amount #in order to even out types, it is necessary for split to be float split = float(input("Split how many ways?")) split_amount = total_bill_amount / split #notice the "$" in the "$%.2f" print("Tip amount: "+ "$%.2f " % tip_amount) print("Total amount: " + "$%.2f" % total_bill_amount) print("Amount per person " + "$%.2f" % split_amount)
true
17c4e5bf0d0a02585bfd4c50f30142954e439138
vijaicv/deeplearning-resources
/self_start/Learn_Numpy/Numpy_Basics/Creating_Arrays.py
1,065
4.21875
4
import numpy as np # 1-d array a=np.array([2,4,6,8]) #creates an array with given list print(a) a=np.arange(2,10,2) #similar to range() 2 to 9 in steps of 2 print(a) a=np.linspace(2,8,4) #creates an array with 4 elements equally spaced between 2 and 8 print(a) #now lets try 2-d arrays print("\n\n 2-d array\n using list of tuples") a=np.array([(1,2,3),(4,5,6),(7,8,9)]) #creates a 2d array print(a) print('using list of lists') a=np.array([[1,2,3],[4,5,6],[7,8,9]]) #creates a 2d array print(a) a=np.array([(1,2,3),(4,5,6),(7,8,9)],dtype=np.int8) #specify the datatype print("zeros") a=np.zeros((3,4)) #creates an array of zeroes with 3 rows and 4 columns print(a) a=np.zeros(10) #creates an array of 10 zeros print(a) print("\n ones") a=np.ones((3,4)) #creates an array of zeroes with 3 rows and 4 columns print(a) a=np.ones(10) #creates an array of 10 ones print(a) print("\n Random values") a=np.random.random((3,2)) #array of random values print(a) a=np.random.randint(0,20,6) #array of random values print(a)
true
29f894ae29d361069dcb3999d6c02fec42ffe81a
vinhpham95/python-testing
/BasicEditor.py
1,287
4.21875
4
# Vinh Pham # 10/11/16 # Lab 7 - Basic Editor # Reads each line from word.txt and copy to temp.txt unless asked to change the line. # Open appopriate files to use. words_file = open("words.txt","r") temp_file = open("temp.txt","w") line_counter = 0 # To count each line; organization purposes. # Read each line seperately and change if program receives an input. for line_str in words_file: line_counter +=1 replacement = input("What do you want to replace for line {}: {}".format(line_counter,line_str)) if replacement == "": print (line_str,end="",file=temp_file) else: print (replacement,file=temp_file) replacement = "" # Resets to no input. # Necessity words_file.close() temp_file.close() # This is a test code to read the temp_file. ##temp_file = open("temp.txt","r") ##for line_str in temp_file: ## print(line_str) ## ##temp_file.close() # Copy everything back into words_file, overwriting it. words_file = open("words.txt","w") temp_file = open("temp.txt","r") for line_str in temp_file: print(line_str,end="",file=words_file) words_file.close() temp_file.close() # This is a test code to read the finished words_file. ##words_file = open("words.txt","r") ##for line_str in words_file: ## print(line_str) ## ##words_file.close()
true
083a971122bc3c0231b5f2014ebc7bb94f3bee6f
vinhpham95/python-testing
/StringFun.py
1,403
4.4375
4
#Vinh Pham # 9/27/16 # Lab 5 # Exercise 1:Given the string "Monty Python": # (a) Write an expression to print the first character. # (b) Write an expression to print the last character. # (c) Write an expression inculding len to print the last character. # (d) Write an expression that prints "Monty". # Exercise 2: Given the string "homebody": # (a) Write an expression using slicing to print "home". # (b) Write an expression using slicing to print "body". # Exercise 3: Given a variable S containing a string of even length: # (a) Write an expression to print out the first half of the string. # (b) Write an expression to print out the second half of the string. # Exercise 4:Given a variable S containing a string of odd length: # (a) Write an expression to print the middle character. # (b) Write an expression to print the string up to but not including the middle character # (c) Write an expression to print the string from the middle # character to the end (not including the middle character). # Exercise 1 string_1 = "Monty Python" print (string_1[0]) print (string_1[-1]) print (string_1[len(string_1)-1]) print (string_1[:5]) # Exercise 2. string_2 = "homebody" print (string_2[0:4]) print (string_2[4:]) #Exercise 3. s = "123456" print (s[:int(len(s)/2)]) print (s[int(len(s)/2):]) #Exercise 4. s = "123456789" print (s[int(len(s)/2)]) print (s[:int(len(s)/2)]) print (s[int(len(s)/2+1):])
true
d1734064123a7d1cd0b4a4c9100743b2ca94ca69
StrawHatAaron/python3_fun
/python_collections/sillycase.py
681
4.3125
4
#Aaron Miller #Feb 17 2017 #python 3.6.0 #this program will make the first half of a string lower case and the second half upper caase #by using the made sillycase method def sillycase(fun_stuff): half_uppercase = fun_stuff[len(fun_stuff)//2:].upper() half_lowercase = fun_stuff[:len(fun_stuff)//2].lower() return half_lowercase+half_uppercase print(sillycase("LoveYourLife")) print(sillycase("GetYourPassion")) print(sillycase("BeUrBest")) #abstract: note: pointers are not created when using splice thing = "some things" other_thing = thing other_thing="if this equals thing then when you dont you splice your create something very close to a pointer"#it does not print(thing)
true
fc89d543eb0e4339334edef14dae4b597f802bf0
Prakashchater/Leetcode-array-easy-questions
/LongestSubarray.py
1,443
4.1875
4
# Python3 implementation to find the # longest subarray consisting of # only two values with difference K # Function to return the length # of the longest sub-array def longestSubarray(arr, n, k): Max = 1 # Initialize set s = set() for i in range(n - 1): # Store 1st element of # sub-array into set s.add(arr[i]) for j in range(i + 1, n): # Check absolute difference # between two elements if (abs(arr[i] - arr[j]) == 0 or abs(arr[i] - arr[j]) == k): # If the new element is not # present in the set if (not arr[j] in s): # If the set contains # two elements if (len(s) == 2): break # Otherwise else: s.add(arr[j]) else: break if (len(s) == 2): # Update the maximum length Max = max(Max, j - i) # Remove the set elements s.clear() else: s.clear() return Max # Driver Code if __name__ == '__main__': arr = [1, 1, 1, 2, 2, 3, 3] N = len(arr) K = 1 length = longestSubarray(arr, N, K) if (length == 1): print("-1") else: print(length) # This code is contributed by himanshu77
true
c9f386c320f571798a0f4637bcfa0004dadffced
muhzulfik/python-dasar
/set.py
658
4.21875
4
fruits = {'banana', 'grape', 'pinapple'} print(type(fruits)) print(fruits) # Access Items for x in fruits: print(x) # Add Items fruits.add('apple') print(fruits) fruits.update(['sawo','rasberry']) print(fruits) # Get The Length print(len(fruits)) # Remove Item fruits.remove("banana") print(fruits) fruits.discard("banana") print(fruits) fruits.pop() print(fruits) fruits.clear() #empties the set print(fruits) del fruits # delete the set # Join Two Set fruits1 = {'banana', 'grape', 'pinapple'} fruits2 = {'apple', 'mango', 'jackfruits'} fruits4 = {'sawo'} fruits3 = fruits1.union(fruits2) print(fruits3) fruits1.update(fruits2) print(fruits1)
true
ffd27b28d2f3ad9f5cdf347fc9aaf3ef346582fb
paulfranco/code
/python/adjacent_elements_product.py
587
4.25
4
# Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. # Example # For inputArray = [3, 6, -2, -5, 7, 3], the output should be # adjacentElementsProduct(inputArray) = 21. # 7 and 3 produce the largest product. def adjacentElementsProduct(inputArray): product = -1001 for i in range(len(inputArray)-1): if (int(inputArray[i] * inputArray[i+1]) > product): product = int(inputArray[i] * inputArray[i+1]) print(product) return product my_array = [-23, 4, -3, 8, -12] adjacentElementsProduct(my_array)
true
9d324dc3cdb0f98519bc5a5620836a200d46aae0
paulfranco/code
/python/hexadecimal_output.py
226
4.15625
4
user_input = raw_input("Enter a hex number") output = 0 for power, hex_digit in enumerate(reversed(user_input)): print("{} * 16 ** {}".format(hex_digit, power)) output += int(hex_digit, 16) * (16 ** power) print(output)
true
7483b2b593dc962382a7af3c802059202cf12e2e
paulfranco/code
/python/longest_word.py
333
4.25
4
# Create a program that reads some files and returns the longest word in those files import os dirname = input("Enter a dirname: ") def longest_word(filename): return max(open(dirname + '/' + filename).read().split(), key=len) print({dirname + "/" + filename: longest_word(filename) for filename in os.listdir(dirname)})
true
bb1e67d84dc6c7d98a0b5f379304f41fb474b5bc
paulfranco/code
/python/element-wise_operations.py
809
4.46875
4
# The Python way # Suppose you had a list of numbers, and you wanted to add 5 to every item in the list. Without NumPy, you might do something like this: values = [1,2,3,4,5] for i in range(len(values)): values[i] += 5 # now values holds [6,7,8,9,10] # That makes sense, but it's a lot of code to write and it runs slowly because it's pure Python. # Note: Just in case you aren't used to using operators like +=, that just means "add these two items and then store the result in the left item." It is a more succinct way of writing values[i] = values[i] + 5. The code you see in these examples makes use of such operators whenever possible. # The NumPy way # In NumPy, we could do the following: values = [1,2,3,4,5] values = np.array(values) + 5 # now values is an ndarray that holds [6,7,8,9,10]
true
2f41c91d5dd1de35c6dcc4e19a8b5c968efec774
wendyliang714/GWCProjects
/binarysearch.py
1,119
4.25
4
import csv import string # Open the CSV File and read it in. f = open('countries.csv') data = f.read() # Split the data into an array of countries. countries = data.split('\n') length = len(countries) print(countries) # Start your search algorithm here. user_input = input("What country are you searching for?:") #Initialize variables found = False #Use single "=" to set a variable firstPoint = 0 lastPoint = length-1 #start loop while firstPoint <= lastPoint and found == False: #Use double == to check conditions midPoint = int((firstPoint + lastPoint) / 2) if user_input == countries[midPoint]: #Use double == to check condition found = True #Use single "=" to change variable else: if user_input > countries[midPoint]: firstPoint = midPoint + 1 else: lastPoint = midPoint - 1 # If the city is found, then print the city name. Else, print an error message! if found == False: print("Your country is not in the country list!") else: print("Your country is in the country list. It is %s." % user_input)
true
f036cb3bd76671f9d2db54b06180bb7635d6e519
lambdaplus/python
/fibnacci/fibone.py
639
4.28125
4
斐波那契数列的几种算法 1. 普通的循环 ```python # -*- coding: utf-8 -*- def fib(n): lst = [] m, a, b = 0, 0, 1 for m in range(n): lst.append(a) a, b = b, a + b return lst if __name__ == "__main__": n = int(input('Please input n > ')) print(fib(n)) ``` 2. 高效的生成器 ```python def fib(n): m, a, b = 0, 0, 1 for m in range(n): yield a a, b = b, a + b if __name__ == '__main__': lst = [] n = int(input('Please input n > ')) for i in fib(n): lst.append(i) print(lst) ``` ## 当然还有各种lambda奇淫技巧,不写了!
false
4ed46c72d1b746d0d8f3c93e2c053995baa65f2e
lambdaplus/python
/Algorithm/sort/merge/merge-sort1.py
1,061
4.1875
4
# coding: utf-8 -*- from random import randrange from heapq import merge ''' Help on function merge in module heapq: merge(*iterables, key=None, reverse=False) Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] If *key* is not None, applies a key function to each element to determine its sort order. >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len)) ['dog', 'cat', 'fish', 'horse', 'kangaroo'] ''' def merge_sort(L): if len(L) < 2: return L mid = len(L) // 2 left = merge_sort(L[:mid]) right = merge_sort(L[mid:]) return list(merge(left, right)) if __name__ == "__main__": L = [randrange(100) for _ in range(10)] print(merge_sort(L))
true
c46cc3386df1af5828c197bdc3f607ff6145470d
caiosainvallio/estudos_programacao
/curso_em_video/exe090.py
531
4.25
4
"""Exercício criado por: https://www.cursoemvideo.com/ 090: Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela.""" nome = str(input('Nome: ')).strip().capitalize() media = float(input(f'Média de {nome}: ')) boletim = {'Nome': nome, 'Média': media} if boletim['Média'] >= 7: boletim['Situação'] = 'Aprovado' else: boletim['Situação'] = 'Reprovado' for c, v in boletim.items(): print(f'{c} é igual a {v}')
false
0d2308f348f54749c9ed17cc0e90e6dac76ee0d8
caiosainvallio/estudos_programacao
/curso_em_video/exe079.py
666
4.34375
4
"""Exercício criado por: https://www.cursoemvideo.com/ 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.""" num = [] while True: n = int(input('Digite um valor: ')) if n not in num: num.append(n) print('Valor adicionado com sucesso...') else: print('Valor duplicado! Não vou adicionar...') sn = input('Deseja continuar? [s/n] ') if sn.upper() == 'N': break print(f'Você digitou os valores {sorted(num)}')
false
7a105f093edb2dc3e694a96a1080b51f6412d4bc
caiosainvallio/estudos_programacao
/curso_em_video/exe081.py
803
4.21875
4
"""Exercício criado por: https://www.cursoemvideo.com/ 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista.""" lista = [] cont = 0 while True: n = int(input('Digite um valor: ')) lista.append(n) sn = input('Quer continuar? [s/n] ') cont += 1 while not sn in 'sn': sn = input('Quer continuar? [s/n] ') if sn == 'n': break print('-=' * 30) print(f'Você digitou {cont} elementos') print(f'Os valores em ordem decrescente são {sorted(lista, reverse=True)}') if 5 in lista: print(f'O valor 5 faz parte da lista!') else: print(f'O valor 5 não faz parte da lista!')
false
c6b689c3d14f1e40352dbe330935b52a242ce388
caiosainvallio/estudos_programacao
/curso_em_video/exe003.py
295
4.28125
4
"""Exercício criado por : https://www.cursoemvideo.com/ 003 Crie um programa que leia os números e mostre a soma entre eles""" n_um = int(input('Digite um valor: ')) n_dois = int(input('Digite outro valor: ')) print('A soma entre {} e {} é agual a {}!'.format(n_um, n_dois, n_um + n_dois))
false
eec4fa3f1bba458d7c2308e65d98d4bdc8bab6b9
caiosainvallio/estudos_programacao
/curso_em_video/exe076.py
606
4.125
4
"""Exercício criado por: https://www.cursoemvideo.com/ 076: Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.""" prod = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.9, 'Estojo', 25, 'Transferidor', 4.2, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.3, 'Livro', 34.9) print('-'*50) print('{:^50}'.format('LISTAGEM DE PREÇOS')) print('-'*50) for i in range(0, len(prod), 2): print('{:.<40}R$'.format(prod[i]), f'{prod[i + 1]:7.2f}') print('-'*50)
false
715547606ef16c02521aad061acfe56bb7087597
caiosainvallio/estudos_programacao
/curso_em_video/exe074.py
696
4.15625
4
"""Exercício criado por: https://www.cursoemvideo.com/ 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.""" from random import randint num = [] for i in range(5): num.append(randint(1, 9)) num = tuple(num) maior = menor = 0 print('Os valores sorteados foram:', end=' ') for i, n in enumerate(num): if i == 0 or n < menor: menor = n if n > maior: maior = n if i < 4: print(n, end=' ') else: print(n) print(f'O maior valor sorteado foi {maior}') print(f'O menor valor sorteado foi {menor}')
false
5d536548351316a497529dc64ffb2f7660adff1f
thalitazm/revisaoPython
/operadoresCondicionais.py
478
4.15625
4
# -*- coding: utf-8 #Operadores Condicionais: if 5 > 3: print('5 é maior que 3') #print teste if 5 > 4: print('5 é maior') else: print('5 não é maior que 4') n = 9 if n == 4: print('n é igual a 4') else: if n == 3: print('n é igual a 3') else: print('n não é igual a 4 nem 3') x = 2 y = 6 if (x > 1) and (y % 2 == 0): print('x é maior que 1 e y é par') else: print('uma ou nenhuma das condições foram satisfeitas')
false
31c52ba996b1ab82e3e91e76532777bc2ec836fb
iKalyanSundar/Log-Parsing
/modul.py
2,143
4.15625
4
import glob import sys import os.path import pandas as pd #function to get path in which csv files should be scanned def get_file_path_input(): input_path=input("Enter Path where the output file has to be created: ") while (input_path is None) or (input_path == ''): input_path=input("Enter Path where the output file has to be created: ") if os.path.exists(input_path): return input_path else: os.mkdir(input_path) return input_path #Function to get number of input files to be generated, from user def get_num_of_input_files(): num_file=input("Enter number of input csv files that neeeds to be generated: ") while(num_file is None or num_file == ''): num_file=input("Enter number of input csv files that neeeds to be generated: ") return num_file #Function to get number of sets of 3 line string to be written to each input csv file def get_num_of_lines(): num_lines=input("Enter number of sets of 3 line input string to be generated in each input csv files: ") while(num_lines is None or num_lines == ''): num_file=input("Enter number of input csv files that neeeds to be generated: ") return num_lines #function to check if a filepath exists or not (returns true or false) def path_check(pathofFile): path_chk=os.path.exists(pathofFile) return path_chk #function to create dataframe from csv file def create_df(filepath,nm): if (filepath is None or nm is None) or (filepath == '' or nm == ''): print("Both filepath and header list are mandatory parameter for creating a dataframe. Please provide all parameters") #creating an empty dataframe data=pd.DataFrame() return data else: data=pd.read_csv(filepath,names=nm) return data #function to remove specified extension files from the specified path def remove_files_from_dir(path,ext): full_ext="."+str(ext) filelist = [ f for f in os.listdir(str(path)) if f.endswith(full_ext) ] for f in filelist: os.remove(os.path.join(str(path),f))
true
864a7a46c53c3d87cd09fbce26423aa8c1ccd7e9
jimjshields/pswads
/4_recursion/5_tower_of_hanoi.py
1,716
4.34375
4
# Tower of Hanoi - specs # Three poles # Need to move tower of ascending-size disks from one pole to another # Can only put smaller disks on top of larger disks # Probably makes sense to use three stacks to represent this # Recursively solve this - base case is you have one disk # Case to decrease problem size - move tower of size - 1 class Stack(object): """Represents a stack ADT.""" def __init__(self): """Initializes the empty stack.""" self.items = [] def add(self, item): """Adds an item to the top of the stack.""" self.items.append(item) def remove(self): """Removes and returns the top item in the stack.""" if self.is_empty(): return None else: return self.items.pop() def is_empty(self): """Checks if the stack is empty.""" return self.items == [] def size(self): """Returns number of items in the stack.""" return len(self.items) def move_tower(height, from_pole, to_pole, with_pole): """Moves a tower of given height.""" if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(from_pole, to_pole): """Moves a disk from and to given poles.""" print 'Moving disk from %s to %s.' % (from_pole, to_pole) # move_tower(3, 'Start', 'End', 'Mid') def move_tower(height, from_pole, to_pole, with_pole): """Moves a tower of a given height.""" if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(from_pole, to_pole): print 'Moving disk from %s to %s.' % (from_pole, to_pole) move_tower(3, 'Start', 'End', 'Mid')
true
b5f8c3e31bcba9ac00ba62811a4a058e721f9f8e
jimjshields/pswads
/4_recursion/4_visualizing_recursion.py
725
4.25
4
import turtle def draw_spiral(my_turtle, line_len): """Recursively draws a spiral with a turtle object.""" if line_len > 0: my_turtle.forward(line_len) my_turtle.right(30) draw_spiral(my_turtle, line_len - 1) # draw_spiral(my_turtle, 100) def tree(branch_len, turtle): """Recursively draws a tree.""" if branch_len > 5: turtle.forward(branch_len) turtle.right(20) tree(branch_len - 10, turtle) turtle.left(40) tree(branch_len - 10, turtle) turtle.right(20) turtle.backward(branch_len) def main(): t = turtle.Turtle() my_win = turtle.Screen() t.left(90) t.up() t.backward(100) t.down() t.color('green') tree(75, t) my_win.exitonclick # tree(50, my_turtle) # my_win.exitonclick() main()
false
c679e5740a3e15de5800071f5603209629ca69ce
narayan-krishna/fall2019cpsc230
/Assignment6/file_complement.py
2,779
4.25
4
#Krishna Narayan #2327205 #narayan@chapman.edu #CPSC 230 section 08 #Assignment 6 import string #import so that we can test the characters of the input #Complement function def complement(sequence): alphabet_one = "ACTG " #alphabet of letters alphabet_two = "TGAC " #complement to that alphabet comp = "" #variable complement which we will return for x in sequence: #run through the given sequence index_alpha_one = alphabet_one.find(x) #find where the character is the #first alphabet comp += alphabet_two[index_alpha_one] #plugging in this index into the #second index will give the complement of return comp #return the complement def rev_complement(sequence): rev_sequence = sequence[::-1] #reverse the sequence given return complement(rev_sequence) #returns the complement of reversed #reversed sequence #returns a 0 or 1 value depending on whether the string is clean or not. def is_clean(input_string): bad_chars = string.punctuation + string.whitespace + string.digits + "BDEFHIJKLMNOPQRSUVWXYZ" word = input_string error = 0 #this will be returned at the end, 1 means error (unclean), 0 #means no error (clean) for x in bad_chars: if word.find(x) != -1: error = 1 break return error chosen_file = input("enter input file: ") #enter a file to read try: #set up excpeption system, so that if an exception is thrown, we can #print an approriate message input_file = open(chosen_file, 'r') #open the file chosen to be read out_file_complement = open("results_complement.txt", 'w') #write a new file #with the complements of the sequences out_file_reverse = open("reverse_complement.txt", 'w') #write a new file #with the reverse complements of the sequnces for sequence in input_file: #run through the lines (sequences) of the file stripped = sequence.strip() #get rid of extraneous whitespace before or #after the string if is_clean(stripped) == 0: #if the stripped sequence is clean: #print complement onto file print(complement(stripped), file = out_file_complement) #print reverse complement onto file print(rev_complement(stripped), file = out_file_reverse) else: #print that the sequence was invalid to both files print("this sequence was invalid.", file = out_file_complement) print("this sequence was invalid.", file = out_file_reverse) #close all three files that we are working with input_file.close() out_file_complement.close() out_file_reverse.close() #if we run into the FileNotFoundError error, print the approriate message except FileNotFoundError: print("the file entered does not exist")
true
490076c3dbe8fb27aae84eb5de54c1b0ce6c2a39
benie-leroy/DI-learning
/Di_execises/pythonProject/Helloword/venv/exercices_w4_day3.py
880
4.21875
4
# exercice 1 : Convert Lists Into Dictionaries ''' keys = ['Ten', 'Twenty', 'Thirty'] values = [10, 20, 30] dic = dict(zip(keys, values)) print(dic) ''' # exercice 2: Cinemax #2 family = {"rick": 43, 'beth': 13, 'morty': 5, 'summer': 8} cost = 0 for x in family: if family[x] < 3: print(x + ' ,your ticket is free') elif family[x] >= 3 and family[x] < 12: cost = cost + 10 print(x + ', your ticket is $10') elif family[x] >= 12: cost += 15 print(x+' , your ticket is $15') print(cost) names = input("please enter your family's names, separate by coma: name1,name2,... : ") age = input("please enter in order the age of those persons, also separate by comma : ") names = names.split(',') age = age.split(',') print(names) print(age) fam = dict(zip(names,age)) print(fam) # exercice 3: Zara brand = {"creation_date": 1975, }
true
f90eddf4ae56e379f8a9c31bc72d5f6fc891b049
rutujar/practice
/Fork Python/Tracks/Module 2 (Control Structures)/python-loops/3_While_loop_in_Python.py
1,276
4.25
4
#While loop in Python """ While loop in Python is same as like in CPP and Java, but, here you have to use ':' to end while statement (used to end any statement). While loop is used to iterate same as for loop, except that in while loop you can customize jump of steps in coupling with variable used to loop, after every iteration, unlike in for loop (you cannot customize jump according to the variable you are using to loop through). Let's get it more clearly through this question. Given a number x, the task is to print the numbers from x to 0 in decreasing order in a single line (use comma seperator). #Input Format: First line of input contains number of testcases T. For each testcase, there will be a single line containing the number x. #Output Format: For each testcase, print the numbers in decreasing order from x to 0. #Your Task: This is a function problem. You need to complete the printInDecreasing function and print the x from x to 0 in a single line. #Constraints: 1 <= T <= 100 1 <= x <= 106 #Example: Input: 1 3 Output: 3 2 1 0 #Explanation: Testcase 1: Numbers in decreasing order from 3 are 3, 2, 1, 0. """ #solution.py def printInDecreasing(x): while(x >= 0): print(x,end=" ") x -= 1
true
6d4de5bb8d022bfa2e55e0b0ce65ac32b12fa577
rutujar/practice
/Fork Python/Contest/Module 1/Nearest Power.py
1,560
4.34375
4
Nearest Power #You are given two numbers a and b. When a is raised to some power p, we get a number x. Now, you need to find what is the value of x that is closest to b. # Input Format: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains a and second line contains b. # Output Format: For each testcase, in a new line, print the closest power. # Your Task: This is a function problem. You do not need to take any input. Complete the function nearestPower and return the answer. # Constraints: 1 <= T <= 100 2 <= a <= 100 a <= b <= 108 # Example: Input: 1 2 4 Output: 4 # Explanation: Testcase1: 22=4 is closest to 4 # solution { #Initial Template for Python 3 //Position this line where user code will be pasted. import math def main(): testcases=int(input()) #testcases while(testcases>0): a=int(input()) b=int(input()) print(nearestPower(a,b)) testcases-=1 if __name__=='__main__': main() } ''' Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above. ''' #User function Template for python3 def nearestPower(a,b): x=math.floor(math.log(b,a)) xPlusOne=x+1 number1=a**x number2=a**xPlusOne if(abs(number1-b)>abs(number2-b)): return number2 else: return number1
true
3248fbc2ea863e003f5ffa355bb9556349fe3a86
rutujar/practice
/Fork Python/Tracks/Module 3 (strings)/python-strings/2_Slicing_in_String_Python.py
1,667
4.34375
4
#Slicing in String - Python """ Here we'll talk about the novel and perhaps tantalizing concept of slicing. Slicing is the process through which you can extract some continuous part of a string. For example: string is "python", let's use slicing in this. Slicing can be done as: a. string[0:2] = py (Slicing till index 1) b. string[0:] = python (Slicing till last index) c. string[0:4] = pyth (Slicing till index 3) d. string[0:-2] = pyth (Slicing till index -3(which is index 3)). Note: -1 indexing starts from last of any string. Now, lets look into this through a question. Given a string of braces named bound_by, and a string named tag_name. The task is to print a new string such that tag_name is in the middle of bound_by. For example, bound_by : "<<>>" and tag_name : "body", so, new string should be ""<<body>>"(without quotes) #Input Format: First line of input contains number of testcases T. For each testcase, there will be a single line containing bound_by and tag_name seperated by space. #Output Format: For each testcase, in a new line, print the new modified string as described. #User Task: The task is to complete the function join_middle() which should return the modified string. #Constraints: 1 <= T <= 100 1 <= |tag_name| <= 103 #Example: Input: 2 <> body [[]] tag Output: <body> [[tag]] #Explanation: Testcase 2: tag is in the middle of [[]], so new string formed is [[tag]]. """ #solution.py def join_middle(bound_by, tag_name): b=len(bound_by) t=int(b/2) # complete the statement below to return the string as required return bound_by[0:t] + tag_name + bound_by[t: ]
true
66566b1b7b6cb2b76c342763daac5fa4d6d0481d
rutujar/practice
/Fork Python/Tracks/Module 1 (Python Basics)/python-io/6_Taking_input_and_typecasting_Python.py
1,618
4.125
4
#Taking input and typecasting - Python """ You have learned to take string input in python. Now, you'll learn how to take input of int, float, and bool. In Python, we use the input() function and put this function in either int(), float(), or bool() to typecast the input into required data type. Also, integers, floating-points and boolean variables don't have any range in Python. As long as you have enough memory, you can work with them. In this question, you will take input of 4 variables that are in separate lines. The first variable is an integer, the second is a string(single/multiple words possible), the third is a floating number, the fourth is a boolean value. You need to take the inputs and print the outputs. #Input Format: The first line of testcase contains T denoting the number of testcases. T testcases follow. Each testcase contains 4 lines of input. #Output Format: For each testcase, in a new line, print the inputs and the class of the input. #Your Task: Your task is to complete the function inPut(). #Constraints: 1 <= T <= 100 #Example: Input: 1 56 fdg fgdf 3.43534 True Output: 56 <class 'int'> fdg fgdf <class 'str'> 3.43534 <class 'float'> True <class 'bool'> """ #solution.py def inPut(): #Take input and assign the input to a,b,c,d. Please also typecast as type() will produce wrong answer without it a= int(input("")) b= input("") c= float(input("")) d= bool(input("")) print(a, type(a)) print(b, type(b)) print(c, type(c)) print(d, type(d))
true
0e7fdcb1cfea5a0c336e849b9dbdc50089fd6ef1
rutujar/practice
/Fork Python/Tracks/Module 3 (strings)/python-strings/1_Welcome_aboard_Python.py
923
4.3125
4
#Welcome aboard - Python """ This module talks about Strings in Python. String in Python is immutable (cannot be edited). You have learnt about seperators in Python. Let's start String with first question given below: Given name of a person, the task is to welcome the person by printing the name with "Welcome". If name is "John", you should print "Welcome John". #Input Format: First line of input contains number of testcases T. For each testcase, there will be a single line containing name of the person. #Output Format: For each testcase, in a new line, print Welcome Name. #Your Task: This is a function problem. You need to complete the function welcomeAboard and print the required string. #Constraints: 1 <= T <= 100 1 <= |Name| <= 100 #Example: Input: John Python Output: Welcome John Welcome Python """ #solution.py def welcomeAboard(name): print ("Welcome " +name)
true
535bb84156e671b010d9038e29285ee4a6f739fc
Icfeeley/workspace
/Homework/csci362/team5/Commuters_TESTING/scripts/dataTypeParser.py
1,121
4.15625
4
''' parses a string containing data values in python code and determinds the data type of values in the string. ''' def main(): in1 = '[1,2]' in2 = '\'this is a string\'' in3 = '1337' in4 = '10;20' in5 = '[1,2];[2,1]' in6 = '[1,\'2\'];2;4;\'string\'' inputs = [in1,in2,in3, in4, in5, in6] for i in inputs: i = dataTypeParser(i) print i def dataTypeParser(string): #evaluates a ; delemenated multivalued input if string.find(';') != -1: string = string.split(';') i = 0 for i in range(len(string)): string[i] = dataTypeParser(string[i]) i += 1 #evaluates a list elif string.find('[') != -1: string = string.replace('[','') string = string.replace(']','') string = string.split(',') i = 0 for i in range(len(string)): string[i] = dataTypeParser(string[i]) i += 1 #evaluates a string elif string.find('\'') != -1: string = string.replace('\'', '') #evaluates a number else: try: string = int(string) except ValueError: print 'The input \'' + string + '\' does not follow proper formating and could not be resolved to a python data type' return string main()
true
5cd094c4fcfc41b45cd5c9eb755dc5dcdaea81df
picklepouch/workspace
/list_maker2.py
1,247
4.3125
4
import os groceries = [] print("Type help for assistance") def clear_screen(): os.system(cls if os.name == "nt" else clear) def list_items(): clear_screen() for items in groceries: print ("-", items) def remove_item(): list_items() what_remove = input("What would you like to remove? ") try: groceries.remove(what_remove) except ValueError: pass clear_screen() list_items() while True: new_item = input("Add item : ") if new_item.lower() == "help": print(""" To add an item to your list, simply type it in. Type 'done' when finished. To view your list type 'list'. To remove an item typer 'delete' To clear the list type 'CLEAR LIST'. """) elif new_item.lower() == "list": print("Here is your list") list_items() elif new_item.lower() == "done": break elif new_item == "CLEAR LIST": list.clear(groceries) elif new_item.lower() == "delete": remove_item() new_item = input("Add item : ") else: groceries.append(new_item) print("There are currently {} items on your list.".format(len(groceries))) list_items()
true
3da3640a98e9226f656fc55c755a562f1ca4be81
VashonHu/DataStructuresAndAlgorithms
/data_structure/LinkedList.py
1,670
4.15625
4
class ListNode(object): def __init__(self, data, next=None): self.__data = data self.__next = next @property def next(self): return self.__next @property def data(self): return self.__data @next.setter def next(self, next): self.__next = next """ the head node is the first element with value in the linked list,rather then a null node """ class LinkedList(object): def __init__(self): self.__head = ListNode(None) self.__tail = ListNode(None) @property def head(self): return self.__head @property def tail(self): return self.__tail def purge(self): self.__head = None self.__tail = None def is_empty(self): return self.__head.next is None def append(self, value): item = ListNode(value, None) if self.is_empty(): self.__head.next = item else: self.__tail.next = item self.__tail = item def traverse(self): if self.is_empty(): print("the LinkedList is empty!") else: p = self.head.next while p: print(p.data) p = p.next def remove(self, value): pointer = self.__head.next prepointer = self.__head while pointer and pointer.data != value: prepointer = pointer pointer = pointer.next if pointer is None: print("the value is in the Linked List!") return -1 prepointer.next = pointer.next if pointer is self.__tail: self.__tail = prepointer
true
60db2d5c2a5db0763170bd4fecf21fb1427b3c3c
thulc567/Padhai_Course_Materials
/FDSW3Asgn1Prob2_Solution-200215-182944.py
2,398
4.25
4
#!/usr/bin/env python # coding: utf-8 # # Assignment 1 Problem 2 # Exercise 2 # # --- # # 1. Write an iterative function to compute the factorial of a natural number # 2. Write a recursive function to compute the factorial of a natural number. # 3. Write a function to compute $\frac{x^n}{n!}$ given a float $x$ and natural number $n$ as arguments # 4. Write a function to iteratively sum up the value $\frac{x^n}{n!}$ from $n = 1$ to a given $N$ for a given $x$, i.e., # $$ F(x, N) = 1 + \sum_{i = 1}^N \dfrac{x^n}{n!}$$ # 5. Write a function to iteratively sum up the value $\frac{x^n}{n!}$ from $n = 1$ to a chosen value of $N'$ such that $$F(x, N') - F(x, N' - 1) < \epsilon$$ for given real number $x$ and positive small number $\epsilon$ # 6. Choose two real numbers $p$ and $q$ and compute the following two values # $$ v_1 = F(p, 100) * F(q, 100) $$ # $$ v_2 = F(p + q, 100) $$ # Compute the difference $v_1 - v_2$ and comment on what you see. # # Solution to Problem 2 # In[ ]: def factorial(n): product = 1 for i in range(n): # print(i, product) product *= (i + 1) return product # In[2]: print(factorial(3)) # In[ ]: def factorial_recursive(n): if n > 1: return n * factorial_recursive(n - 1) else: return 1 # In[4]: print(factorial_recursive(3)) # In[ ]: def compute_ratio(x, n): ratio = x**n / factorial(n) return ratio # In[6]: compute_ratio(2, 3) # In[ ]: def compute_sum(x, N): sum = 1 for i in range(N): sum += compute_ratio(x, i + 1) return sum # In[8]: print(compute_sum(2, 3)) # In[ ]: def compute_sum_epsilon(x, epsilon): sum = 1 var = epsilon i = 1 while var >= epsilon: var = compute_ratio(x, i) sum += var i += 1 return sum # In[10]: print(compute_sum_epsilon(2, 0.01)) # In[11]: print(compute_sum(2, 100)) # In[ ]: def compute_sum_epsilon(x, epsilon): sum = 1 i = 1 while True: var = compute_ratio(x, i) sum += var i += 1 if var < epsilon: break return sum # In[13]: print(compute_sum_epsilon(2, 0.01)) # In[14]: p = -1.5 q = 7.1 v1 = compute_sum(p, 100) * compute_sum(q, 100) v2 = compute_sum(p + q, 100) print(v1, v2, v2 - v1) # In[15]: for i in range(10): print(i, compute_sum(i, 100)) # In[ ]:
true
f84b2a6845e047ad54f1b548315373365db45f41
breezekiller789/LeetCode
/101_Symmetric_Tree.py
1,482
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/symmetric-tree/ # 如果是對稱的,代表我把他左右子樹其中一個人swap之後,兩個子樹會長一樣,因為對稱 # ,所以很簡單,我就先swap左子樹,然後比看看左右子樹一不一樣,這樣就好了。 class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_Same_Tree(p, q): # Base Condition,當兩個樹都是空的,回傳true if not p and not q: return True elif p and q: # 該節點都一樣,要繼續比 if p.val == q.val: # 若左子樹一樣,就比右子樹,直接用return的,很漂亮 if is_Same_Tree(p.left, q.left): return is_Same_Tree(p.right, q.right) # 節點值不一樣直接回傳False else: return False # 會走到這裡代表p, q就直接不一樣了 return False def swap(root): if not root: return else: swap(root.left) swap(root.right) tmp = root.left root.left = root.right root.right = tmp # 測資 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(3) root.right.left = TreeNode(4) root.right.right = TreeNode(3) swap(root.left) print is_Same_Tree(root.left, root.right)
false
15f0034b53c0619cd7c527d0433294ec17b93c1b
weiyima/python-examples
/chap11_regex/regex.py
1,379
4.21875
4
# Regular Expressions """ Python Regular Expression Quick Guide ^ Matches the beginning of a line $ Matches the end of the line . Matches any character \s Matches whitespace \S Matches any non-whitespace character * Repeats a character zero or more times *? Repeats a character zero or more times (non-greedy) + Repeats a character one or more times +? Repeats a character one or more times (non-greedy) [aeiou] Matches a single character in the listed set [^XYZ] Matches a single character not in the listed set [a-z0-9] The set of characters can include a range ( Indicates where string extraction is to start ) Indicates where string extraction is to end Examples: [0-9] one digit [0-9]+ one more more digit (because of + sign) '\S+@\S+' = regex for email ^From (\S+@\S+) = extract email pattern only if regex matches ^From re.search('[0-9]+') # returns True / False depending on whether the string matches the regex re.findall('[0-9]+') # returned the matching string to be extracted """ # import re fname = 'regex_sum_6035' xfile = open(fname) lst = list() sumtotal = 0 count = 0 for line in xfile: line = line.rstrip() lst = re.findall('[0-9]+',line) for l in lst: sumtotal = sumtotal + int(l) count = count + 1 print('Final',sumtotal) print('Count',count)
true
ab1f9e2562f47f50d5cf2120195f49964484bd5e
weiyima/python-examples
/chap06_datatypes/list.py
1,182
4.1875
4
#Chapter 8 - List friends = ['Joseph',0.99,'Hello','World'] friends[1] = 'Sally' #list are mutable, list are not #print(friends) #range(int) used to create range/list of size int (e.g. range(4) will be [0,1,2,3]) for i in range(len(friends)): friend = friends[i] print(friend) #list functions friends[3:] #slicing - from 3 not including stuff = [] #create empty list stuff.append('Book') stuff.append('Umbrella') #unlike string, list are mutable stuff.append('Apple') 'Book' in stuff #search and compare. returns True/False stuff.sort() #['Apple', 'Book', 'Umbrella'] #Simple list Data Structures numlist = [] while True: inp = input('Enter a number: ') if inp == 'done' : print('Done!') break try : fval = float(inp) numlist.append(fval) except : print('Not a valid number') print('Total sum is:',sum(numlist)) print('Average is',sum(numlist)/len(numlist)) # Strings and List working together, using split whitespace = 'The big brown fox jumps over the log' listws = whitespace.split() print(list1) csv = 'The,big,brown,fox,jumps,over,the,log' listcsv = csv.split(',') print(listcsv) # Chapter 8 - Homework
true
4b40e8821fe98898611ff181eeefa845412ae036
aprebyl1/DSC510Spring2020
/BUNCH_JONATHAN_DSC510/BUNCH_11_1.py
2,817
4.125
4
# File: BUNCH_11_1.py # Name: Jonathan Bunch # Date: 24 May, 2020 # Course: DSC510-T303 Introduction to Programming (2205-1) # Your program must have a welcome message for the user. # Your program must have one class called CashRegister. # Your program will have an instance method called addItem which takes one parameter for price. The method should # also keep track of the number of items in your cart. # Your program should have two getter methods. # getTotal – returns totalPrice # getCount – returns the itemCount of the cart # Your program must create an instance of the CashRegister class. # Your program should have a loop which allows the user to continue to add items to the cart until they request to quit. # Your program should print the total number of items in the cart. # Your program should print the total $ amount of the cart. # The output should be formatted as currency. Be sure to investigate the locale class. You will need to call # locale.setlocale and locale.currency. import locale locale.setlocale(locale.LC_ALL, "") class CashRegister: """This class has the following attributes: a list of prices, the number of prices on that list, and the sum of all the prices on that list.""" def __init__(self): self.items = [] self.count = int(0) self.total = float(0) def add_item(self, item_price): self.items.append(item_price) self.count = len(self.items) self.total = sum(self.items) print(locale.currency(item_price), 'added to list.') def get_total(self): return self.total def get_count(self): return self.count # This function collects entries from the user and gives the user the option to finish by # entering any alphabetic character(s). def get_price(cr_object): run_loop = True while run_loop: price = input('Enter the price of an item or any letter to finish: ') if price.isalpha(): print('Entry Complete!') run_loop = False else: try: price = float(price) except ValueError: print('Error: entries must be in standard numerical format.') else: if price < 0: print('Error: entries must be positive numbers.') else: price = round(price, 2) cr_object.add_item(price) def main(): print('Welcome to our cash register program!') cost = CashRegister() get_price(cost) print('Total number of items on list: ', cost.get_count()) print('Total cost of items on list: ', locale.currency(cost.get_total())) print('Thanks for using our cash register program!') main()
true
ef09a653928272cd0062a73514bbf6623f47d75f
aprebyl1/DSC510Spring2020
/Kuppuswami_DSC510/Fiber_Cable_Quotation.py
1,522
4.15625
4
# Program Name: Quotation for Fiber Cable Installation #Calculate the installation cost of fiber optic cable by multiplying the total cost as the number of feet times $0.87. # Print a receipt for the user including the company name, number of feet of fiber to be installed, the calculated cost, and total cost in a legible format. # Author: Rajkumar Kupuswamii # Date:Wednesday, March 21, 2020 # Display a welcome message for your user. # Retrieve the company name from the user. # Retrieve the number of feet of fiber optic cable to be installed from the user. import datetime as dt #Set variable space= " " Symbol1 = "#" amt = 0.87 #Get the input Quotation_date = dt.date.today().strftime("%d/%m/%y") print("Welcome to fiber optics installation company") get_input = input("Please enter your company name :") company_name = get_input get_input = input("Please enter the feet for fiber optics installation :") #get input qty qty = round(float(get_input), 2) #Calculate the qty * Cost total_cost_of_installation = round(qty * amt, 2) #Print the output print (Symbol1*80 + '\n' + Symbol1 + space*20 + "Quotation for fiber Optics Installation" + space*10 + Symbol1 + '\n'+ Quotation_date + '\n'+ company_name + '\n' + Symbol1*80 + '\n' + 'Number of Feet tobe Installed: ' + str(qty) + ' qty\n' + ' Fiber Installation cost: $' + str(total_cost_of_installation) + '\n' + Symbol1 * 80 + '\n' + ' Total cost of Installation: $' + str(total_cost_of_installation) + '\n' + Symbol1 * 80)
true
3120783f04c073be7f1eb0ab6c1bb5ef3f6593c9
aprebyl1/DSC510Spring2020
/BUNCH_JONATHAN_DSC510/BUNCH_4_1.py
2,886
4.375
4
# File: BUNCH_4_1.py # Name: Jonathan Bunch # Date: 5 April, 2020 # Course: DSC510-T303 Introduction to Programming (2205-1) # This week we will modify our If Statement program to add a function to do the heavy lifting. # Modify your IF Statement program to add a function. This function will perform the cost calculation. # The function will have two parameters (feet and price). When you call the function, you will pass two arguments # to the function; feet of fiber to be installed and the cost (remember that price is dependent on the number of # feet being installed). You probably should have the following: # A welcome message # A function with two parameters # A call to the function # The application should calculate the cost based upon the number of feet being ordered # A printed message displaying the company name and the total calculated cost # This function takes the argument feet that we collect from the user and returns the price based on the bulk discount. def price_tier(length): if length > 500: price = 0.50 elif length > 250: price = 0.70 elif length > 100: price = 0.80 else: price = 0.87 return price # This function takes our two arguments, feet of cable and price per foot, and returns the total cost. def calculate_cost(feet, price): cost = feet * price return cost # Print a welcome message for the user. print('Welcome to our digital quoting system!') # Prompt the user to enter a company name, and assign the name to a new variable. company_name = input('Please enter your company name:') # Prompt the user to enter feet of cable requested, and assign that value to another variable. feet_cable = input('How many feet of fiber optic cable will you be installing?:') # Python will return the input value as an "int" type, so we must convert it to a "float" type for compatibility with # the "price_per_foot" variable. Note: the program will crash here if the user enters any non-numbers. feet_cable = float(feet_cable) # Now that we have the length, we can call our "price_tier" function to determine the price per foot. price_per_foot = price_tier(feet_cable) # Now that we have determined length and price we can call "calculate_cost" and pass those values in as arguments. total_cost = calculate_cost(feet_cable, price_per_foot) # Print a receipt for the user based on the values of our variables, and format output to standard monetary format. print('') print('Thank you for using our digital quoting system. Please see your quote below.') print('Company:', company_name) print(f'Feet of cable requested: {round(feet_cable, 2):.2f}') print(f'Price per foot: ${price_per_foot:.2f}') print(f'Total Cost: ${round(total_cost, 2):.2f}') print('Thank you for considering us for your cable installation needs!')
true
aa5509e97d88e5a453029dba3f95513988e34938
aprebyl1/DSC510Spring2020
/SURYAWANSHI_DSC510/week3/assignment3_1.py
2,504
4.53125
5
# File: billingInvoice_assignment2_1.py # Author: Bhushan Suryawanshi # Date:Wednesday, March 25, 2020 # Course: DSC510-T303 Introduction to Programming (2205-1) # Desc: The program will do followings: # Display a welcome message for your user. # Retrieve the company name from the user. # Retrieve the number of feet of fiber optic cable to be installed from the user. # Using the default value of $0.87 calculate the total expense. # If the user purchases more than 100 feet they are charged $0.80 per foot. # If the user purchases more than 250 feet they will be charged $0.70 per foot. # If they purchase more than 500 feet, they will be charged $0.50 per foot. # Print a receipt for the user including the company name, number of feet of fiber to be installed, the calculated cost, and total cost in a legible format. import datetime as date #Setup basic data items line = '#' space = ' ' dash = '-' other_cost = 0.0 per_feet_default_price = 0.87 more_than_100_feet_price = 0.80 more_than_250_feet_price = 0.70 more_than_500_feet_price = 0.50 #Get input from user today = date.date.today().strftime("%m/%d/%y") print("Welcome to Fiber Installation Cost calculator.") input_value = input("Please Enter your Company Name:->") company_name = input_value input_value = input("Enter the Fiber to be Installed (in feet):->") #Convert input string to float and round the value to 2 decimal. feet = round(float(input_value), 2) #Calculate the cost of installing fiber and round to 2 decimal. if (feet > 500): cost_of_installation = round(feet * more_than_500_feet_price, 2) elif (feet > 250): cost_of_installation = round(feet * more_than_250_feet_price, 2) elif (feet > 100): cost_of_installation = round(feet * more_than_100_feet_price, 2) else: cost_of_installation = round(feet * per_feet_default_price, 2) #Calculate total cost and round to 2 decimal. total_cost = round(cost_of_installation + other_cost,2) #Print receipt showing details. print(line * 51 +'\n' + line + space*19 + 'Billing Invoice'+ space*15 + line+'\n' + line *51 + '\n' + line + 'Company Name: ' + company_name +' \n' + line + 'Date:'+today +'\n' + dash*51 + '\n' + 'Number of Feet tobe Installed: ' + str(feet) + ' feet\n' + ' Fiber Installation cost: $' + str(cost_of_installation) + '\n' + ' Other cost: $' + str(other_cost) +'\n' + dash*51 + '\n' + ' Total cost of Installation: $' + str(cost_of_installation) + '\n' + dash*51)
true
a05756270eef5a4351ac08944d06b1de123199b5
aprebyl1/DSC510Spring2020
/TRAN_DSC510/UserFiberOptics.py
866
4.3125
4
#The purpose of this program is to retrieve company name and number of feet of fiber optic cable to be installed from user, Assignment number 2.1, Hanh Tran username= input('What is your username?\n') print('Welcome' + username) company_name=input('What is your company name?\n') quantity= input('How many feet of fiber optic cable do you want installed?\n') #quantity of fiber optic cable in feet price= 0.87 total_cost= float(quantity)*price #Calculate installation cost of cable #Receipt for user print('Receipt\n') print(username) print(company_name) print('-------------------------------------------------\n') print('ITEM\t\t\t\t\tFiber Optic Cable') print('QUANTITY IN FEET\t\t\t'+str(quantity)) print('PRICE PER FEET\t\t\t\t'+str(price)) print('-------------------------------------------------\n') print('Total Cost\t\t\t\t\t'+str(total_cost))
true
af7bb7bb3009a4c6a707db238f389f8f81fb4c18
aprebyl1/DSC510Spring2020
/TRAN_DSC510/Week_6.1_Temperatures.py
1,256
4.5
4
# File: Assignment_6.1 # Name: Hanh Tran # Due Date: 4/19/2020 # Course: DSC510-T303 Introduction to Programming (2205-1) # Desc: This program will do the following: # create a list of temperatures based on user input # determine the number of temperatures # determine the largest temperature and the smallest temperature # created an empty list called temperatures temperatures = [] count = 0 while True: input_temp = input('Please enter a fahrenheit temperature number or done to stop: ') # sentinel value, 'done', stops the user input if input_temp == 'done': break try: temp = float(input_temp) except ValueError: print('Invalid input') quit() count = count + 1 temperatures.append(round(float(input_temp), 2)) # populated list of temperatures based on user input print('Your entered list of temperatures in fahrenheit: ', temperatures) # evaluate and print largest and smallest temperatures print('Your highest temperature in fahrenheit is: {} F'.format(max(temperatures))) print('Your lowest temperature in fahrenheit is: {} F'.format(min(temperatures))) # print message that tells user how many temperatures are in the list print('The number of temperatures in your list: ' + str(count))
true
74d09b7aee7f0536acc60e687d64eff287d23e63
santoshmano/pybricks
/recursion/codingbat/powerN.py
372
4.15625
4
""" Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power, so powerN(3, 2) is 9 (3 squared). powerN(3, 1) → 3 powerN(3, 2) → 9 powerN(3, 3) → 27 """ def powerN(base, n): if n == 0: return 1 else: return base*powerN(base, n-1) print(powerN(3, 2)) print(powerN(2, 10)) print(powerN(10, 0))
true
a3a72378f879fa833ed20aad25a1d97ff0280f47
santoshmano/pybricks
/lists/mergesort_linkedlist.py
1,892
4.21875
4
""" Merge sort a linked list O(nlog(n)) time complexity. O(1) space. """ class Node: def __init__(self, val, next=None): self.val = val self.next = next def list_to_str(head): temp = head list = [] while temp: list.append(temp.val) temp = temp.next return ",".join(map(str, list)) def list_length(head): temp = head len = 0 while temp: len += 1 temp = temp.next return len def _merge_lists(h1, h2): head = temp_head = Node(0) while h1 and h2: if h1.val < h2.val: head.next = h1 h1 = h1.next else: head.next = h2 h2 = h2.next head = head.next if h1: head.next = h1 elif h2: head.next = h2 head = temp_head.next del temp_head return head """ examples: List len mid h1 h2 3 1 2 1 3 1 3 5 1 3 4 2 3 1 8 1 4 1 9 5 2 """ def _mergesort_list(head, len): if len == 0 or len == 1: return head mid = len // 2 left = right = head # get the middle list pointer/reference prev = None for i in range(mid): prev = right right = right.next #split it into two lists if prev: prev.next = None h1 = _mergesort_list(left, mid) h2 = _mergesort_list(right, len - mid) head = _merge_lists(h1, h2) return head def mergesort_list(head): """ :param head: list to be sorted :return: head of the sorted list """ len = list_length(head) return _mergesort_list(head, len) head = Node(5) head.next = Node(1) head.next.next = Node(2) head.next.next.next.next = Node(4) head.next.next.next.next.next = Node(5) print("Original list:", list_to_str(head)) head = mergesort_list(head) print("Sorted list:", list_to_str(head))
false
870acfbf8698fae99d81cd7769b54b15adb5fd6c
santoshmano/pybricks
/sorting/mergesort_1.py
983
4.1875
4
def mergesort(nums): aux = [None for x in nums] print("before mergesort - ", nums) _mergesort(nums, aux, 0, len(nums)-1) print("after mergesort -- ", nums) def _mergesort(nums, aux, start, end): if start >= end: return mid = start + (end - start) // 2 print(start, mid, end) _mergesort(nums, aux, start, mid) _mergesort(nums, aux, mid + 1, end) left = start right = mid + 1 auxi = start print(left, right, auxi) while left <= mid and right <= end: if nums[left] <= nums[right]: aux[auxi] = nums[left] left += 1 else: aux[auxi] = nums[right] right += 1 auxi += 1 while left <= mid: aux[auxi] = nums[left] left += 1 auxi += 1 while right <= mid: aux[auxi] = nums[right] right += 1 auxi += 1 for i in range(start, end + 1): nums[i] = aux[i] mergesort([34, 2, 1, 23, 12])
false
a34e540e2ebe1b343c2d59cf9d5ec1d25c6afc10
Ernestterer/python_work
/lists/places_to_visit.py
625
4.375
4
places = ['jerusalem', 'london', 'newyork', 'singapore', 'dubai'] print(f"The cities I would like to visit are:\n\t\t\t\t\t{places}") print(f"The cities I would like to visit alphabetically:\n\t\t\t\t\t{sorted(places)}") print(f"Here is the original order of the list:\n\t\t\t\t\t{places}") print(f"The cities I would like to visit sorted in reverse:\n\t\t\t\t\t{sorted(places, reverse=True)}") print(f"Here is the original order of the list:\n\t\t\t\t\t{places}") places.reverse() print(places) places.reverse() print(places) places.sort() print(f"Here is list of places to visit sorted permanentyly:{places}") print(places)
true
6e5bed5488ddda287c784d67090d1d6f785e2c21
mohammad-javed/python-pcap-course
/020-055-lab-list-methods/cipher_decrypt_answer.py
545
4.4375
4
cipher = input('Enter your encrypted message: ') def decrypt(cipher): result = "" # Iterate through the cipher for char in cipher: # Check whether character is alphanumeric if char.isalpha(): if char == 'A': result += 'Z' elif char == 'a': result += 'z' else: result += chr(ord(char) - 1) else: result += char return result print("Cipher was :", cipher) print("Decrypted message is :", decrypt(cipher))
true
0cec6daa3794d985d252d772832795642a7ba42a
mohammad-javed/python-pcap-course
/010-025-lab-math-module/is_triangle_answer.py
374
4.1875
4
import math def is_triangle(a, b, c): if math.hypot(a, b) == c: return True return False print("The program checks if three sides form a right-angled triangle.") inp1 = int(input("Enter first side value: ")) inp2 = int(input("Enter second side value: ")) inp3 = int(input("Enter third side value: ")) print("Is triangle?", is_triangle(inp1, inp2, inp3))
true
afbdc179d558b94dd187d540ba8c7ea27804da51
jacekku/PP3
/Python/04/zadanie08.py
744
4.15625
4
#the exercise wants me to create a transposition for square maticies but the next one wants me to #create one for any size matrix so im going to do it here from random import randint def create_matrix(y_size,x_size,key=0,key_args=[]): return[ [ (key(*key_args) if callable(key) else key) for _ in range(x_size) ] for _ in range(y_size) ] def transpose_matrix(matrix): y_size=len(matrix) x_size=len(matrix[0]) temp=create_matrix(x_size,y_size) for i in range(y_size): for j in range(x_size): temp[j][i]=matrix[i][j] return temp matrix=create_matrix(3,5,key=randint,key_args=[0,9]) print(*matrix,sep="\n",end="\n\n") print(*transpose_matrix(matrix),sep="\n")
true
58cba3dfbd0f53307a2927d7ad3c93c93b352658
Alexkalbitz/leetcode
/14.py
1,712
4.21875
4
# Write a function to find the longest common prefix string amongst an array of strings. # # If there is no common prefix, return an empty string "". # # Example 1: # # Input: ["flower","flow","flight"] # Output: "fl" # # Example 2: # # Input: ["dog","racecar","car"] # Output: "" # Explanation: There is no common prefix among the input strings. # # Note: # # All given inputs are in lowercase letters a-z. class Solution: def longestCommonPrefix(self, strs): # check for empty list as input smallest_prefix = [] if strs == smallest_prefix: return '' # sort for the shortest word in the list since the smallest prefix can be the shortest word at max strs.sort(key=len) for letter in strs[0]: smallest_prefix.append(letter) # probably should not pop an item from the list but instead just ignore it strs.pop(0) target_index = 0 for word in strs: for char in range(len(smallest_prefix)): # check if the letters match the prefix if len(smallest_prefix) == 0: return '' if word[char] == smallest_prefix[char]: target_index = char # if not cut the prefix else: if char is not 0: smallest_prefix = smallest_prefix[: target_index + 1] break else: return '' # return whatever is left of the initial prefix as string return ''.join(smallest_prefix) test = ["dogde","dorito","dog"] s = Solution() result = s.longestCommonPrefix(test) print(result)
true
72737daa1013835d1c191efb2a02c74ab6a5441a
Duelist256/python_basics
/python_basics/strings.py
562
4.25
4
x = "Hello" print(x) a = str("world") print(a) print() print(x[-1]) print(x[0]) print(x[4]) print() print(x[1:3]) print(x[1:]) print(x[:3]) print(x[:10]) print() x = "I'm %d y.o" % 171 print(x) print(str(1)) print(len("12345")) print(sum([1, 2, 3])) print() # Exercise 1. Make a program that displays your favourite actor/actress. print("Christian Bale") # Exercise 2. Try to print the word ‘lucky’ inside s. s = print("lucky") print(s) # Exercise 3. Try to print the day, month, year in the form “Today is 2/2/2016”. print("Today is %d/%d/%d" % (4, 4, 2019))
true
c0849e4301054fd5484bb3dfd02ab40b7092901a
TesztLokhajtasosmokus/velox-syllabus
/week-05/1-tdd/grouptest/works/aliz_work.py
1,272
4.28125
4
# Write a function, that takes two strings and returns a boolean value based on if the two strings are Anagramms or not. def anagramm(string1, string2): if type(string1) == int: return False if string1 == '' or string2 == '': return False if len(string1) != len(string2): return False char_list1 = [] for char1 in string1: char_list1 += char1.lower() char_list2 = [] for char2 in string2: char_list2 += char2.lower() if sorted(char_list1) != sorted(char_list2): return False return True # print(anagramm('alma', 'lamm')) # print(anagramm('', '')) # print(anagramm('123', '321')) # print(anagramm(123, 321)) # Write a function, that takes a string as an argument and returns a dictionary with all letters in the string as keys, and numbers as values that shows how many occurrences there are. def count_letters(string): string = str(string) string = str(string.lower()) letters_in_string = {} for letter in string: letters_in_string[letter] = string.count(letter) return letters_in_string # print(count_letters('alma')) # print(count_letters('')) # print(count_letters('Alma')) # print(count_letters(123))
true
55438a72dad375d8a4d97997f34fc57fddc31837
TesztLokhajtasosmokus/velox-syllabus
/week-05/1-tdd/grouptest/works/ddl_work.py
1,101
4.28125
4
# Write a function, that takes two strings and returns a boolean value based on if the two strings are Anagramms or not. # def anagramm(str1, str2): a = sorted(str1) b = sorted(str2) if str1 or str2 != '': pass else: return('Please type in valid strings') try: if int(str1) or int(str2) == True: return 'Please type in words.' else: pass except: return(a == b) # Write a function, that takes a string as an argument and returns a dictionary with all letters in the string as keys, and numbers as values that shows how many occurrences there are. def count_letters(str3): try: if int(str3) != False: return 'Please type in words.' else: pass except: pass try: if str3 != '': pass else: return('Please type in valid strings') except: pass dicto = {} for letter in str3: dicto[letter] = str3.count(letter) return dicto # print(count_letters('haagolemrolhianyzottazapadlaza'))
true
415d129291f2531a5f5867fedc30c45f47776210
TesztLokhajtasosmokus/velox-syllabus
/week-03/2-functions-data-structures/solutions/37.py
303
4.125
4
numbers = [3, 4, 5, 6, 7] # write a function that filters the odd numbers # from a list and returns a new list consisting # only the evens def filter_odds(input): evens = [] for item in input: if item % 2 == 0: evens += [item] return evens print(filter_odds(numbers))
true
9ed0b7f1ac77d9271995eb562d9b19dc4e37e80c
anuabey/Event_Management
/eventlist.py
647
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 20:38:11 2018 This program uses the pandas dataframe to read from a CSV file containing event and participant details, sort the values event-wise & writes the data to multiple CSV files based on the event @author: Anu Mary Abey """ import pandas as pd def main(): """Reads the CSV file, recategorizes the data & writes to different CSV files based on each event """ individual = pd.read_csv("individual_1.csv") event = individual.Event.unique() [individual[individual['Event'] == i ].to_csv(i+".csv") for i in event] if __name__ == "__main__": main()
true
751ebf359318f8e81e0ae5c6a327ed990413f55a
notdiego1/Palindrone
/palindrone.py
512
4.125
4
def palindrone(phrase): x = -1 y = 0 noSpaces = [] makeList = list(phrase) for i in makeList: if i == " ": del i else: noSpaces.append(i) for i in noSpaces: if i != noSpaces[x]: y = 1 break x = x - 1 if y == 1: print("Not a palindrone!:(") else: print("It is a palindrone!:D") print("This algorithm checks for palindrones.") phrase = input("Please enter input: ") palindrone(phrase)
true
5f390487c7a24b856147147609ea0f76e1c4fe18
justingabrielreid/Python2019AndON
/DogClass.py
964
4.25
4
#!/usr/bin/env python3 #Author: Justin Reid #Purpose: Practice classes and object oriented programming def main(): class Dog: species = 'mammal' #instance attributes #these can be different for each instance def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender #example of an instance method. def description(self): return "This dog's name is {}. His/her age is {} years old.".format(self.name, self.age) def speak(self, sound): print ("{} says {}.".format(self.name, sound)) maxi = Dog("Max", 3, "Male") bigd = Dog("Delilah", 4, "Female") roxy = Dog("Roxy", 9, "Female") def getOldestDog(*args): return max(args) print("The oldest dog is {} years old.".format(getOldestDog(maxi.age, bigd.age, roxy.age))) print(maxi.description()) maxi.speak("Hello Mate!") main()
true
14db57cfe33091676a940a4b193645d79c3bf9a8
FengQiS/python
/sort-algorithms.py
1,041
4.1875
4
'''冒泡排序''' def bubble_sort(number): for i in range(len(number)): for j in range(len(number)-1,i,-1): if(number[j] < number[j-1]): number[j],number[j-1] = number[j-1],number[j]; return number; '''选择排序''' def select_sort(number): for i in range(len(number)): for j in range(i+1,len(number)): if (number[i] > number[j]): number[i],number[j] = number[j],number[i]; return number; '''插入排序''' def insert_sort(number): for i in range(1,len(number)): for j in range(0,i): if (number[i] < number[j]): temp = number[i]; for t in range(i,j,-1): number[t] = number[t-1]; number[j] = temp; break; return number; number1 = [42,13,2,67,34,21,45,15,8,18,0]; print(bubble_sort(number1)); number2 = [42,13,2,67,34,21,45,15,8,18,0]; print(select_sort(number2)); number3 = [42,13,2,67,34,21,45,15,8,18,0]; print(insert_sort(number3));
false
a5ecd5b8f9188bf41e66ffd14b935886dbae57c5
PierceAndy/rpc-taxi-booking-sim
/booking/trip.py
1,246
4.21875
4
from .point import Point, manhattan_dist class Trip: """Contains the starting and ending locations of a trip. Attributes: src: A Point instance of the starting location of a trip. dst: A Point instance of the ending location of a trip. """ def __init__(self, booking): """Initializes Trip with starting and ending locations. Args: booking: A dict mapping starting (source) and ending (destination) locations to x and y coordinates. For example: {'source': {'x': 0, 'y': 0}, 'destination': {'x': 1, 'y': 1}} """ self.src = Point(booking['source']['x'], booking['source']['y']) self.dst = Point(booking['destination']['x'], booking['destination']['y']) def travel_duration(self): """Returns the amount of time needed to complete the trip. Distance is calculated using the Manhattan distance of the starting and ending locations, and it takes 1 time unit to traverse 1 Manhattan distance unit. Returns: An integer of time units needed to complete the trip. """ return manhattan_dist(self.src, self.dst)
true
feafb858caa38a45d5ed7070eb063ed3c1f36c48
quento/660-Automated
/odd-or-even.py
663
4.28125
4
def number_checker(num, check): "Function checks if a number is a multiple of 4 and is odd or even. " if num % 4 == 0: print(num, "Is a multiple of 4") elif num % 2 == 0: print(num, "Is an even number") else: print(num,"You picked an odd number.") if num % check == 0: print(num, "divide evenly by", check) else: print(num, "does not divide evenly by", check) def main(): # Get numeric input from user. num = int(input("Give me a number to check: ")) check = int(input("give me a number to divide by: ")) # Call function to check number. number_checker() if __name__ == '__main__': main()
true
80424cf18c0f9d67b8479d8e0c265a658ca143b4
Skinshifting/lpthw
/ex6.py
808
4.21875
4
# variable x assigned to a string %d means decimal value x = "There are %d types of people." % 10 # variable assigned to strings binary = "binary" do_not = "don't" # variable assigned to string with %s variables as strings y = "Those who know %s and those who %s." % (binary, do_not) # code begins - print the values print x print y # print the strings with the values print "I said: %r." % x print "I also said: '%s'." % y #boolean set to false hilarious = False # %r stands for repr string containing a printable representation of an object joke_evaluation = "Isn't that joke so funny?! %r" #calls for the boolean print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." #prints without a space between print w + e #print with a space between print w, e
true
627671aece9a7b8c6969dacbf36b9589bf16e5d4
Ashton-Sidhu/Daily-Coding-Problems
/Solutions/Problem 3.py
2,202
4.28125
4
#QUESTION # Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, # and deserialize(s), which deserializes the string back into the tree. # For example, given the following Node class # class Node: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # The following test should pass: # node = Node('root', Node('left', Node('left.left')), Node('right')) # assert deserialize(serialize(node)).left.left.val == 'left.left' #SOLUTION #Serialize: Iterate recursively through the tree, if a node is empty return a string # to determine the nodes with 0/1 edge, #otherwise return node.val + ',' #Time complexity: O(n) -> traverse each node only once. #Deserialize: For each serialized node (separated by ,) rebuild the tree starting from the left. #When it reaches a # it knows the node has no more children on the left and then repeat on the right. #Time complexity: O(n) -> Traverse serial list only once. #Space complexity for the entire algorithm is O(n) as building the tree takes up n space as well the serialization string. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def main(): node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' node = Node('root') assert deserialize(serialize(node)).left is None assert deserialize(serialize(node)).val == 'root' def serialize(node): serial = "" if node == None: serial += '#,' return serial serial += node.val + ',' serial += serialize(node.left) serial += serialize(node.right) return serial def deserialize(s): s = s[:-1] s = s.split(',') return DeserializeHelper(s) def DeserializeHelper(s): if not s: return None node = None rootval = s.pop(0) if rootval != '#': node = Node(rootval) node.left = DeserializeHelper(s) node.right = DeserializeHelper(s) return node if __name__ == '__main__': main()
true
e5b6371ed9f4f8077a55aba8b0556b695308aa24
Ashton-Sidhu/Daily-Coding-Problems
/Solutions/Problem 5.py
617
4.125
4
#QUESTION #cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. #Given this implementation of cons: #def cons(a, b): # def pair(f): # return f(a, b) # return pair def cons(a, b): def pair(f): return f(a, b) return pair def car(f): def first(a,b): return a return f(first) def cdr(f): def last(a,b): return b return f(last) def main(): print(car(cons(3, 4))) print(cdr(cons(3, 4))) if __name__ == '__main__': main()
true
47b9d78eaeb94d0bdef33466c1f86642e8eb4551
ssamanthamichelle/Sam-Codes-Python
/python08-code.py
741
4.34375
4
""" hey guys, it's me SAM~ here is the code for the two programs in my youtube video python 08 feel free to download & run this! ;) """ # first program # only works for 1 string- my_string = '123 GO!' # ... if you want to use a different string, have to modify function... # not ideal :/ #################################### def print_chars1(): my_string = '123 GO!' for char in my_string: print(char) #calling first function print_chars1() # second program # more useful because my_string isn't hard-coded # can call function with different arguments #################################### def print_chars(my_string): for char in my_string: print(char) #calling second function print_chars("this is my string!")
true