blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d84f54932db5b2e1da02567f9eccf3db50b2b72b
puhaoran12/python_note
/61.字符串的查询操作.py
746
4.53125
5
#字符串是不可变序列 # 查询方法: s='hello,hello' # 1.index() 查找字符串substr第一次出现的位置,如果查找的子串不存在时,则抛出ValueError print(s.index('lo')) #print(s.index('k'))#ValueError: substring not found # 2.rindex() 查找字符串substr最后一次出现的位置,如果查找的子串不存在时,则抛出ValueError print(s.rindex('lo')) #print(s.rindex('k'))#ValueError: substring not found # 3.find() 查找字符串substr第一次出现的位置,如果查找的子串不存在时,则返回-1 print(s.find('lo')) print(s.find('k')) # 4.rfind() 查找字符串substr最后一次出现的位置,如果查找的子串不存在时,则返回-1 print(s.rfind('lo')) print(s.rfind('k'))
false
b565872eea2c84d9c7ebf162f5c2c8cb470d3e6d
puhaoran12/python_note
/65.字符串判断的相关方法.py
642
4.40625
4
# 判断字符串操作 s='hello,python' # 1.isidentifier() 判断指定的字符串是不是合法的标识符 print('1',s.isidentifier()) # 2.isspace() 判断指定的字符串是否全部由空白字符组成(回车,换行,水平制表符) print('2',s.isspace()) # 3.isalpha() 判断指定的字符串是否全部由字母组成 print('3','sfef'.isalpha()) # 4.判断指定的字符串是否全部由十进制的数字组成 print('4','13235'.isdecimal()) # 5.判断指定的字符串是否全部由数字组成 print('5','34'.isnumeric()) # 6.判断指定字符串是否全部由字母和数字组成 print('6','s43fef'.isalnum())
false
43a5434f3ebce881b0baf474822522f08af9e18b
leomessiah10/Operations
/fibonacci_series.py
657
4.125
4
print('In this program we will play with fibonacci sequence') first_num = 1 sec_num = 1 fibo_list = [1,1] count = 0 while(count == 0): num = eval(input('Upto which number you want the sequence\n:-')) for i in range(num-2): temp = sec_num + first_num first_num = sec_num sec_num = temp fibo_list.append(temp) print(fibo_list,'\n') res_num = eval(input('Which number you want to see from the sequence\n:-')) print(fibo_list[res_num]) choice = input("Wanna try once again,[y/n]") if choice == 'n' or choice == 'N': print('Hope you have enjoyed!!') break else: pass
true
a88857c51d81f2bd872b60c9c42d6219b701e936
gvillena76/Tic-Tac-Toe-Game
/GUI.py
1,573
4.25
4
# import the tkinter module import tkinter def main(): # create the GUI application main window root = tkinter.Tk() # customize our GUI application main window root.title('CS 21 A') # instantiate a Label widget with root as the parent widget # use the text option to specify which text to display hello = tkinter.Label(root, text='Hello World!') # invoke the pack method on the widget hello.pack() # create a STOP button stop_button = tkinter.Button(root, text='STOP') stop_button.pack() # create a GO button go_button = tkinter.Button(root, text='GO') go_button.pack() # create the GUI application main window root1 = tkinter.Tk() # create a label title = tkinter.Label(root1, text="Let's Draw!") title.pack() # instantiate a Canvas widget with root as the parent widget canvas = tkinter.Canvas(root1, background='green') # draw a blue rectangle on the canvas # create_rectangle returns an object id that we save in the variable body body = canvas.create_rectangle(50, 50, 150, 100, fill='blue') # draw two red circles on the canvas # create_oval also returns an object id wheel1 = canvas.create_oval(50, 100, 75, 125, fill='red') wheel2 = canvas.create_oval(125, 100, 150, 125, fill='red') # draw a line my_line = canvas.create_line(50, 50, 150, 200) canvas.pack() # enter the main event loop and wait for events root1.mainloop() if __name__ == '__main__': main()
true
3ce98143dd5154e2dfe8ccf33ebd0fc502849ee5
antongulyakov/.py
/task2.py
577
4.34375
4
#!/usr/bin/env python # python3 import check def is_year_leap(year): "Chek the leap year" if -45 <= year < -8: if year % 3 == 0: return True elif -8 <= year < 1582: if (year % 4 == 0) and (year is not 0): return True elif year >= 1582: if (year % 4 == 0) and (year % 100 is not 0): return True elif year % 400 == 0: return True else: return False return False #year = check.input_num(1, 3) year = check.input_digit(1, 3) flag = is_year_leap(year) print(flag)
false
87883b97eb61df26cc428afb1b4c6cb4f8457c3f
oraocp/pystu
/primitive/base/lambda_expr.py
726
4.125
4
""" 文档目的:演示Python中lambda表达式的概念和用法 创建日期:2017/11/14 演示内容包括: 1. lambda表达式的概念 lambda只是一个表达式,函数体比def简单很多。 lambda表达式是起到一个函数速写的作用。允许在代码内嵌入一个函数的定义。 lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。 2.lambda表达式的用法 """ from functools import reduce def factorial(n): ''' 求数n的阶乘 :param n: 数n :return: 数n的阶乘 ''' return reduce(lambda x, y: x * y, range(1, n + 1)) if __name__ == "__main__": print('factorial(10)=', factorial(10))
false
b50c1702b58fe728e04f26409a0d44dbb0a0287c
lunAr-creator/learning_python
/while_loops.py
1,427
4.375
4
''' Loops are used repeat a certain action multiple times. Python gives us two options for this: while and for ''' #This loop will print the numbers 1-5 because every time the loop is run (until count = 5) 1 is added to count count = 1 while count <= 5: print(count) count += 1 #Cancelling a loop using break while True: stuff = input('String to capitalize [type e to exit]: ') if stuff == 'e': break print(stuff.capitalize()) #Sometimes, you dont want to break out of a loop but want to skip ahead to the next iteration. We can do this using the 'continue' keyword. while True: stuff = input('Integer [type e to exit]: ') if stuff == 'e': # quit break num = int(stuff) if num % 2 == 0: # an even number continue print(f'{num} squared is {num*num}') ''' If the while loop enden normally (no break), control passes to an optional else. You use this when youve coded a while loop to check for something, and breaking as soons as its found. ''' numbers = [1, 3, 5] position = 0 while position < len(numbers): number = numbers[position] if number % 2 == 0: print(f'Found even number {number}') position +=1 else: print('No even numbers found') ''' Expected Output: 1 2 3 4 5 String to capitalize [type e to exit]: w W String to capitalize [type e to exit]: e Integer [type e to exit]: 5 5 squared is 25 Integer [type e to exit]: e Found even number 6 ''' ''' Next file will be about for loops '''
true
22679ff1d5e51d6f15bb9302712c0c6b914636b1
amssdias/python-books_db
/csv/app.py
1,408
4.28125
4
from utils import database USER_cHOICE = """ Enter: - 'a' to add a new book - 'l' to list all books - 'r' to mark a book as read - 'd' to delete a book - 'q' to quit Your choice:""" def menu(): database.create_book_table() menu = { 'a': prompt_add_book, 'l': list_books, 'r': prompt_read_book, 'd': prompt_delete_book } user_input = input(USER_cHOICE) while user_input != 'q': try: user_option = menu[user_input] user_option() except KeyError: print('Unknown command. Please try again.') user_input = input(USER_cHOICE) # ask for book name and author def prompt_add_book(): name = input('Book name: ') author = input('Book author: ') database.add_book(name, author) # show all the books in our list def list_books(): books = database.get_all_books() for book in books: read = 'YES' if book['read'] == '1' else 'NO' print(f"{book['name']} by {book['author']}, read: {read}.") # ask for book name and change it to "read" in our list def prompt_read_book(): name = input('Enter the name of the book you just finished reading: ') database.mark_book_as_read(name) # ask for book name and remove book from list def prompt_delete_book(): name = input('Enter the name of the book you wish to delete: ') database.delete_book(name) menu()
true
1d9b536b3134f72446d97acc5c1fa40ef07da0a2
FlorianWi89/A-problem-a-day
/Parking_System.py
1,117
4.375
4
# Design a parking system for a parking lot. The parking lot has three kinds of # parking spaces: big, medium, and small, with a fixed number of slots for each size. # # Implement the ParkingSystem class: # ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. # The number of slots for each parking space are given as part of the constructor. # bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants # to get into the parking lot. carType can be of three kinds: big, medium, or small, # which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. # If there is no space available, return false, else park the car in that size space and return true. # class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.parkingSpaces = [big, medium, small] def addCar(self, carType: int): carIndex = carType-1 if self.parkingSpaces[carIndex] > 0: self.parkingSpaces[carIndex] -= 1 return True return False
true
41a14ab4052b768976c05db596a32c9b22f02ff8
varvara-spb99/DevOps
/hw2v.py
1,200
4.15625
4
"""Встроенная функция input позволяет ожидать и возвращать данные из стандартного ввода в виде строк (весь введенный пользователем текст до нажатия им enter). Используя данную функцию, напишите программу, которая: 1. После запуска предлагает пользователю ввести текст, содержащий любые слова, слоги, числа или их комбинации, разделенные пробелом. 2. Считывает строку с текстом, и разбивает его на элементы списка, считая пробел символом разделителя. 3. Печатает этот же список элементов (через пробел), однако с удаленными дубликатами.""" string = input("Enter something: ") lst = string.split(" ") result=[] for i in lst: if i not in result: result.append(i) result = ' '.join(result) print("Source text: "+ string) print("Text without duplicates: "+ result)
false
185abf614bf1127fc988f9d0175cb82095735c64
OLABOSS123/Hello-World
/List.py
669
4.1875
4
# name = ["Olamide","Olu", "John", "Bola"] # age = ["4", "5", "7", "8"] # # print(age.pop(3)) # # print(age) # # print(age[2]) # # print(age[0:3]) # print(name[0:3]) # lst = [1,2,3,4,5] # lst2= ["Jane","Kemi","Obi","Musa"] # lst3 = [1, "john", 2, "ada"] # print(len(lst)) # print(len(lst2)) # print(lst[1::2]) #This prints the reversed version of the numbers # print(lst[::-1]) #to change or replace the value of an index # lst.insert(0,0.5) # print(lst) # lst[0] = 5 # print(lst) # to delete an index #del lst[2] #print(lst) #to clear the whole index #lst.clear() #print(lst) # add value to lists #lst.append(6) #print(lst) # lst2.extend(lst3) # print(lst2)
false
bfec17ebabe824f54629f37961125a9033f5425b
Simranbassi/python_grapees
/ex4a.py
214
4.21875
4
year=int(input("enter the year ")) if year%4==0: print("the year you enter is a leap year") elif year%400==0: print("the year you enter is a leap year") else: print("the year you enter is not a leap year")
false
f615fb290428d9575c761455dbdf98ba9a98c89a
Simranbassi/python_grapees
/ex3i.py
309
4.125
4
ram=int(input("enter the age of ram : ")) shyam=int(input("enter the age of shyam : ")) ajay=int(input("enter the age of ahay : ")) if ram<shyam and ram<ajay : print("Ram is youngest ") if shyam<ram and shyam<ajay : print("shyam is youngest ") if ajay<ram and ajay<shyam : print("ajay is youngest")
false
e262eee555c5f359df24f443b21d660799969cfa
Simranbassi/python_grapees
/ex2f.py
340
4.125
4
kilometer=int(input("enter the distance (in kilometer) between two cities")) meter=1000*kilometer print("the distance in meter is",meter) feet=kilometer*3280.8 print("the distance in feet is",feet) inch=kilometer*39370.078 print("the distance in feet is",inch) centimeter=kilometer*100000 print("the distance in feet is",centimeter)
true
b8b0a1f73d8f245317e7235cd061ce7dc39bcacb
bopopescu/python-practice
/pycharm/telusko/generator.py
270
4.34375
4
#----- Generator is used to create iterators instead of using __iter__ and __next__ functions def square(): n = 1 while n <= 10: sq = n*n yield sq n+=1 sqvalues = square() print(sqvalues.__next__()) for i in sqvalues: print(i)
true
3896844aa193a1cd92560202a592fbcffde8a491
bopopescu/python-practice
/pycharm/telusko/fibonacci.py
441
4.1875
4
fn = int(input("Please enter length of fibonacci series : ")) #------- Fibonacci series -1 def fibonacci(n): if n <= 0: print("Number is negative number") elif n == 1: a=0 print(a) else: a=0 b=1 print(a) print(b) for i in range(2,fn): c = a + b a = b b = c print(c) fibonacci(fn) #------- Fibonacci series -2
false
17a886fd906d09f08e10d59579334896757d4063
bopopescu/python-practice
/functions.py
1,665
4.1875
4
#-- Required arguments def printme(str): "This functions expects the required number of arguments to be passed" print(str) return; printme("Purushotham") #-- keyword arguments def keywordarguments(name,age): "This function expects the keyword arguments to be passed" print("My name is" + name + " and my age is " + age) return; keywordarguments(age='28',name="purushotham") #--- Default arguments def defaultarguments(name,age='28'): "This function expects the default arguments to be passed" print("my name is ", name + " my age is ", age) return; defaultarguments("Purushotham") #--- Variable length arguments def variablelengtharguments(*argv): "variable length arguments using argv" for arg in argv: print(arg) variablelengtharguments('purushotham','chandra','ravi') #--- variable length arguments using kwargs def kwarguments(**kwargs): for key,value in kwargs.items(): print("%s == %s" %(key,value)) kwarguments(Name='Purushotham',age='28') #--- anyonumous functions sum = lambda x,y : x+y print(sum(10,20)) #-- pass by reference def printlist(mylist): mylist.append([1,2,3]) print("Value inside function ",mylist) return mylist mylist = [ 10,20,30] printlist(mylist) print("Value outside funtion ", mylist ) def printlist1(mylist): mylist=[1,2,3] print("Value inside function ", mylist) return mylist = [10,20,30] printlist1(mylist) print("Value outside funtion is ", mylist) #--- local & Global variavles total = 0 def sum(x,y): print("Value inside function is ", x+y) return sum(10,20) print("Value outside function is ", total)
true
6666d89a9c98a30a2bc454f62c9c4ab22007edfa
bopopescu/python-practice
/lists.py
2,170
4.65625
5
#-- creating a list mylist = [] print("printing the empty list") print(mylist) #-- adding element to the list mylist=['purushotham'] print("adding element to the list") print(mylist) #-- Adding multiple elements to the list mylist=['hello','purushotham','reddy'] print('adding multiple elements to the list') print(mylist) #-- adding lists to lists mylist=[['hello','purushotham'],['reddy']] print("adding lists to lists") print(mylist) #--- creating a list with duplicate values mylist=['h','p','h','w','l','p','n','w'] print("creating a list with duplicate values") print(mylist) #--- creating a list with mixed type of values mylist=['a',1,"purushotham",7+10] print("creating a list with mixed type of values") print(mylist) #--- adding elements to list mylist=[] print("printing empty list") print(mylist) mylist.append(1) mylist.append(2) mylist.append(4) print(mylist) for i in range(1,4): mylist.append(i) print(mylist) mylist.append((5,6))#adding tuple to list print("adding tuple to list") print(mylist) mylist2=['hello','purushotham'] mylist.append(mylist2) print("appending list to list") print(mylist) mylist2.insert(0,'Reddy') print(mylist2) mylist.insert(3,'Accenture') print(mylist) # adding multiple elements at the end of the list using extend mylist.extend([8,'hey','wow']) print(mylist) #-- Accessing the elements of list using indexes mylist=["Hello","Puruhsotham","Reddy"] print(mylist[0]) print(mylist[2]) mylist=[['Hello','purushotham'],['reddy']] print(mylist[0][1]) print(mylist[1][0]) mylist=[1,'hello','puru','reddy',8+17] print(mylist[-1]) print(mylist[-3]) #-- Removing the elements using remove and pop method mylist=[1,2,3,4,5,6,7,8,9] mylist.remove(5) mylist.remove(6) print(mylist) for i in range(1,5): mylist.remove(i) print(mylist) mylist.pop() print(mylist) mylist.pop(1) print(mylist) #-- slicing using : mylist = ['h','e','y','z','l','k','b','r','x','q','w','d'] print(mylist[3:7]) print(mylist[5:]) print(mylist[:-6]) print(mylist[:]) # printing whole list print(mylist[::-1])# printing the elements in reverse order #--- to check all the functions supported by list type print(dir(list))
true
1027ce9e3efc931b56863be135062b8c450804ee
Avlbelikov/python-homeworks
/homework_1_5.py
775
4.125
4
income = int(input('Укажите доход компании: ')) spending = int(input('Укажите расходы компании: ')) if income > spending: print('Доходы превышают расходы: Ваша компания приносит прибыль!') print('Ваша прибыль: ', income - spending , 'Рублей') workers = int(input('Укажите количество сотрудников вашей компании: ')) print('Прибыль компании исходя из расчета на одного сотрудника: ', (income - spending) / workers, 'Рублей') if income < spending: print("Расходы превышают доходы: Ваша компания несет убытки!")
false
9cfd82a7813c3d1042be99a1eea0155439d7fb03
CristinaPineda/Python-HSMuCode
/Exemplo_recursao/funcao_recursao.py
1,783
4.53125
5
""" Em programação, a recursão envolve problemas em que uma função chama a si mesma. Toda função recursiva possui uma condição base para que ela seja finalizada. O que é recursão? Recursão é um método de resolução de problemas que envolve quebrar um problema em subproblemas menores e menores até chegar a um problema pequeno o suficiente para que ele possa ser resolvido trivialmente. Normalmente recursão envolve uma função que chama a si mesma. Embora possa não parecer muito, a recursão nos permite escrever soluções elegantes para problemas que, de outra forma, podem ser muito difíceis de programar. Ex: (panda.ime.usp.br) Uma função iterativa que calcula a soma é mostrada no exemplo abaixo. A função usa uma variável acumuladora (theSum) para calcular o total de todos os números da lista iniciando com 0 e somando cada número da lista. """ def listsum(numList): theSum = 0 for i in numList: theSum = theSum + i return theSum print(listsum([1,3,5,7,9])) """ Imagine por um minuto que você não tem laços while ou for. Como você calcularia a soma de uma lista de números? Em primeiro lugar, vamos reformular o problema soma em termos de listas de Python. Poderíamos dizer que a soma da lista numList é a soma do primeiro elemento da lista (numList [0]), com a soma dos números no resto da lista (numList [1:]). De forma funcional podemos escrever: listSum(numList)=first(numList)+listSum(rest(numList)) Nesta equação first(numList) retorna o primeiro elemento da lista e rest(numList) retorna a lista com tudo menos o primeiro elemento. """ def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:]) print(listsum([1,3,5,7,9]))
false
e373cc2c3e63856ecd859da7629f9ec0f4d75d77
CristinaPineda/Python-HSMuCode
/Exemplos_strings/media_semestre.py
694
4.375
4
""" No terceiro exemplo, será calculada a média semestral de um aluno. O semestre é composto por três notas, cada uma com os pesos 2, 4 e 6, respectivamente. Como primeiro passo, o programa deve solicitar a entrada das três notas. Em seguida, precisa calcular a média ponderada por causa dos pesos na composição das notas. O resultado será armazenado na variável media e a saída será o valor da média com precisão de dois dígitos. """ nota1 = float(input('Insira a primeira nota: ')) nota2 = float(input('Insira a segunda nota: ')) nota3 = float(input('Insira a terceira nota: ')) media = ((nota1 * 2) + (nota2 * 4) + (nota3 * 6))/12 print(f'Média do semestre: {media:.2f}')
false
169c04e53dafc83ebc3e03841ccec520321ab17a
xerifeazeitona/PCC_Alien_Invasion
/exercises/12_04_rocket/super_rocket.py
2,904
4.25
4
""" 12-4. Rocket: Make a game that begins with a rocket in the center of the screen. Allow the player to move the rocket up, down, left, or right using the four arrow keys. Make sure the rocket never moves beyond any edge of the screen. """ import sys import pygame from settings import Settings from rocket import Rocket class SuperRocket: """Overall class to manage game assets and behaviour.""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Super Rocket!!!") self.rocket = Rocket(self) def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: # Move the rocket to the right self.rocket.moving_right = True if event.key == pygame.K_LEFT: # Move the rocket to the left self.rocket.moving_left = True if event.key == pygame.K_UP: # Move the rocket up self.rocket.moving_up = True if event.key == pygame.K_DOWN: # Move the rocket down self.rocket.moving_down = True if event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT: # Move the rocket to the right self.rocket.moving_right = False if event.key == pygame.K_LEFT: # Move the rocket to the left self.rocket.moving_left = False if event.key == pygame.K_UP: # Move the rocket up self.rocket.moving_up = False if event.key == pygame.K_DOWN: # Move the rocket down self.rocket.moving_down = False def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip() if __name__ == "__main__": # Make a game instance, and run the game. sr = SuperRocket() sr.run_game()
true
b2be5653b22bacfd4355128b90e3ca9efb9e15b2
iamanobject/Lv-568.2.PythonCore
/HW_5/OliaPanasiuk/Home_Work5_Task_1.py
407
4.25
4
#a = range(11) #for x in a: #if x % 2 == 0: # print(x) #continue #print("This numbers are divisible by 2") #a = range(11) #for x in a: #if x % 3 == 0: # print(x) #continue #print("This numbers are divisible by 3") a = range(11) for x in a: if x % 2 != 0 and x % 3 != 0: print(x) continue print("This numbers are not divisible by 2 and 3")
false
d328ed927f8ee05cc60eab542643e77fd3621419
iamanobject/Lv-568.2.PythonCore
/HW_5/serhiiburnashov/convert-boolean-values-to-strings-yes-or-no.py
275
4.21875
4
def bool_to_word(boolean): """ Method that takes a boolean value and return a "Yes" string for true, or a "No" string for false. """ message = "Yes" if boolean else "No" return message #Yes print(bool_to_word(True)) #No print(bool_to_word(False))
true
da99ef0ac07b7619c844d5c773d0b2b867bd6182
iamanobject/Lv-568.2.PythonCore
/HW_6/ruslanliska/Home_Work6_Task_1.py
558
4.25
4
def largest_number(a, b): """The function returns bigger numbers Input is 2 digits Output is bigger number """ # a = input("Please enter first number: ") # b = input("Please enter second number: ") if a>b: return ("First number {} is bigger than second number {}".format(a, b)) elif a == b: return ("First number {} is equal to second number {}".format(a, b)) else: return ("Second number {} is bigger than first number {}".format(b, a)) print(largest_number(17,16)) print(largest_number.__doc__)
true
dade4188c910ed8807267fb86e0d73723c13c9a1
iamanobject/Lv-568.2.PythonCore
/HW_3/serhiiburnashov/Home_Work3_Task_3.py
391
4.125
4
first_variable = input("Enter first variable: ") second_variable = input("Enter second variable: ") print( "Before:" ) print( "First variable:", first_variable, "Second variable:", second_variable ) first_variable, second_variable = second_variable, first_variable print( "After:" ) print( "First variable:", first_variable, "Second variable:", second_variable )
true
ce1ff5ae00abba12c3d9375fe612cda63b6a7727
iamanobject/Lv-568.2.PythonCore
/HW_6/ruslanliska/Home_Work6_Task_3.py
330
4.40625
4
def count_symbols (word): """This function calculates all symbols in string""" letter_dict = {} for letter in word: if letter not in letter_dict: letter_dict[letter] = 1 else: letter_dict[letter] = letter_dict[letter]+1 return letter_dict print(count_symbols(input("Please, enter your string: ")))
true
d4f4a0bc5af0d6298952b9f1a2a6a7d98dab6607
iamanobject/Lv-568.2.PythonCore
/HW_9/Taras_Smaliukh/HW9_task2.py
368
4.15625
4
def dayName(day_num): days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return days[day_num-1] if 0 < day_num <= len(days) else None try: day_num = int(input('Enter the number of the day in the week : ')) if day_num == int(day_num): print(dayName(day_num)) except ValueError as e: print("You should entered a number")
true
a88171d80c41aaf2ff8a57f17c1328a8bb175bbc
iamanobject/Lv-568.2.PythonCore
/HW_8/serhiiburnashov/grasshopper-summation.py
300
4.21875
4
def summation(num): """ Function that finds the summation of every number from 1 to num. """ result = sum(list(range(num + 1))) return result # 1 print(summation(1)) # 36 print(summation(8)) # 253 print(summation(22)) # 5050 print(summation(100)) # 22791 print(summation(213))
true
393d64a2b8d98827137d8d22987c360418940da1
iamanobject/Lv-568.2.PythonCore
/HW_7/ruslanliska/Home_Work7_Task_2.py
1,317
4.28125
4
import re def password_check(): """This function validates password cheks if there is at least 1 capital letter if there us more than 6 or less than 16 characters, if there at least 1 lowercase letter, if there at least 1 specific character and 1 digit """ password = input("Please enter your password: ") result_upper = re.findall("[A-Z]", password) result_lower = re.findall("[a-z]", password) result_digit = re.findall("\d", password) result_special = re.findall("[#$@]", password) max_len = 16 min_len = 6 if len(password) < min_len: return "Password must consist at least 6 characters" elif len(password) > max_len: return "Password must consist no more than 16 characters" elif result_upper == []: return "Your password is invalid. Password must consist at least 1 capital letter" elif result_lower == []: return "Your password is invalid. Password must consist at least 1 lowercase letter" elif result_digit == []: return "Your password is invalid. Password must consist at least 1 digit" elif result_special == []: return "Your password is invalid. Password must consist at least 1 special symbol (@#$)" else: return "Your password is valid" print(password_check())
true
1b9d5dbddc0dfdb51ba5828c0b54bb49227ae886
iamanobject/Lv-568.2.PythonCore
/HW_5/ruslanliska/Kata_1.py
367
4.1875
4
distance_to_pump = int(input("What is the distance to pump? ")) mpg = int(input("How many miles your car takes per gallon? ")) fuel_left = int(input("How many fuel left in your car?'")) def zero_fuel(distance_to_pump, mpg, fuel_left): if fuel_left >= distance_to_pump / mpg: return True return False print(zero_fuel(distance_to_pump, mpg, fuel_left))
true
8e263e425e01c92e470ac17ea59413f66368decc
snowtiger42/Shapes-01
/rectangle.py
1,227
4.15625
4
from shape import Shape class Rectangle(Shape): def __init__(self, name, width, height): self.__name = name self.__width = width self.__height = height # def set_name(self, name): # self.__name = name def get_name(self): if self.__name is not "Rectangle": raise Exception ("Wrong Name or data type") return self.__name def perimeter(self): if self.__name is not "Rectangle": raise Exception ("Wrong Name or data type") return 2 * (self.__width + self.__height) def area(self): if self.__name is not "Rectangle": raise Exception ("Wrong Name or data type") return self.__width * self.__height def draw(self): result = "" if self.__name is not "Rectangle": raise Exception("Wrong Name or data type") for shape in self.Shape: result = result + shape.__str__() + "\n" def testPerimeter(): r1 = Rectangle("Rectangle", 2.5, 5) print(r1.perimeter()) def testArea(): r2 = Rectangle("Rectangle", 2.5, 5) print(r2.area()) testPerimeter() testArea()
false
50ba71168512a6c00adbe4cb45b92071aad8edf8
cdvillegas/datastructures
/datastructures/hash_table.py
1,323
4.21875
4
class HashTable: """ A HashTable is a data structure that provides a mapping between keys and values using a hashing function. It allows efficient retrieval, insertion, and deletion of elements. The keys are hashed into indices of an array, and values are stored at those indices. In case of hash collisions, chaining is used to store multiple key-value pairs at the same index. """ def __init__(self, size): self.table = [[] for _ in range(size)] self.size = size def put(self, key, val): # Compute the index using the hash function index = hash(key) % self.size chain = self.table[index] # Search the chain to see if the key already exists # If it does, overwrite it for i in range(len(chain)): if chain[i][0] == key: chain[i] = (key, val) return # If the key does not exist, append a new key-value # tuple to the chain self.table[index].append((key, val)) def get(self, key): # Compute the index using the hash function index = hash(key) % self.size # Search the chain for the key and return # the corresponding value for k, v in self.table[index]: if k == key: return v # If the key does not exist, raise a KeyError raise KeyError
true
3fc439fa20e1220659f7f5060341f242e3e25879
amiraHag/python-basic-course2
/set/set4.py
979
4.40625
4
# ------------------------------- # --------- Set Methods --------- # ------------------------------- # issuperset() return true if the set contains all elements in the second set set1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } set2 = { 1, 2, 3, 4 } set3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } set4 = { "A", "B", "C" } print(set1.issuperset(set2)) print(set1.issuperset(set3)) print(set1.issuperset(set4)) print("*"*40) # issubset() return true if the set contains part of the elements in the second set set5 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } set6 = { 1, 2, 3, 4 } set7 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} set8 = { "A", "B", "C" } print(set6.issubset(set5)) print(set7.issubset(set5)) print(set8.issubset(set5)) print("*"*40) # isdisjoint() return true if the set didn't contains any of the elements in the second set set9 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } set10 = { 1, 2, 3, 4 } set11 = { "A", "B", "C" } print(set9.isdisjoint(set10)) print(set9.isdisjoint(set11)) print("*"*40)
true
8c7985276536f988e7a4f8752f9ebc06802b363c
amiraHag/python-basic-course2
/function/function2.py
1,135
4.4375
4
# --------------------------------------- # -- Function Parameters And Arguments -- # --------------------------------------- a, b, c = "One", "Two", "Three" print(f"Number {a}") print(f"Number {b}") print(f"Number {c}") print("*"*40) # def => Function Keyword [Define] # say_hello() => Function Name # name => Parameter # print(f"Hello {name}") => Task # say_hello("Ahmed") => Function Call , Ahmed is The Argument def say_hello(name): print(f"Hello {name}") say_hello("Amira") say_hello(a) say_hello(b) say_hello(c) print("*"*40) def addition(number1, number2): return number1 + number2 print(addition(5, 9)) def additionIntegers(number1, number2): if type(number1) != int or type(number2) != int: return "only integers allowed" else: return number1 + number2 print(additionIntegers(7, 10)) print(additionIntegers(7, 10.00)) print("*"*40) def display_full_name(first, middle, last): print(f"{first.strip().capitalize()} {middle.strip().upper():.01s} {last.strip().capitalize()}") display_full_name("amira ", " hag", " mustafa")
false
ca1a99a20be44463289093dd275f453413a6177b
amiraHag/python-basic-course2
/function/function8.py
479
4.25
4
# ------------------------ # -- Function Recursion -- # ------------------------ # --------------------------------------------------------------------- # -- To Understand Recursion, You Need to First Understand Recursion -- # --------------------------------------------------------------------- def cleanWord(word): if len(word) < 2: return word return cleanWord(word[1:]) if word[0] == word[1] else word[0] + cleanWord(word[1:]) print(cleanWord("AAAAmmmiiira"))
false
a158334fdb3a8b335d0562453ee976d13512057b
Sanjay567-coder/NumberGuessingGame
/Number Guessing Game.py
1,098
4.28125
4
print("Number Guessing Game") #importing randit from random from random import randint guessesTaken = 0 print("What's your Name?") myName=input() #Telling the computer to pick a number between 1 and 15 number=randint(1,15) print("Hello!,", myName,",I am thinking a number between 1 and 15") print("You have only 8 chances to predict ME") while guessesTaken < 8: print("Guess the number which I tought") guess = int(input()) guessesTaken = guessesTaken + 1 #creating condition for checking whether the guessed number too high or too low if guess > number : print("Your guess was too high: Guess a number lesser than ",guess) if guess < number : print("Your guess was too low: Guess a number higher than ",guess) if guess == number : break if guess == number: guessesTaken = str(guessesTaken) print('Good job,' + myName + '! You guessed the correct number in '+ guessesTaken +' guesses!') if guess != number: number = str(number) print('Sorry...You ran out of 8 guesses!') print("Please try again Later")
true
31259ca678b11249f5aa50a17427ed26e49ba71a
TechNestOwl/DigitalCrafts-COR
/Python/thursdayPython.py
321
4.25
4
# lists # --- How to create groceries = ["milk","eggs","bread","salmon"] print (groceries[-2]) print (groceries[-3]) # Adding to a list groceries.append("bacon") print(groceries) # How to remove items popped_item = groceries.pop(3) print(groceries) print(popped_item) # Remvoe bread del groceries[2] print(groceries)
true
983e609a02c1e0095eb1fdfc1ef63484bfaba889
hugo-wsu/python-hafb
/Day1/gen.py
1,672
4.1875
4
#!/usr/bin/env python3 """ Author : hvalle <me@wsu.com> Date : 8/9/2021 Purpose: """ def take(count, iterable): """ Take items for the front of the iterable :param count: The maximum number or items to retrieve :param iterable: The source series :yield: At most 'count' items for 'iterable """ counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def run_take(): items = [2, 4, 6, 8, 10] for item in take(3, items): print(item) def distinct(iterable): """ Return unique items by eliminating duplicates :param iterable: The source series :yield: Unique elements in order from 'iterable' """ seen = set() for item in iterable: if item in seen: continue yield item seen.add(item) def run_distinct(): items = [5, 7, 7, 6, 5, 5] for item in distinct(items): print(item) def run_pipeline(): items = [3, 6, 6, 2, 1, 1] for item in take(3, distinct(items)): print(item) # -------------------------------------------------- def main(): """Make your noise here""" # run_take() # run_distinct() # run_pipeline() # Generators: (expr(item) for item in iterable) # Task: Calculate the sum of the first 1 thousand square numbers m_sq = (x*x for x in range(1, 1000001)) # Save memory l_sq = list(m_sq) # l_sq = [x*x for x in range(1, 1000001)] # Comprehension print(f'The sum of the first 1000 square numbers is: {sum(l_sq)}') # -------------------------------------------------- if __name__ == '__main__': main()
true
b3bc30b824184a28aaff4b8d48776d74f6fe3d2a
thalytacf/PythonClass
/pre_codility/atv2.py
1,822
4.28125
4
# CyclicRotation # # Uma matriz A consistindo de N inteiros é fornecida. # A rotação da lista significa que cada elemento é deslocado para a direita por um índice, # e o último elemento da lista é movido para o primeiro lugar. # Por exemplo, a rotação da lista A = [3, 8, 9, 7, 6] é [6, 3, 8, 9, 7] # (os elementos são deslocados para a direita por um índice e 6 é movido para o primeiro lugar). # # O objetivo é girar a matriz A K vezes; isto é, cada elemento de A será deslocado para o K tempo certo. # # Escreva uma função: # # solução def (A, K) # # que, dada uma lista A que consiste em N números inteiros e um número inteiro K, # retorna a lista A girada K vezes. # # Por exemplo, dado # # A = [3, 8, 9, 7, 6] # K = 3 # # a função deve retornar [9, 7, 6, 3, 8]. Foram realizadas três rotações: # # [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7] # [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9] # [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] # Por outro exemplo, dado # # A = [0, 0, 0] # K = 1 # a função deve retornar [0, 0, 0] # # Dado # # A = [1, 2, 3, 4] # K = 4 # a função deve retornar [1, 2, 3, 4] # ----------- Resolution ------------- # # def matrix_rotation(A, K): # for times in range(K): # a = A[-1] # A.remove(a) # A.insert(0, a) # return A # # # matrix_a = [1,2,3,4,5] # print(matrix_rotation(matrix_a, 3)) # # Result: [3, 4, 5, 1, 2] # # matrix_b = [1,2,3,4] # print(matrix_rotation(matrix_b, 1)) # # Result: [4, 1, 2, 3] # def solution(a, k): for time in range(k): last = a.pop(-1) a.insert(0, last) return a # # matrix = [] # print(solution(matrix, 2)) def solution(A, K): if A == []: return A for times in range(K): a = A[-1] A.remove(a) A.insert(0, a) return A
false
0bd33d1a36f0cba21689f4b2a1314219e2152827
umutcaltinsoy/Objected-Oriented-Programming
/oop_005.py
1,632
4.59375
5
#Special (Magic/Dunder[Double Underscores]) Methods: #These special methods allow us to emulate some built-in behavior within Python #And it's also how we implement operator overloading #These special methods are always surrounded by double underscores(dunder) #So a lot of people call the double underscores dunder # def __repr__(self): # pass # def __str__(self): # pass #These two special methods allow us to change how our objects are printed and displayed class Employee: raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amt) def __repr__(self): return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay) def __str__(self): return '{} - {}'.format(self.fullname(), self.email) #if we wanted to add two employees together and have the result their combined salaries #we're going to have create __add__ def __add__(self, other): return self.pay + other.pay def __len__(self): return len(self.fullname()) emp_1 = Employee('Umut', 'Cagri', 10000) emp_2 = Employee('Test', 'User', 20000) print(len(emp_1)) #print(len('test')) = print('test'.__len__()) print(emp_1 + emp_2) #it gives us combined salaries #print(emp_1) print(repr(emp_1)) print(str(emp_1)) #print(emp_1.__repr__()) #print(emp_1.__str__()) print(1+2) print(int.__add__(1,2))
true
1a716957853b41768565e2b262bc9e638e3fa55c
BhargavReddy461/Coding
/Binary Tree/Flip_BinaryTree_clockwise.py
1,463
4.4375
4
# Python3 program to flip # a binary tree # A binary tree node class Node: # Constructor to create # a new node def __init__(self, data): self.data = data self.right = None self.left = None def flipBinaryTree(root): # Base Cases if root is None: return root if (root.left is None and root.right is None): return root # Recursively call the # same method flippedRoot = flipBinaryTree(root.left) # Rearranging main root Node # after returning from # recursive call root.left.left = root.right root.left.right = root root.left = root.right = None return flippedRoot def levelorder(root): if root is None: return q = [] q.append(root) q.append(None) while len(q) > 1: node = q.pop(0) if node == None: q.append(None) print() else: if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) print(node.data, end=" ") # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.right.right = Node(5) levelorder(root) print("\n") root = flipBinaryTree(root) levelorder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
true
f657636d845dea0e6870ab0fb92c26e63ddd2f96
BhargavReddy461/Coding
/LinkedList/insert_in_a_sorted_SLL.py
1,116
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def traversal(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next def sortedInsert(self, new_data): new_node = Node(new_data) curr = self.head if self.head == None: self.head = new_node return if curr.data > new_node.data: new_node.next = curr self.head = new_node return while curr.next and curr.next.data < new_node.data: curr = curr.next new_node.next = curr.next curr.next = new_node if __name__ == '__main__': start = LinkedList() start.push(8) start.push(7) start.push(4) start.push(3) start.sortedInsert(5) start.traversal()
true
4ed287357b0c476a892091e0ac62a12e8f58ed0b
Pavana16/scripting-language
/prg2.py
568
4.46875
4
#demo classes in python #concept:use of delete attribute of obj and obj itself class Person: def __init__(self,name,age): #constructor of the class Person self.name=name; self.age=age; p1 = Person('supandi',14) print("\n the name of person1 is:",p1.name) print("\n the age of person1 is:",p1.age) print("\n ***printing after deleting age attribute ***\n") del p1.age #deleting age attribute print("\n the name of person1 is:",p1.name) print("\nprinting after deleting p1") del p1 print("\n the name of the person:",p1.name) #gives an error
true
806f186357f7f6e9be6e07a8a7d67d11f126c8d9
data-modeler/prod-ready-ml
/src/models/train_model.py
581
4.125
4
''' Train Model ----------- Runs the training for the model. ''' def sample(x: int=1, letters: str='ABC') -> bool: '''Is a sample function. Note: This is an example of complete documentation. Args: x: The first value to pass in. letters: The second argument. Returns: True if acceptable; False if unacceptable Raises: ValueError: if `x` is not int or `letters` is not string Examples: >>> print(sample(3, ' is the number')) '3 is the number' ''' str(x) + letters return
true
61980a8f48ea05db7f7e59d0f2d79db1bf3c61b2
sharamamule/Py_Learn
/Py_Udemy1/Numbers.py
831
4.125
4
int_num = 1000 # this is the way we define the number in python float_num = 20.5 print(int_num) print(float_num) print ('*******') a=10 b=50 add = a+b print(add) sub =b-a print(sub) multi = a*b print(multi) div = a/b print(div) exponents = 10 ** 20 # 10 to the power of 20 (10*10...20 times) , symbol is " ** " print(exponents) remainder = 11 % 3 # % -- will give the remainder for the value print(remainder) """ >>> (2+4) * 3 / 2 ## the output is 8.0 I.e division & multiplication will take the precedence , hence they are done first 9.0 >>> (2+4*5 ) * 3 / 2 33.0 >>> (2+4*2 ) * 3 / 2 ## But if we want to do it our way we use 'parenthesis' = (2+4)*3 /2 = 9.0 15.0 ## Same precedence is carried out if we have multiple calculations under parenthesis. >>> """
true
fcd418d51797e43cff669f3955752ac909c26ac3
sharamamule/Py_Learn
/Py_Udemy1/Postional-Optional Parameters.py
527
4.1875
4
""" Postiional Parameters They are like optional paramters And can be assigned a default value, if no value is provided from outside """ def sum_nums (n1=2, n2=4): # Optional Paramters # def sum_nums (n1,n2=4): we can declare this also return n1 + n2 sum1 = sum_nums(n1=5,n2=5) print(sum1) print("**********************") sum2 = sum_nums (4,n2=10) # We can use the arguments different ways print(sum2) def sum_nums2(n1, n2=4): return n1 + n2 sum1 = sum_nums2(n1=4, n2=12) print(sum1)
true
b6686802837e75137cdf323cc7026a399fea6e75
bharathmc92/python-coding
/conditional_changes_output.py
272
4.1875
4
num_knights = int(input("Enter the number of knights \n")) day = input("Enter the day of the week \n") if num_knights < 3 or day == "Monday": print("Retreat!") elif num_knights >=10 and day == "Wednesday": print("Trojan Rabbit!") else: print("Truce?")
false
2c37d21ac32355a8bf6ca792e3a83fd8f8157e67
bharathmc92/python-coding
/challenge_1.py
316
4.1875
4
#program to check the age of a person and allow if he is eligible for 18-30 holiday name = input("Enter your Name:") age = int(input("Enter your age: ")) if 17 < age < 31: print("Welcome to the Holiday {0}".format(name)) else: print("Sorry, you are not eligible for this holiday trip {0}".format(name))
true
532c6aa9d1d02517bf96d2e51558c220b7aa24e6
kys1234561/pycharmprojects
/Pre_course_links/day2_06_01.py
892
4.34375
4
''' num_list = [1,5,2,3,9] num_list.sort() print(num_list) num_list = [1,5,2,3,9] print(sorted(num_list)) print(num_list) num_list.reverse()#reverse本身的意思有反向,reverse表示反向排序 print(num_list) num_list = [] l1 = [1,2,3] print(num_list) num_list.append(l1) print(num_list) ''' num_list = [] l1 = [1,2,3] l2 = [4,5,6] l1.append(l2) print(l1,'\n') num_list.append(l1) print(num_list) num_list.append(l1) print(num_list) #num_list[0][3][1] = 100 #print(num_list) print(num_list[0][3][2]) print(num_list[1][3][2]) a = [[1,2,3],[53,2,1]] print(a[0][1]) a = [1,2,3] b = [1,4,8] a.extend(b) print(a) a.extend(b) print(a) a = [1,2,3] b = [1,4,8] a.append(b) print(a) print(a[0]) print(a[3]) print(a[3][1]) a.append(b) print(a) print(a[0]) print(a[3]) print(a[3][1]) a = [1] a.insert(1,3) print(a) a.remove(1) print(a) a = [1] a.insert(1,3) print(a) a.pop(1) print(a)
false
a4d89857aa782981d9fc2bb1e4dd738b89d51444
jraman/algos
/python/backtracking/permutations.py
822
4.125
4
''' Backtracking: Find all the permutations of the characters in a string or elements in an array. Note: * Time complexity: O(n!) * If letters are repeated in the input, the output set will have repeated strings. Ref: * http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ ''' def swap(array, ii, jj): tmp = array[jj] array[jj] = array[ii] array[ii] = tmp def print_array(array): print ''.join(array) def permute(array, idx=0): if idx == len(array) - 1: print_array(array) return for jj in xrange(idx, len(array)): swap(array, idx, jj) permute(array, idx + 1) swap(array, idx, jj) def main(text): array = list(text) permute(array) if __name__ == '__main__': import sys main(sys.argv[1])
true
91843d3128c930fd947ff1eda05117f518179197
ChawEiPhyu308/CP1404
/Prac_1/loops.py
329
4.15625
4
for i in range(1, 21, 2): print(i, end=' ') print() for i in range(0, 110, 10): print(i, end=' ') print() for i in range(20, 0, -1): print(i, end=' ') print() star = int(input("Enter a number :")) while i <= star: print('*', end=' ') i += 1 print('') for i in range(1, star+1): print('*'*i) print()
false
de688eb65832a432ccc8f4490c9edee48e350710
dalukyanov/PythonAlgorithms
/algorithms/integers/recursive_sum_of_digits.py
936
4.21875
4
def sum_of_digits(n): """ Функция вычисляет сумму всех разрядов в числе """ sm = 0 while n > 0: d = n % 10 n = n // 10 sm += d return sm def recursive_sum_of_digits(n): """ Функция вычисляет рекурсивно сумму всех цифр, входящих в число "n" до тех пор пока не останется один разряд Пример: recursive_sum_of_digits(132189) => 1 + 3 + 2 + 1 + 8 + 9 => 24 ... => 2 + 4 => 6 """ while n > 9: n = sum_of_digits(n) return n if __name__ == "__main__": print(recursive_sum_of_digits(16)) # 7 print(recursive_sum_of_digits(942)) # 6 print(recursive_sum_of_digits(132189)) # 6 print(recursive_sum_of_digits(493193)) # 2 print(recursive_sum_of_digits(0)) # 0
false
20a908651e8b18c44e4a207b8599a4a62aee6a13
eiadshahtout/Python
/python3/fruit.py
370
4.15625
4
favouriteFruits = ["Bananas","Apples","Mangoes"] if "Bananas" in favouriteFruits: print("You like bananas") else: print("You don't like bananas") if "Peacjes" in favouriteFruits: print("You like peaches") else: print("You don't like peaches") if "Apples"in favouriteFruits: print("You really like apples!") else: print("You don't like apples")
false
2d4568d32b5f180dae7ac6d5928b971ffb2f5ec4
eiadshahtout/Python
/python3/album.py
798
4.34375
4
def make_album(artistName, albumTitle, numberOfSongs = None): album = { "Name": artistName, "Title" : albumTitle } if numberOfSongs: album["Number_Songs"] = numberOfSongs return album while True: print("--------------------------------------------") artist_n = input("What is the name of the artist? ") print("--------------------------------------------") album_n = input("What is the title of the album? ") print("--------------------------------------------") print("This is optional! ") numberofsongs = input("What are the number of the songs in the album? ") print("--------------------------------------------") break message = make_album(artistName = artist_n, albumTitle = album_n, numberOfSongs = numberofsongs) print(message)
true
9d3f54aa3279a1a32f2be807b3b0e842460fce7f
Kritika05802/Functions
/Functions.py
451
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #prints the letters in a string in decreasing order of frequency # In[4]: a=input("Please enter a string: ") def most_frequent(string): mydict=dict() for key in string: if key not in mydict: mydict[key]=1 else: mydict[key]+=1 q=mydict.items() n=sorted(q, key=lambda x: x[1], reverse=True) return n print(most_frequent(a)) # In[ ]:
true
35e2f1c5272886912bcc246e81a67fb08f1bf8a7
Trago18/master-python-programming-exercises
/exercises/11-Swap_digits/app.py
315
4.15625
4
#Complete the fuction to return the swapped digits of a given two-digit-interger. def swap_digits(num): first = num//10 second = num%10 return (str(second) + str(first)) #return ((second*10) + first) #Invoke the function with any two digit interger as its argument print(swap_digits(30))
true
3728125e0d0893a76937e51aa63c613a123d6c08
Talibov333/Python3-for-beginner-az
/python3/strngmetods.py
1,615
4.125
4
teststring = 'py is a wonderfull' print(len(teststring)) # len funksiyasi stringin xarekter sayini gosterir # len() funks ile hemcinin input meselelrinde ist edilir teststring = 'py is a wonderfull' print(teststring.upper()) # stringin xarexterlerini boyutmek ucun .upper() ist edlr # stringi orijinalini deyisdirmir yalniz xarextrni deysdirir teststring = 'Py is a wonderfull' teststring = teststring.upper() print(teststring) # burda stringimiz orijinal sekilde deyisdirir yeni boyudur teststring = 'py is A wondeRFull' print(teststring.lower()) # strng xarekterini kiciltmek ucn teststring = 'pY is A wondeRFull' print(teststring.title()) # stringin yalniz ilk herfini boyudur teststring = 'pY is a wonderfull' print(teststring.find('w')) # find() metodu ile biz w herfini necenci sirada oldugunu bilmek isteyirikse # burda ilk gorduyu xarekterini gosterecek teststring = 'pY is a wonderfull' print(teststring.replace('wonderfull','high level programing')) # replace xarekterleri deyisdirmek ucun ist edlr. # neticesi wonderful yerine high level programing olacag teststring = 'py is a wonderfull' print('py' in teststring) print('python' in teststring) # bir xarekterin stringde olub olmasi ucun in metodundan ist edilir # 1-ci printde 'py' sozu oldugu ucun True donecek # 2-cide ise 'python' sozunu tapmayacag ve False donecek teststring = 'Py is a wonderfull Programing wonderfull' print(teststring.count('P')) print(teststring.count('wonderfull')) # bir sozun (ve ya herfin,reqemin) strng ifadade nece defe ilendiyini bilmek # ucun ist edilir netice 2 yeni 'wonderfull' sozu 2defe islenib
false
4c73dd2b34e4f810b6ee3250239ae0e98d3f4c49
icpc0928/MyFirstPython
/Leo/Leo012.py
349
4.25
4
# tuple 固定長度固定元素的串列 tpl = ("1", "2", "3", "4", 5) print(tpl) print(tpl[1]) a, b, c, d, e = tpl # 將tpl的所有元素一一給到每個變數內(變數數量與元素數量一樣) print(a) print(c) # tuple 因為不能修改的特性 所以不能有append/ extend的方法 # 好處是占用較少 元素不會任意更動
false
7772d90cf1bad0eba6595d44255a550f3113fba3
JerameKim/CS325HW4
/mergeSort.py
1,873
4.21875
4
def merge_sort(my_list, sort_func: lambda x, y: x < y): # 1. Exit Statement # only gets called n number of times if len(my_list) <= 1: return my_list middle_idx = len(my_list) // 2 # 2. Recurse # left = merge_sort(my_list[0:middle_idx]) # will return a sorted list from "left side" left = merge_sort(my_list[:middle_idx], sort_func) # right = merge_sort(my_list[middle_idx:len(my_list)-1]) # will return a sorted list from "right side" right = merge_sort(my_list[middle_idx:], sort_func) # 3. Resolve Recursion sorted_list = merge(left, right, sort_func) return sorted_list def merge(left, right, sort_func) -> []: combined = [] left_idx = 0 right_idx = 0 # Run while there's uncompared values in both lists while left_idx < len(left) and right_idx < len(right): # if left's value smaller than right's value if sort_func(left[left_idx], right[right_idx]): # add the left value in combined.append(left[left_idx]) # increment to compare to next left element left_idx += 1 else: combined.append(right[right_idx]) right_idx += 1 # If there's uncompared values in right list, add the uncompaed values into combined while right_idx < len(right): combined.append(right[right_idx]) right_idx += 1 # if there's uncompared values values in left list, add the uncompared values into combined while left_idx < len(left): combined.append(left[left_idx]) left_idx += 1 return combined #''' arr = [6, 5, 7, 5, 8, 43, 9, 4, 8, 9, 12] result = merge_sort(arr, lambda left, right: left > right) # left > right descending print(result) result = merge_sort(arr, lambda left, right: left < right) # left < right ascending print(result) #'''
true
93a83fcfd32fe85193cbc98707f5d8dc66ace4d9
lastbyte/dsa-python
/problems/easy/square_root.py
967
4.1875
4
''' 69. Sqrt(x) Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. Example 1: Input: x = 4 Output: 2 Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. Constraints: 0 <= x <= 231 - 1 link -> https://leetcode.com/problems/sqrtx/ ''' class Solution: def mySqrt(self, x: int) -> int: if x == 0 or x == 1: return x; ans = 1; for i in range(1, x//2+1): if i*i <= x: ans = i else: break return ans if __name__ == "__main__": solution = Solution() result = solution.mySqrt1(4) print(result)
true
3d46ad9e5bf15a187f1c7fef9c3f04b550cc3c58
lastbyte/dsa-python
/problems/medium/duplicate_number.py
950
4.125
4
''' Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. Example 1: Input: nums = [1,3,4,2,2] Output: 2 Example 2: Input: nums = [3,1,3,4,2] Output: 3 Example 3: Input: nums = [1,1] Output: 1 Example 4: Input: nums = [1,1,2] Output: 1 Constraints: 2 <= n <= 105 nums.length == n + 1 1 <= nums[i] <= n All the integers in nums appear only once except for precisely one integer which appears two or more times. link -> https://leetcode.com/problems/find-the-duplicate-number/ ''' def find_duplicate(nums): for i in range(len(nums)): index = abs(nums[i]) if nums[index] < 0: return index else: nums[index] = -nums[index] return -1 if __name__ =="__main__": nums = [1, 1, 2] result = find_duplicate(nums) print(result)
true
5bc257f8a71d3b297bb6174ef5e758be4cfa25b1
SamuelKelechi/My_First_Python_Calculator
/calc.py
1,656
4.125
4
# A simple Calculator Program Designed By Samuel, A Product of BrighterDays Codelab # This function will add two numbers def add(a, b): return a + b # This function will subtract two numbers def sub(a, b): return a - b # This function will multiply two numbers def mul(a, b): return a * b # This function will divide two numbers def div(a, b): return a / b # A Welcome Display to the Screen print("Welcome to Samuel's Program") # This allows User to Input his/her name name = input("Please Input Your Name:") # This Prints Out Welcome and the name of the user as inputed print("Welcome", name) # This Show Options that the user can pick from print("Select Operator Choice") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # This will take input from the User choice = input("Enter Operator Choice (1/2/3/4): ") #This will check if Choice is one of the four options if choice in (1, 2, 3, 4): FirstNumber = float(input("Enter First Number: ")) SecondNumber = float(input("Enter First Number: ")) if choice == 1: print(FirstNumber, "+" , SecondNumber, "=", add(FirstNumber, SecondNumber)) elif choice == 2: print(FirstNumber, "-", SecondNumber, "=", sub(FirstNumber, SecondNumber)) elif choice == 3: print(FirstNumber, "*", SecondNumber, "=", mul(FirstNumber, SecondNumber)) elif choice == 4: print(FirstNumber, "/", SecondNumber, "=", div(FirstNumber, SecondNumber)) else: print("Invalid Selection")
true
1663882dd777611609d05eaa588123d377ef7ce0
philippzhang/leetcodeLearnPython
/leetcode/lc0284/PeekingIterator.py
754
4.1875
4
class PeekingIterator(object): def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.iter = iterator self.val = self.iter.next() self.hasnext = True def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int """ return self.val def next(self): """ :rtype: int """ ans = self.val if self.iter.hasNext(): self.val = self.iter.next() else: self.hasnext = False return ans def hasNext(self): """ :rtype: bool """ return self.hasnext
false
839bb0fdcdaebf2954f4672c0b62f54d3804ac7b
spacetime314/python3_ios
/extraPackages/matplotlib-3.0.2/examples/ticks_and_spines/major_minor_demo.py
2,677
4.3125
4
""" ================ Major Minor Demo ================ Demonstrate how to use major and minor tickers. The two relevant userland classes are Locators and Formatters. Locators determine where the ticks are and formatters control the formatting of ticks. Minor ticks are off by default (NullLocator and NullFormatter). You can turn minor ticks on w/o labels by setting the minor locator. You can also turn labeling on for the minor ticker by setting the minor formatter Make a plot with major ticks that are multiples of 20 and minor ticks that are multiples of 5. Label major ticks with %d formatting but don't label minor ticks The MultipleLocator ticker class is used to place ticks on multiples of some base. The FormatStrFormatter uses a string format string (e.g., '%d' or '%1.2f' or '%1.1f cm' ) to format the tick The pyplot interface grid command changes the grid settings of the major ticks of the y and y axis together. If you want to control the grid of the minor ticks for a given axis, use for example ax.xaxis.grid(True, which='minor') Note, you should not use the same locator between different Axis because the locator stores references to the Axis data and view limits """ import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) majorLocator = MultipleLocator(20) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(5) t = np.arange(0.0, 100.0, 0.1) s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01) fig, ax = plt.subplots() ax.plot(t, s) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) # for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) plt.show() ############################################################################### # Automatic tick selection for major and minor ticks. # # Use interactive pan and zoom to see how the tick intervals # change. There will be either 4 or 5 minor tick intervals # per major interval, depending on the major interval. # # One can supply an argument to AutoMinorLocator to # specify a fixed number of minor intervals per major interval, e.g.: # minorLocator = AutoMinorLocator(2) # would lead to a single minor tick between major ticks. minorLocator = AutoMinorLocator() t = np.arange(0.0, 100.0, 0.01) s = np.sin(2 * np.pi * t) * np.exp(-t * 0.01) fig, ax = plt.subplots() ax.plot(t, s) ax.xaxis.set_minor_locator(minorLocator) ax.tick_params(which='both', width=2) ax.tick_params(which='major', length=7) ax.tick_params(which='minor', length=4, color='r') plt.show()
true
f7d45210da3224eabc6a14b690d8eeb7b1abd9b0
spacetime314/python3_ios
/extraPackages/matplotlib-3.0.2/examples/mplot3d/polys3d.py
1,696
4.125
4
""" ============================================= Generate polygons to fill under 3D line graph ============================================= Demonstrate how to create polygons which fill the space under a line graph. In this example polygons are semi-transparent, creating a sort of 'jagged stained glass' effect. """ # This import registers the 3D projection, but is otherwise unused. from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from matplotlib.collections import PolyCollection import matplotlib.pyplot as plt from matplotlib import colors as mcolors import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) def cc(arg): ''' Shorthand to convert 'named' colors to rgba format at 60% opacity. ''' return mcolors.to_rgba(arg, alpha=0.6) def polygon_under_graph(xlist, ylist): ''' Construct the vertex list which defines the polygon filling the space under the (xlist, ylist) line graph. Assumes the xs are in ascending order. ''' return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)] fig = plt.figure() ax = fig.gca(projection='3d') # Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i verts = [] # Set up the x sequence xs = np.linspace(0., 10., 26) # The ith polygon will appear on the plane y = zs[i] zs = range(4) for i in zs: ys = np.random.rand(len(xs)) verts.append(polygon_under_graph(xs, ys)) poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')]) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim(0, 10) ax.set_ylim(-1, 4) ax.set_zlim(0, 1) plt.show()
true
45c1fcf62ecb2e1a1c1fca798373f537ea217eea
spacetime314/python3_ios
/extraPackages/matplotlib-3.0.2/examples/pyplots/annotation_basic.py
947
4.21875
4
""" ================= Annotating a plot ================= This example shows how to annotate a plot with an arrow pointing to provided coordinates. We modify the defaults of the arrow, to "shrink" it. For a complete overview of the annotation capabilities, also see the :doc:`annotation tutorial</tutorials/text/annotations>`. """ import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) ax.set_ylim(-2, 2) plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.axes.Axes.annotate matplotlib.pyplot.annotate
true
7cc9f9191275137a2f96164977cf17db7eec7d0f
mmattano/example_repo
/example_repo/linreg.py
1,848
4.46875
4
"""Example module.""" __all__ = ["LinearRegression"] import numpy as np class LinearRegression: """Linear Regression. Uses matrix multiplication to fit a linear model that minimizes the mean square error of a linear equation system. Examples -------- >>> import numpy as np >>> from example_repo import LinearRegression >>> rng = np.random.RandomState(0) >>> n = 100 >>> x = rng.uniform(-5, 5, n) >>> y = 2*x + 1 + rng.normal(0, 1, n) >>> linreg = LinearRegression().fit(x, y) >>> linreg.predict(range(5)).T array([[1.19061859, 3.18431209, 5.17800559, 7.17169909, 9.1653926 ]]) """ def __init__(self): self._beta = None def _2mat(self, arr): # Returns input as matrix with ones in first column return np.insert(self._2vec(arr), 0, 1, axis=1) def _2vec(self, arr): # Returns input as vector return np.ravel(arr)[:, None] def fit(self, x, y): """Fit linear model. Parameters ---------- x : array-like Features y : array-like Labels Returns ------- same type as caller """ X = self._2mat(x) Y = self._2vec(y) self._beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y) return self def predict(self, x): """Predicts using the linear model. Parameters ---------- x : array-like Samples Returns ------- numpy.ndarray Predicted values See Also -------- fit Raises ------ Exception If the model has not been fitted """ if self._beta is None: raise Exception("Fit the model first.") return self._2mat(x).dot(self._beta)
true
c852c9b76434a825abd0564d4238e37720ac5360
heronsilva/udacity-unscramble-cs-problems
/Task4.py
1,427
4.21875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ callers = [] called = [] texters = [] texted = [] for call in calls: incoming_call_number = call[0] receiving_call_number = call[1] if incoming_call_number not in callers: callers.append(incoming_call_number) called.append(receiving_call_number) for text in texts: incoming_text_number = text[0] receiving_text_number = text[1] texters.append(incoming_text_number) texted.append(receiving_text_number) for phone_number in callers[:]: if phone_number in called or phone_number in texters or phone_number in texted: callers.remove(phone_number) possible_telemarketers = sorted(callers) print("These numbers could be telemarketers:", *possible_telemarketers, sep="\n")
true
3c4813856d32ecd0aeb72075f7cbe93624d06a3b
CheolminConanShin/PythonTakeNote
/Day1/src/Day1/PassVSContinue.py
249
4.28125
4
list = [1,2,3,4,5,6,7] for item in list: print("inside for loop : " + str(item)) if item > 3: pass print("inside if statement : " + str(item)) # pass if ȿִ ó skip, continue for skip
true
a4ee30d6f29af76459338db82a548ece62994d27
nellybella/ICodeAI
/Set_adt.py
2,683
4.5625
5
class Set: """ implementation of the set ADT using lists """ def __init__(self): """ initialize the set adt """ self.set_ = [] def add_item(self,item): """ add an element to the set Algorithmic complexity: Constant time: O(1) """ def remove_item(self): """ removes an element form the set Returns: The element popped Algorithmic complexity: Constant time: O(1) """ return self.set_.pop() def contains (self,item): """ checks if an element is in the set Returns: True if the item is in the set Algorithmic complexity: Linear time: O(n) """ for i in self.set_: if i == item: return 'The item is in the set' def set_union(self,set2): """ finds the union between two sets Returns: The items in both sets Algorithmic complexity: Constant time: O(1) """ for i in set2: if i not in self.set_: self.set_.append(i) return self.set_ def set_intersection(self,set2): """ checks the intersection between two sets Returns: Items that are in both sets Algorithmic complexity: O(len(s) * len(t)) """ intersection_set = [] for i in set2: if i in self.set_: intersection_set.append(i) return intersection_set def symmetric_diffrence(self,set2): """ finds the symmetric diffrence between two sets Returns: the diffrenece between the union and intersection of the two sets Algorithmic complexity: Constant time: O(1) """ union_ = self.set_union(set2) intersection_ = self.set_intersection(set2) symmetric_ = [] for i in union_ and i not in intersection: symmetric_.append(i) def set_subset(self,set2): """ checks if a set is the subset of another set Returns: True if it is or false otherwise Algorithmic complexity: Constant time: O(1) """ my_intersection = self.set_intersection(set2) if len(my_intersection) ==len(set2): return True else: return False
true
889c0c0a5a954098078a1353f872dfcb800d5faa
oa0311/NetworkChuck-Python-Tutorial
/main.py
556
4.28125
4
#printing single strings with several print functions. #print("Hello there!!!") #print("I am Iron Man") #print("No, I am Tony Stark") #print("No, blah blah") #Pound sign is how you comment in Python. #This comment is just to test the Version Control #printing a Multiline string with one print function. #print("""I'm Iron Man #No, I am Tony Stark #No, I am Thanos!""") #printing multiple strings with a single print function. #print("I am Iron Man. \n" + "No, I am Iron Man. \n" + "Whateve...") #printing the same string multiple times print("I am Batman\n" * 11)
true
e78aea815a8195d1016d64bea3bc4e6c93e279ee
mshehan/pythonPractice
/MatthewShehanLab3.py
2,637
4.25
4
#################################################################### # CIS 117 Internet Programming # Lab #3: "Super Secret Password" #################################################################### # This program checks to see if a user provided password # is super secret enough. # a password is considered super secret if: # 1) the password is at least 8 char long # 2) the password has one uppercase and one lowercase char # 3) the password has at least one digit # else the program prompts the user to re-enter # until the password becomes super secret enough #################################################################### PASS_LEN = 8 def is_Password(word): isUpperCase = False isLowerCase = False isDigit = False for i in range(len(word)): if word[i].isupper(): isUpperCase = True elif word[i].islower(): isLowerCase = True elif word[i].isdigit(): isDigit = True if (isUpperCase and isLowerCase and isDigit and (len(word) >= PASS_LEN)): return True else: return False def main(): password1 = input("Please enter a new super secret password: ") password2 = input("Please re-enter the password: ") while(not is_Password(password1) or password1 != password2): if(password1 != password2): print("\nthe two passwords do not match\n") elif(not is_Password(password1)): print("\nThe password is not super secret enough\n") password1 = input("Please enter a new super secret password: ") password2 = input("Please re-enter the password: ") print("good job, that password word is super secret") main() ########################################################################## #------ #RUN #------ # #Please enter a new super secret password: passwor #Please re-enter the password: passwor # #The password is not super secret enough # #Please enter a new super secret password: nouppercase1 #Please re-enter the password: nouppercase1 # #The password is not super secret enough # #Please enter a new super secret password: NOLOWER1 #Please re-enter the password: NOLOWER1 # #The password is not super secret enough # #Please enter a new super secret password: 12345678 #Please re-enter the password: 12345678 # #The password is not super secret enough # #Please enter a new super secret password: notmatching #Please re-enter the password: nope # #the two passwords do not match # #Please enter a new super secret password: yesthisWorks1 #Please re-enter the password: yesthisWorks1 #good job, that password word is super secret ##########################################################################
true
ef1d339722bc8734a041ba7337930aeeb4756844
Richardbmk/PythonFundamentals
/sqlite/friends2_SQL.py
451
4.21875
4
# 364. Selecting With Python import sqlite3 conn = sqlite3.connect("my_friends.db") # Create cursor object c = conn.cursor() #c.execute("SELECT * FROM friends") #c.execute("SELECT * FROM friends WHERE first_name IS 'Steve'") c.execute("SELECT * FROM friends WHERE closeness > 5 ORDER BY closeness") #for result in c: # print(result) #print(c.fetchall()) #print(c.fetchone()) print(c.fetchall()) # commit changes conn.commit() conn.close()
true
be06ce5c3dff120a3df341c463c0bcfc8f62a7be
Richardbmk/PythonFundamentals
/09dictionaries.py
2,984
4.28125
4
# Dictionaries in python instructor = { "name": "Colt", "owns_dog": True, "num_courses": 4, "favorite_language": "Python", "is_hilarious": False, 44: "my favorite number!" } cat = {"name": "blue", "age": 3.5, "isCute": True} # A combination of a list and Dictionaries cart = [{"name": "blue", "age": 3.5, "isCute": True}] # Dict cat2 = dict(name = "Richard") cat2 = dict(name = "Richard", age="5") # Accessing Individual Values instructor["name"] #"Colt" instructor["owns_dog"] #True # Acces all values in a Dictionaries instructor.values() for v in instructor.values(): print(v) # Acces all keys in a Dictionaries instructor.keys() for v in instructor.keys(): print(v) # Acces all keys and values in a Dictionaries instructor.items() for k,v in instructor.items(): print(f"key is {k} and value is {v}") # Does a dictionary have a key? "name" in instructor # True "awesome" in instructor # False # Does a dictionary have a value? "Colt" in instructor.values() # True "Nope!" in instructor.values() # False # Dictionary Mecthods # Method clear d = dict(a=1,b=2,c=3) d.clear() d # {} #Method copy d = dict(a=1,b=2,c=3) c = d.copy() c # {'a': 1, 'b': 2, 'c': 3} c is d # False c == d # True # Method fromkeys {}.fromkeys("a","b") # {'a': 'b'} {}.fromkeys(["email"], 'unknown') # {'email': 'unknown'} {}.fromkeys("a",[1,2,3,4,5]) # {'a': [1, 2, 3, 4, 5]} {}.fromkeys("phone", "unknown") # {'p': 'unknown', 'h': 'unknown', 'o': 'unknown', 'n': 'unknown', 'e': 'unknown'} new_user = {}.fromkeys([]) new_user.fromkeys(range(1,10), "unknown") # Method Get d = dict(a=1,b=2,c=3) d['a'] # 1 d.get('a') # 1 d['b'] # 2 d.get('b') # 2 d['no_key'] # KeyError d.get('no_key') # None # Method pop: d = dict(a=1,b=2,c=3) d.pop() # TypeError: pop expected at least 1 arguments, got 0 d.pop('a') # 1 d # {'c': 3, 'b': 2} d.pop('e') # KeyError # Method popitem() d = dict(a=1,b=2,c=3,d=4,e=5) d.popitem() # ('d', 4) d.popitem('a') # TypeError: popitem() takes no arguments (1 given) #Method update instructor person = {"City": "Antigua"} person.update(instructor) person["name"] = "Evelia" person.update(instructor) # Dictionary Comprehension # {__:__for__in__} numbers = dict(first=1, second=2, third=3) squared_numbers = {key: value ** 2 for key,value in numbers.items()} print(squared_numbers) # {'first': 1, 'second': 4, 'third': 9} {num: num**2 for num in [1,2,3,4,5]} str1 = "ABC" str2 = "123" combo = {str1[i]: str2[i] for i in range(0,len(str1))} print(combo) # # {'A': '1', 'B': '2', 'C': '3'} instructor yelling_instructor = {k.upper(): v.upper() for k,v in instructor.items()} yelling_instructor = {(k.upper() if k is "color" else k): v.upper() for k,v in instructor.items()} # Conditional logic of Dictionary Comprehension num_list = [1,2,3,4] { num:("even" if num % 2 == 0 else "odd") for num in num_list } # {1: 'odd', 2: 'even', 3: 'odd', 4: 'even'} { num:("even" if num % 2 == 0 else "odd") for num in range(1,100) }
true
cfc3471428d81b3068444730ef162e7e491fb46f
IsaacStalley/Course_Open_Platforms
/laboratorio5.py
2,674
4.125
4
#!/usr/bin/python3 """ Created on Friday July 10 10:19:04 2020 @author: Isaac Stalley Matriz class, takes 2 parameters for rows and columns and creates a matrix, contains useful methods for modifying the matrices, like adding and subtracting them or printing them. """ class Matriz(): # Constructor method, takes in the row and column parameters to create a # matrix instance. def __init__(self, n, m): try: self.n = n self.m = m self.matriz = [] for i in range(n): self.matriz.append([]) for x in range(m): self.matriz[i].append(0) except TypeError: print("Parametros deben ser numeros enteros.") # Modified __str__ method to return a string for this object type. def __str__(self): string = "" for i in self.matriz: for x in i: string = string + str(x) string = string + "\n" return string[:-1] # Get method, used to get the coordinate of the matrix instance. def get(self, f, c): try: return self.matriz[f][c] except TypeError: print("Parametros deben ser numeros enteros.") except IndexError: print("Coordenada inexistente.") # Set method, used to set the value at the coordinate of the matrix # instance to some value n. def set(self, f, c, n): try: self.matriz[f][c] = n except TypeError: print("Parametros deben ser numeros enteros.") except IndexError: print("Coordenada inexistente.") # Modified __add__ method so that this object type can be added. def __add__(self, other): if (self.n == other.n and self.m == other.m): temp = Matriz(self.n, self.m) for i in range(len(self.matriz)): for x in range(len(self.matriz[i])): temp.matriz[i][x] = self.matriz[i][x] + other.matriz[i][x] return temp else: print("Matrices deben tener las mismas dimensiones.") # Modified __sub__ method so that this object type can be subtracted. def __sub__(self): if (self.n == other.n and self.m == other.m): temp = Matriz(self.n, self.m) for i in range(len(self.matriz)): for x in range(len(self.matriz[i])): temp.matriz[i][x] = self.matriz[i][x] - other.matriz[i][x] return temp else: print("Matrices deben tener las mismas dimensiones.")
true
367c4bb8d8804e38efcbf13d208f90e13d21d879
PyQIT/Python-Distance-Converter
/Converter.py
2,315
4.28125
4
# Author Przemysław Pyk # Maracui # 25.09.2018 def milesToKilometersConverter(): print("Write distance in miles: ") miles = float(input()) distanceInKilometers = miles * 1.609344 print("Your distance in kilometers is equal ", distanceInKilometers) def kilometersToMilesConverter(): print("Write distance in kilometers: ") kilometers = float(input()) distanceInMiles = kilometers * 0.621371192 print("Your distance in miles is equal ", distanceInMiles) def kilometersToFeetConverter(): print("Write distance in kilometers: ") kilometers = float(input()) distanceInFeet = kilometers * 3280.8399 print("Your distance in feet is equal ", distanceInFeet) def feetToKilometersConverter(): print("Write distance in feet: ") feet = float(input()) distanceInKilometers = feet * 0.0003048 print("Your distance in kilometers is equal ", distanceInKilometers) def natuicalMilesToKilometersConverter(): print("Write distance in natuical miles: ") nauticalmiles = float(input()) distanceInKilometers = nauticalmiles * 1.85200 print("Your distance in kilometers is equal ", distanceInKilometers) def kilometersToNauticalMilesConverter(): print("Write distance in kilometers: ") kilometers = float(input()) distanceInNauticalMiles = kilometers * 0.539956803 print("Your distance in nautical miles is equal ", distanceInNauticalMiles) print("Welcome in Python Distance Converter") while True: print("\n1. Convert miles to kilometers") print("2. Convert kilometers to miles") print("3. Convert feet to kilometers") print("4. Convert kilometers to feet") print("5. Convert nautical miles to kilometers") print("6. Convert kilometers to nautical miles") print("7. Exit") userDecision = int(input()) if userDecision == 1: milesToKilometersConverter() elif userDecision == 2: kilometersToMilesConverter() elif userDecision == 3: feetToKilometersConverter() elif userDecision == 4: kilometersToFeetConverter() elif userDecision == 5: natuicalMilesToKilometersConverter() elif userDecision == 6: kilometersToNauticalMilesConverter() elif userDecision == 7: exit() else: print("Wrong number has been written")
false
7a16a32c9b73fe4733b1e44255904fb6aacb7937
pranavv1251/python-programs
/Prac3/P33.py
222
4.3125
4
list1 = [] largest = '' line = input("Enter words:") while(line != ''): if(len(largest) <= len(line)): largest = line line = input() print(f'The largest word is {largest} and its length is {len(largest)}')
true
fb1a65926ab7532c0776af46ed234e868420b86a
gopi-123/Speech_To_Text
/convert_audio_mp3_file_to_text.py
912
4.15625
4
""" Audio transcription works by a few steps: input: .mp3 file output: .wav file ++ text recognized ouput How it works: first converts mp3 to wav conversion, loading the audio file, feeding the audio file to a speech recongition system """ import speech_recognition as sr from os import path from pydub import AudioSegment # convert mp3 file to wav mp3_filename = "test_1.mp3" sound = AudioSegment.from_mp3(mp3_filename) sound.export("transcript.wav", format="wav") # transcribe audio file AUDIO_FILE = "transcript.wav" # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # read the entire audio file print("Transcription: " + r.recognize_google(audio))
true
ab3f0f0ff62d8bd50d79e0ffcde2beca51e477e9
alyslma/HackerRank
/Python/Strings/SwapCase.py
841
4.3125
4
# https://www.hackerrank.com/challenges/swap-case/problem # You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. # Examples: Www.HackerRank.com → wWW.hACKERrANK.COM || Pythonist 2 → pYTHONIST 2 ################################################################ # Using the swapcase() function def swap_case(s): return s.swapcase() if __name__ == '__main__': s = input() result = swap_case(s) print(result) # Not using the swapcase() function def swap_case(s): result = "" for letter in s: if letter == letter.upper(): result += letter.lower() else: result += letter.upper() return result if __name__ == '__main__': s = input() result = swap_case(s) print(result)
true
77e61338c8b2849a671112c1ee59e03b303fae63
imckl/leetcode
/easy/263-ugly-number.py
724
4.25
4
# Write a program to check whether a given number is an ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # https://leetcode.com/problems/ugly-number/ class Solution(object): def isUgly(self, num: int) -> bool: if num == 0: return False if num == 1: return True if num % 2 and num % 3 and num % 5: return False while not num % 2 or not num % 3 or not num % 5: if not num % 2: num //= 2 if not num % 3: num //= 3 if not num % 5: num //= 5 if num == 1: return True else: return False
true
c594a9615ed48036d5cf76d83d151f56aae70f19
imckl/leetcode
/easy/58-length-of-last-word.py
621
4.25
4
# 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 # # 如果不存在最后一个单词,请返回 0 。 # # 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/length-of-last-word # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Solution: def lengthOfLastWord(self, s: str) -> int: try: return len(s.split()[-1]) except IndexError: return 0
false
7b3fd8bb8a7002bb4802f813a8c1e4fe976e64ca
karthikm999/python_101
/ex21.py
1,026
4.4375
4
# Python program to find the largest number among the three input numbers # change the values of num1, num2 and num3 # for a different result num1 = 10 num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is:",largest) #output: Enter first number: 45 Enter second number: 36 Enter third number: 89 The largest number between is: 89.0 LCD x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1,2,3] y3 = [1,2,3] print(x1 is not y1) # Output: False print(x2 is y2) # Output: True print(x3 is y3) # Output: False Membership operator x = 'Hello world' y = {1:'a',2:'b'} print('H' in x) # Output: True print('hello' not in x) # Output: True print(1 in y) # Output: True print('a' in y) # Output: False
true
0ff1ba5fe60d9f7c578f8f2b4aaecc313eea190f
VicArDAl/python-labs
/03_more_datatypes/2_lists/03_11_split.py
514
4.15625
4
''' Write a script that takes in a string from the user. Using the split() method, create a list of all the words in the string and print the word with the most occurrences. ''' script=str(input("type a script please: ")) script_split=script.split() print(script_split) bigger_amount=0 solution=[] for i in script_split: amount=script_split.count(i) if amount>=bigger_amount: bigger_amount=amount palabra=i print(i) print(amount) print("solucion") print(palabra,bigger_amount)
true
c852938281a5be533f6586233a236829987e4835
VicArDAl/python-labs
/02_basic_datatypes/2_strings/02_08_occurrence.py
317
4.15625
4
''' Write a script that takes a string of words and a letter from the user. Find the index of first occurrence of the letter in the string. For example: String input: hello world Letter input: o Result: 4 ''' string=str(input("Write a script:\n")) letter=str(input("letter to find:\n")) print(string.find(letter))
true
7ec3728efe5497597f628dd87260a4428a2557c1
VicArDAl/python-labs
/01_python_fundamentals/01_01_run_it.py
959
4.5625
5
''' 1 - Write and execute a script that prints "hello world" to the console. 2 - Using the interpreter, print "hello world!" to the console. 3 - Explore the interpreter. a - Execute lines with syntax error and see what the response is. * What happens if you leave out a quotation or parentheses? * How helpful are the error messages? b- Use the help() function to explore what you can do with the interpreter. For example execute help('print'). press q to exit. c- Use the interpreter to perform simple math. d- Calculate how many seconds are in a year. ''' #1 print("hello world") #3.a # leave out parenthesis # print(hello world) # When I run the program, it says that there is a SytaxError # It's very helpful because it shows in which line is the problem #3.b #Shows a description of what the command does. help(print) #3.c 5+4 print(5+4) #3.d sec = 60 min=60 hour=24 day=365 year=sec*min*hour*365 print(year)
true
7a09cbb56692751dfcbc007cc84141193cedb2a8
HenriqueSaKi/Python-Fundamentos-Para-Analise-De-Dados
/Lab/calculadora_v1.py
866
4.1875
4
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! print("\n******************* Python Calculator *******************") # Funções da Calculadora soma = lambda a, b : a + b subtracao = lambda a, b : a - b multiplicacao = lambda a, b : a * b divisao = lambda a, b : a / b resultado = 0 operacao = input("Digite a operacao que deseja realizar.\nO formato deve seguir o padrão apresentado a seguir: 'a + b'\nEntrada: ") operacao.split(" ") a = int(operacao[0]) b = int(operacao[4]) if(operacao[2] == "+"): print(soma(a, b)) elif(operacao[2] == "-"): print(subtracao(a, b)) elif(operacao[2] == "*"): print(multiplicacao(a, b)) elif(operacao[2] == "/"): print(divisao(a, b))
false
d283c5db3961b3978c9c098ce5fbfe2a5a268dd3
Jokertion/Learn-Python-the-Hard-Way
/ex33-5.py
277
4.125
4
i = 0 numbers = [] maxium = int(input("请输入列表最大值: ")) step = int(input("请定义数字间隔(范围1-10): ")) for loop in range(0, maxium, step): numbers.append(i) i = i + step print ("The numbers: ") for num in numbers: print (num)
false
cb4c7047893f4165a75c1337931e95f6cca11b35
savirnosaj/codingDojo
/python_stack/Python/python_OOP/car.py
1,455
4.21875
4
# Assignment: Car # Create a class called Car. In the __init__(), allow the user to specify the following attributes: price, speed, fuel, mileage. # If the price is greater than 10,000, set the tax to be 15%. Otherwise, set the tax to be 12%. # Create six different instances of the class Car. In the class have a method called display_all() that returns all the information about the car as a string. # In your __init__(), call this display_all() method to display information about the car once the attributes have been defined. class Car: def __init__(self, price, speed, fuel, mileage): self.variable_to_store_price = price self.variable_to_store_speed = speed self.variable_to_store_fuel = fuel self.variable_to_store_mileage = mileage self.tax = 0.12 if self.variable_to_store_price > 10000: self.tax = 0.15 Car.display_all(self) def display_all(self): print("*"*30) print(f"Price: ${self.variable_to_store_price}") print(f"Speed: {self.variable_to_store_speed}mph") print(f"Fuel: {self.variable_to_store_fuel}") print(f"Milage: {self.variable_to_store_mileage}mpg") print(f"Tax: {self.tax}") car_1 = Car(2000, 35, "Full", 15) car_2 = Car(2000, 5, "Not Full", 105) car_3 = Car(2000, 15, "Kind of Full", 95) car_4 = Car(2000, 25, "Full", 25) car_5 = Car(2000, 45, "Empty", 25) car_6 = Car(20000000, 35, "Empty", 15)
true
2f2324f5026319012a5e608cc1343c9afa109a2c
dipesh1011/class6_functions
/combination.py
331
4.125
4
def factorial(num): res = 1 for i in range(1, num + 1): res = res * i return res def combination(): n = int(input("Enter value for 'n':")) r = int(input("Enter value for 'r':")) combi = factorial(n) / (factorial(r) * factorial(n-r)) print("The combination is:",combi) combination()
true
0bb2d79bdf58353a16f346aff38be8afefee9815
pyav/labs
/src/python/nested_dictionary.py
946
4.625
5
#!/usr/bin/env python ''' Following program demonstrates nested dictionary access techniques. Output (python nested_dictionary.py) ------ {'Second': {'Second_1': 'Second_1_1', 'Second_2': 'Second_2_1'}, 'First': {'First_1': 'First_1_1', 'First_2': 'First_2_1'}} First_2_1 First_1_1 Second_2_1 __author__ = "pyav" ''' # Define dictionary a = { "First": { "First_1": "First_1_1", "First_2": "First_2_1" }, "Second": { "Second_1": "Second_1_1", "Second_2": "Second_2_1" } } ''' The above nested dictionary members can be accessed as follows: 1. a 2. a.get("server1").get("action1_2") 3. a.get("server1")["action1_1"] 4. a["server2"]["action2_2"] ''' # Access members print a print a.get("First").get("First_2") print a.get("First")["First_1"] print a["Second"]["Second_2"]
false
717bca05b8a8d2018645de701f06918e166c9a41
viicrow/yes_no
/main.py
1,136
4.15625
4
# functions go here... def yes_no(question): valid = False while not valid: response = input(question).lower() if display_instructions == "yes" or display_instructions == "y": response = "yes" return response elif display_instructions == "no" or display_instructions == "n": response = "no" return response else: print("Please answer yes / no") def instructions(): print("**** how to Play ****") print() print("The rules of the game go here") print() return "" # main routine goes here... played_before = yes_no("have you played the " "game before") print("you chose {}".format(display_instructions)): print() having_fun = yes_no("are you having fun? ") print("you said {} to having fun".format(having_fun)) display_instructions = "" while display_instructions.lower() != "xxx": # ask the user if they have played before display_instructions = input("have you played this game" "before?").lower() # If they say yes, output 'program continues' # If they say no, output 'display instructions' # If the answer is invalid, print an error.
true
efc3651e5beee8826f1307db4c171f096bdb6fe6
mooney79/python-number-guessing-game
/leveltwo.py
495
4.21875
4
from random import randint lucky_number = input('Enter the number for the computer to guess: ') guesses_remaining = 3 while guesses_remaining > 0: computer_guess = randint(1, 10) if computer_guess == int(lucky_number): print("Correct! The computer wins!") break elif computer_guess > int(lucky_number): print("Too high!") guesses_remaining = guesses_remaining -1 else: print("Too low") guesses_remaining = guesses_remaining -1
true
691c501f6686e05d6f053e1b28a5591bb70e5b6a
AJHudson2003/the-final-project
/final project.py/the-final-project.py
2,427
4.15625
4
''' AJ Hudson 3.7.19 This is a questions game that i am using for this fun questions game. this will ask five random questions for you to answer. This will be a few questions that will have a few different questions for you to answer. I hope that you will have ''' welcome = input('Welcome to the Questions game!') def welcome(): print("") # this will ask your name so they components will be able to identify the person taking the servey. print('question number one') print('') name = input("What is your name: ") def greeting(): print(" hi there " + name + "!") print("nice to meet you") greeting() print('') print('questions two!') print('') # This will ask the user to enter a few numbers for their test to answer and then it will round it for them. total = 0 how_many_tests = int(input("How many test would you like to average today: ")) print("") for i in range(how_many_tests): score = float(input("enter score for tests: ")) total = total + score average = total / how_many_tests print("") print("average: " + str(round(average, 2))) print(average) print('question three lets have some more fun.') print('') # This will ask the user that they will have to enter a quad size that they will need to be able to ride. # This will ask about your quad size for you to ride. while True: quad_size_frame=int(input("enter a size of quad frame you need.")) if quad_size_frame <= 30: print('that size is to small') elif quad_size_frame >= 145: print('that quad size is way still to big') elif quad_size_frame >= 95: print('that quad size is to big.') else: quad_size_frame >= 60 print('that quad size is the right size!') break print('questions four') print('') # this will ask for some numbers that they put in and add them together for them so they don't have to. sum = 0 for i in range(10): enter_a_number=int(input('enter a few numbers: ')) sum = sum + enter_a_number print('') print('the sum of all your numbers is ' + str(sum)) print('question five') print('') print("we are going to print a set of two numbers") # this will have the user input to print out the numbers that they put in. def two_numbers(a, c = 20): print('first number: ', a) print('second number: ', c) two_numbers(3, 79) two_numbers(30) print('') print('thanks for playing my game') print('i am glad you played my game it means a lot to me!')
true
528a6d078a64137c9f5d10bc97b78be7459c38b5
AHecky3/Arthas
/Chapter4_Challenge/Challenge_1.py
1,008
4.15625
4
""" 1) Write a program that counts for the user. Let the user enter the starting number, then ending number, and the amount by wich to count. """ #Andrew Hecky #10/23/2014 #Opening Regards print(""" Hello There! I will count for you! Please enter the number you wish to start at, end at, and what we will be counting by. """) #Getting Info From User while True : try: startingNum = int(input("Starting Number: ")) break except ValueError: print("Please enter a valid input. \n") while True : try: endingNum = int(input("Ending Number: ")) break except ValueError: print("Please enter a valid input. \n") while True : try: countBy = int(input("Count By: ")) break except ValueError: print("Please enter a valid input. \n") #Counting Loop for i in range (startingNum,endingNum+1,countBy): print(i) for i in reversed(range(endingNum,startingNum+1,countBy)): print(i)
true
500901f608d092467c08aa375f8215a5a16a68c5
clebertonf/Python-course
/001-Python-basico/028-desempacotamento.py
459
4.15625
4
# Desempacotamento em python list_names = ["Cleber", "Lucas", "Maria", "Paulo", "Carlos", "João"] nome_1, nome_2, *resto = list_names print(resto) # recebe um array com os valores restantes da lista list_ages = [18, 27, 35] age_1, age_2, age_3 = list_ages print(age_2) list_numbers = [1, 5, 8, 12, 10] # Apos o *restante, se eu buscar algum numero começara de forma decrescente n1, n2, *restante, ultimo_numero = list_numbers print(ultimo_numero)
false
1c0cf5c29e9b454d9201bac8ee8a34d8b916e7c9
clebertonf/Python-course
/001-Python-basico/008-desafio-pratico.py
512
4.125
4
from datetime import date year_current_date = date.today().year def get_info(name, age, height, weight): year_birth = year_current_date - age imc = round(weight / (height ** 2), 2) print(f"{name} tem {age} anos, {height} de altura e pesa {weight} KG.") print(f"O IMC do {name} é: {imc}") print(f"{name} nasceu em {year_birth}") get_info("Cleberton", 28, 1.69, 75) # Função recebe algumas informaçoes por parametro, e retorna ano de nascimento, imc # com algumas frases customizadas
false
8059fafca80a43306a4a2ba4eda90c027e83c9d7
clebertonf/Python-course
/001-Python-basico/017-formatando-valores.py
950
4.1875
4
# Formatando valores com modificadores """ :s - Strings :d - Int :f - Float :. - Quantidade de casas decimais Float : - Caractere (> ou < ou ^) (Quantidade) (Tipo s, d ou f) > esquerda < direita ^ centro """ # exemplo do uso da formatação :. (:f :d) numero_1 = 10 numero_2 = 3 divisao = numero_1 / numero_2 print(f'Divisão formatada em duas casas decimais {divisao:.2f}') print(f'Divisão formatada em duas casas decimais {numero_1:d}') # exemplo :s nome = 'Cleber' print(f'Ola mundo! {nome:s}') # Caractere (> ou < ou ^) (Quantidade) (Tipo s, d ou f) numero_3 = 1 print(f'{numero_3:0>10}') # Adicionando 10 casas a direita no numero print(f'{numero_3:0<10}') # Adicionando 10 casas a esquerda no numero print(f'{numero_3:0^10}') # Adicionando 10 casas e coloca o numero no centro # exemplo com strings print(f'{nome:#>10}') # direita print(f'{nome:#<10}') # esquerda print(f'{nome:#^10}') # centro
false
42487628f83a437a8c08983138a0ec7d82d64957
clebertonf/Python-course
/001-Python-basico/016-desafio-pratico-2.py
862
4.1875
4
from datetime import datetime # Desafio numero par ou impar number = input('Digite um numero inteiro: ') try: number = int(number) if number % 2 == 0: print('Numero é par!') else: print('numero é impar!') except: print('Digite somente numeros inteiros!') # Desafio hora atual com saudação now = datetime.now() hour = f'{now.hour}:{now.minute}:{now.second}' if now.hour > 0 and now.hour < 11: print(f'Bom dia! são exatamente: {hour}') elif now.hour > 11 and now.hour < 17: print(f'Boa tarde! são exatamente: {hour}') else: print(f'Boa noite! são exatamente: {hour}') # Desafio tamanho do nome nome = input('Digite seu nome: ') if len(nome) <= 4: print('Seu nome é muito curto!') elif len(nome) >= 5 and len(nome) <= 6: print('Seu nome é normal!') else: print('Seu nome é muito grande!')
false
3d0dec4941eaeaa712e39ed1495879189e2429b4
essweinjacob/School
/ProgLanguages/project4.py
2,226
4.3125
4
'''' Jacob Esswein Professor Galina Completed 11/3/2019 This program has a 'Product' class and two child classes 'Book' and 'Movie' that inherit 'Product''s constructor and in that, its private variables name, price and discount percent. ''' # Parent class 'Product' class Product: name = "" price = 0 discountPercent = 0 #Contstructor def __init__(self, name, price, discountPercent): # All variables are private self.__name = name self.__price = price self.__discountPercent = discountPercent # Calculate discount amount def getDiscountAmount(self): return self.__price * self.__discountPercent #Calculate discount price def getDiscountPrice(self): return self.__price - self.getDiscountAmount() #Print description / details def printDescription(self): return "Name is: " + self.__name + " price is: " + str(self.__price) + " discount is: " + str(self.__discountPercent) + " discount amount is: " + str(self.getDiscountAmount()) + " discount price is " + str(self.getDiscountPrice()) # Polymorphed class 'Book' of 'Product' takes class 'Product' as a variable class Book(Product): def __init__(self, author, name, price, discountPercent): self.__author = author # Polymorphed class's constructor 'calls' the 'Product' classes constructor Product.__init__(self, name, price, discountPercent) # Polymorphed printDescription def printDescription(self): return "Author is: " + self.__author + Product.printDescription(self) class Movie(Product): def __init__(self, year, name, price, discountPercent): self.__year = year Product.__init__(self, name, price, discountPercent) def printDescription(self): return "Year is " + self.__year + Product.printDescription(self) def main(): #Create objects and give their values product = Product("product", 10, 0.9) book = Book("Jacob Esswein ", "Best Book", 10, 0.1) movie = Movie("1994 ", "Pulp Fiction", 22, 0.3) # Output their descriptions / details print(product.printDescription()) print(book.printDescription()) print(movie.printDescription()) main()
true