blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7fea3515d9f73205a802dc87112acb5270d2d95c
Maurya232Abhishek/Python-repository-for-basics
/Negative Loops.py
440
4.3125
4
r=range(-5) print(r) print("range(-5)") for i in r:#This loop will print nothing because start is 0 and is already greater than -5 print(i) r=range(-5,-1)#Start at -5 and go to -1. start = -5, end=-1, since loop goes to end-1, end-1 is -2 print("range(-5,-1)") print(r) for i in r: print(i) r=range(-5,0) print("range(-5,0)") for i in r: print(i) r=range(-1,-10,-1) print(r) print("range(-1,-10,-1)") for i in r: print(i)
true
f0c6ef5731c81316f62284dec2193dae205c5ba7
Maurya232Abhishek/Python-repository-for-basics
/pyramid.py
234
4.15625
4
n=5 for row in range(1,n + 1): for space in range(1, n-row + 1): print(" ",end="") for o in range(1,row): print(o,end="") for o in reversed( range(1, row-1)): print(o, end="") print()
false
72e8293c5f3a8874a3f657ae8d84ce820d6e164e
hirooiida/Data-Structures-and-Algorithms
/Problems-vs-Algorithms/problem_2.py
2,766
4.46875
4
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ if type(input_list) is not list: return -1 if input_list == []: return -1 left_index = 0 right_index = len(input_list) - 1 while left_index < right_index: mid_index = (left_index + right_index) // 2 left_value = input_list[left_index] mid_value = input_list[mid_index] right_value = input_list[right_index] ''' print("\n") print("target: {}".format(number)) print("left index: {}".format(left_index)) print("mid index: {}".format(mid_index)) print("right index: {}".format(right_index)) print(input_list[left_index:right_index+1]) ''' if mid_index == left_index and mid_value != number: return -1 if mid_value == number: return mid_index elif right_value == number: return right_index elif left_value == number: return left_index ''' case1: 1,2,3,4,5,6,7 left < mid < right case2: 5,6,7,1,2,3,4 mid < right < left case3: 3,4,5,6,7,1,2 right < left < mid ''' if left_value < mid_value < right_value: if number > mid_value: left_index = mid_index continue else: right_index = mid_index continue elif mid_value < right_value < left_value: if mid_value < number <= right_value: left_index = mid_index continue else: right_index = mid_index continue elif right_value < left_value < mid_value: if number > mid_value or number <= right_value: left_index = mid_index continue else: right_index = mid_index if input_list[right_index] == number: return right_index def linear_search(input_list, number): for index, element in enumerate(input_list): if element == number: return index return -1 print(rotated_array_search([6, 7, 8, 9, 10, 1, 2, 3, 4], 2)) # 6 print(rotated_array_search([6, 7, 8, 9, 10, 1, 2, 3, 4], 6)) # 0 print(rotated_array_search([6, 7, 8, 9, 10, 1, 2, 3, 4], 4)) # 8 print(rotated_array_search([6, 7, 8, 9, 10, 1, 2, 3, 4], 0)) # -1 print(rotated_array_search([6, 7, 8, 9, 10, 1, 2, 3, 4], 11)) # -1 print(rotated_array_search([], 2)) # -1 print(rotated_array_search("MyList", 2)) # -1
true
ab1ad56654b41516f4d79d3bd7353a554b4e0c69
anacarolina1002/infosatc-lp-avaliativo-02
/atividade3.py
281
4.125
4
#Escreva um programa para verificar se um elemento x está presente em uma lista. listaA = ["Python","Java","PHP",] print(listaA) print("Python está na lista?") if "Python" in listaA: print("Sim, Python está na lista!") else: print("Não, Python não está na lista!")
false
2726002d13f54aeaf67169ab1a2b52af2618a567
SonjaGrusche/LPTHW
/EX03/ex3update1.py
1,591
4.21875
4
# + "plus" does addition # - "minus" does subtraction # / "slash" does division # * "asterisk" does multiplication # % "percent" does modulus calculation (divides and displays the remainder) # < "less-than" says if the number before the character < is smaller than the number behind it by giving the statement "True" or "False" # > "greater-than" says if the number before the character > is greater than the number behind it by giving the statement "True" or "False" # <= "less-than-equal" says if the number before the characters <= is smalleror equal than the number behind it by giving the statement "True" or "False" # >= "greater-than-equal" says if the number before the characters >= is greater or equal than the number behind it by giving the statment "True" or "False" print "Let's have some more fun with calculations!" print "I want to know how many five-times great-grandparents I'd have, if they were all still alive." print "I'm doing it the easy way." print "I have", 1 +1, "parents." print "They have twice the amount of parents. That would be 2*2. Which equals", 2 * 2 print "My grandparents have 4*2 the amount of parents. Which equals", 4 * 2 print "MY great-grandparents have 8*2 the amount of parents. So", 8 * 2 print "Ugh, it gets confusing." print "My two-times great-grandparents have", 16 * 2, "parents." print "My three-times great-grandparents have", 32 * 2, "parents." print "My four-times great-grandparents have", 64 * 2, "parents." print "And, finally, my five-times great-grandparents have *drum roll*", 128 * 2, "parents." print "Well, that's sick."
true
2c10bdfc733cdd741756a00e53aed161deaf4dc1
apolonio/mundo-python
/ex79-valores-lista.py
732
4.125
4
''' 79 - Crie um propgrama onde o usuario possa digitar varios valores numericos e cadastre-os em uma lista. Caso o numero ja exista la dentro, ele nao sera adicionado, No final, serao exibidos todos os valores unicos digitados. em ordem crescente. ''' numeros = list() while True: n = int(input('Digite um valor: ')) if n not in numeros: numeros.append(n) #adicionando no final da lista print('Valor adicionado com sucesso...') else: print('Valor duplicado! Nao vou adicionar...!') r = str(input('Quer continuar? [S|N]: ')) # se digitar n sai com o break if r in 'Nn': break print('#' * 30) #ordenando numeros.sort() print(f'Voce digitou os valores {numeros}')
false
f64026fa2159aa8ceb8c6f17fe1718c532a115b5
Naimish100/Movies-collection
/app.py
1,179
4.15625
4
MENU_PROMPT = "\n Enter 'a' to add movie, 'f' to find movie, 'l' to show movie or 'q' to quit: " movies = [] def add_movies(): title = input(f"Enter the movie name: ") director = input(f"Enter the movie director: ") year = input("Enter the release year: ") movies.append({ 'title': title, 'director': director, 'year': year }) def show_movies(): for movie in movies: print_movie(movie) def print_movie(movie): print(f"Title: {movie['title']}") print(f"Director: {movie['director']}") print(f"Release year: {movie['year']}") def find_movie(): search_title = input("Enter the title of the movie: ") for movie in movies: if movie['title'] == search_title: print_movie(movie) def menu(): selection = input(MENU_PROMPT) while selection != 'q': if selection == 'a': add_movies() elif selection == 'l': show_movies() elif selection == 'f': find_movie() else: print("Known command. Please try again") selection = input(MENU_PROMPT) menu()
false
f86498fb489580ac1ccf92575b572047e234d4a2
Govorun11/beetroot
/lesson13/task2.py
274
4.1875
4
# Task 2 # Write a Python program to access a function inside a function # (Tips: use function, which returns another function) def my_func(power): def new_func(*args): return sum((x ** power for x in args)) return new_func print(my_func(2)(2, 3, 4, 5))
true
a5fdb975a7c12bfd37edbe2d93ff20b6d8611d68
ag5300cm/sql_light_lab3
/InsertingAndUpdatingRowsSQLite.py
2,296
4.3125
4
#Inserting and updating rows into an existing SQLite database table - next to sending queries - is #probably the most common database operation. The Structured Query Language has a convenient #UPSERT function, which is basically just a merge between UPDATE and INSERT: It inserts new rows #into a database table with a value for the PRIMARY KEY column if it does not exist yet, or updates a row #for an existing PRIMARY KEY value.Unfortunately, this convenient syntax is not supported by the more #compact SQLite database implementation that we are using here. However, there are some #workarounds. But let us first have a look at the example code import sqlite3 sqlite_file = 'my_first_db.sqlite' table_name = 'my_table_3' id_column = 'my_1st_column' column_name = 'my_2nd_column' # Connecting to the database file conn = sqlite3.connect(sqlite_file) c = conn.cursor() # A) Inserts an ID with a specific value in a second column try: c.execute("INSERT INTO {tn} ({idf}, {cn}) VALUES (123456, 'test')".\ format(tn=table_name, idf=id_column, cn=column_name)) except sqlite3.IntegrityError: print('ERROR: ID already exists in PRIMARY KEY column {}'.format(id_column)) # B) Tries to insert an ID (if it does not exist yet) # with a specific value in a second column c.execute("INSERT OR IGNORE INTO {tn} ({idf}, {cn}) VALUES (123456, 'test')".\ format(tn=table_name, idf=id_column, cn=column_name)) #Both A) INSERT and B) INSERT OR IGNORE have in common that they append new rows to the #database if a given PRIMARY KEY does not exist in the database table, yet. However, if we’d try to #append a PRIMARY KEY value that is not unique, a simple INSERT would raise an #sqlite3.IntegrityError exception, which can be either captured via a try-except statement (case A) #or circumvented by the SQLite call INSERT OR IGNORE (case B). This can be pretty useful if we want to #construct an UPSERT equivalent in SQLite. E.g., if we want to add a dataset to an existing database #table that contains a mix between existing and new IDs for our PRIMARY KEY column. # C) Updates the newly inserted or pre-existing entry c.execute("UPDATE {tn} SET {cn}=('Hi World') WHERE {idf}=(123456)".\ format(tn=table_name, cn=column_name, idf=id_column)) conn.commit() conn.close()
true
a22d3c2cfb16eac9d5a3be2bacdac132bc272842
z1dzot/python_lessons
/lesson_1/lesson_1.4.py
537
4.25
4
"""Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.""" user_number = int(input('Enter int number: ')) max_number = user_number % 10 user_number = user_number // 10 while user_number > 0: if user_number % 10 > max_number: max_number = user_number % 10 user_number = user_number // 10 print(max_number)
false
25be81c85a0f0f085e3fcf908f5a18633fcbd434
CarlosHndz/Python_Exercises
/Notes/Chapter01/P1-31.py
2,049
4.4375
4
''' Write a program that can "make change". Your program should take two numbers as input, one that is a monetary amount charged and the other that is a monetary amount given. It should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged. The values assigned to the bills and coins can be based on the monetary system of any current or former government. Try to design your program so that it returns as few bills and coins as possible. ''' def make_change(charge, payment): # NOTE: In order to represent currency properly you # need to use cents as an integer and divide by 100 to convert to dollars. # Using floating point is not accurate to properly represent currency. # Currency represented in cents. Divide by 100 to convert to dollars currency = (10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1) total_change = 0 change = {} difference = int(payment * 100) - int(charge * 100) #convert to cents # while the change is > 0, divide the amount by the highest possible bill # and coin denominations while difference >= 1: for value in currency: if difference >= value: change[value] = int(difference // value) difference %= value # print the charge amount along with the payment and the breakdown of the # calculated change with the minimum amount of bills/coins possible. print("") print("Charge amount: $", charge) print("Payment amount: $", payment) print("") print("Your change consists of: ") for key, value in change.items(): total_change += (key * value) print(value, " x $", (key/100), " = $", ((key * value)/100)) print("For a total change of: $", (total_change/100)) # test the function make_change(4.01, 10.00) # $5.99 make_change(3.45, 20.00) # $16.55 make_change(16.87, 50.00) # $33.13 make_change(0.99, 1.00) # $0.01
true
e7ab1313e218142a9707a56c2747dbb4ceda2124
CarlosHndz/Python_Exercises
/Notes/Chapter01/R1-2.py
847
4.46875
4
# Write a short Python function, is_even(k), that takes an interger value # and returns True if k is even, and False otherwise. However, your # function cannot use the multiplication, modulo, or division operators. def is_even(k): while k > 0: k -= 2 if k == 0: return True return False def is_even_bitwise(m): if m & 1 == 1: return False else: return True print("Is the number 1 even? ", is_even(1)) print("Is the number 2 even? ", is_even(2)) print("Is the number 44 even? ", is_even(44)) print("Is the number 79 even? ", is_even(79)) print("") print("Is the number 1 even? ", is_even_bitwise(1)) print("Is the number 2 even? ", is_even_bitwise(2)) print("Is the number 44 even? ", is_even_bitwise(44)) print("Is the number 79 even? ", is_even_bitwise(79))
true
0ea435bab692fb34ee0aaa99d7e513cd2d604d21
IldarBaydamshin/Coursera-Python-basic
/week_5/zamiechatiel-nyie-chisla-1.py
475
4.1875
4
""" Найдите и выведите все двузначные числа, которые равны удвоенному произведению своих цифр. Формат ввода Программа не требует ввода данных с клавиатуры, просто выводит список искомых чисел. """ for i in range(10, 100): a = i // 10 b = i % 10 if 2 * a * b == i: print(i)
false
a9f4240d4c585e95e00c85247ff176bb8bbef94a
IldarBaydamshin/Coursera-Python-basic
/week_2/tip-trieughol-nika.py
1,495
4.28125
4
""" Даны три стороны треугольника a,b,c. Определите тип треугольника с заданными сторонами. Выведите одно из четырех слов: rectangular для прямоугольного треугольника, acute для остроугольного треугольника, obtuse для тупоугольного треугольника или impossible, если треугольника с такими сторонами не существует (считаем, что вырожденный треугольник тоже невозможен). """ a = abs(int(input())) b = abs(int(input())) c = abs(int(input())) if a >= b >= c or a >= c >= b: hypotenuse = a leg1 = b leg2 = c elif b >= a >= c or b >= c >= a: hypotenuse = b leg1 = a leg2 = c elif c >= a >= b or c >= b >= a: hypotenuse = c leg1 = a leg2 = b left = hypotenuse ** 2 right = leg1 ** 2 + leg2 ** 2 if left * right == 0 or hypotenuse >= leg1 + leg2: print('impossible') # если треугольника с такими сторонами не существует elif left == right: print('rectangular') # для прямоугольного треугольника, elif left < right: print('acute') # для остроугольного треугольника, elif left > right: print('obtuse') # для тупоугольного треугольника или
false
a175aa0b0b5dfe0f1d5119dfa0074e767542d1a9
IldarBaydamshin/Coursera-Python-basic
/week_3/protsienty.py
1,038
4.1875
4
""" Процентная ставка по вкладу составляет P процентов годовых, которые прибавляются к сумме вклада. Вклад составляет X рублей Y копеек. Определите размер вклада через год. При решении этой задачи нельзя пользоваться условными инструкциями и циклами. Формат ввода Программа получает на вход целые числа P, X, Y. Формат вывода Программа должна вывести два числа: величину вклада через год в рублях и копейках. Дробная часть копеек отбрасывается. """ P, X, Y = int(input()), int(input()), int(input()) base = X * 100 + Y percents = (base / 100) * P deposit = base + percents x = int(deposit // 100) y = int(deposit - x * 100) print(x, y)
false
7e16cf25cc79008dc343aeb44a44dcfb001c4d5d
IldarBaydamshin/Coursera-Python-basic
/week_5/riad-2.py
485
4.125
4
""" Даны два целых числа A и В. Выведите все числа от A до B включительно, в порядке возрастания, если A < B, или в порядке убывания в противном случае. Формат ввода Вводятся два целых числа. """ a = int(input()) b = int(input()) if a <= b: print(*tuple(range(a, b + 1))) else: print(*tuple(range(a, b - 1, -1)))
false
5a1a569c496d30b9b416c1138fba85c7f35b1761
IldarBaydamshin/Coursera-Python-basic
/week_3/vstavka-simvolov.py
627
4.375
4
""" Дана строка. Получите новую строку, вставив между каждыми двумя символами исходной строки символ *. Выведите полученную строку. Тест 1 Входные данные: Python Вывод программы: P*y*t*h*o*n Тест 2 Входные данные: Hello Вывод программы: H*e*l*l*o Тест 3 Входные данные: A Вывод программы: A """ s1 = input() s2 = s1[0:1] if len(s1) > 1: for i in range(1, len(s1)): s2 += '*' + s1[i:i + 1] print(s2)
false
ed31396ba8e53f9593a53d7169c123eebb37d3b2
VladimirRech/python
/tuples.py
971
4.25
4
# tuples.py # showing tuples class animal: LegsNumber = 0 def __init__(self, legs = 0): self.LegsNumber = legs # the basic t = 12345, 54321, "hello" # it contains diferent types print(t[0]) print (t) # Tuples may be nested u = t, (1, 2, 3, 4, 5) print(u) # The are immutable # t[0] = 88888 # you can add multiple objects v = ([1,2,3], "hello") print(v) dog = animal() dog.LegsNumber = 4; print(dog.LegsNumber) print("Tuble with Multiple object types") animals = [1, 2, 3], 'A DOG', ('DOG LEGS', dog) print(animals) # Build empty tuple empty = () # with empty closed parentesis print(len(empty)) # Tuple with a single value singleton = 'Just one value', # defined by the coma at end of the line print(len(singleton)) # It's possible to unpacking the elements of a tuple into variables # Just assign with the same number of variables than elements myTuple = (123, 456, 789) print(myTuple) x, y, z = myTuple print(x) print(y) print(z)
true
dc493c917f271b4ef194d95a5b3b4c352eac90c0
VladimirRech/python
/dic.py
1,281
4.28125
4
# dic.py # Dictionaries on Python # The keyes must have immutable # It starts with empty braces: {} firstDic = {} # It's possible initialize with Key:Value pairs phones = { "Joe": "99999-1234", "Ana": "32152-3245"} print(phones) print() # Adding phones["Jessica"] = "89892-3232" print (phones) print() # The are accessible by keys print(phones["Joe"]) print() # Can remove a key del phones["Ana"] print(phones) print() phones["Te"] = "9-9921-3232" phones["Josy"] = "9-0232-1112" # They can be sorted print('Keys sorted') print(sorted(phones)) print() print(phones) print() print("Printing only keys") print(list(phones)) print() print("Finding <<Jessica>> in dic") print("Jessica" in phones) print() print("Finding <<Nemo>>") print("Nemo" in phones) print() # Another way to build a dictionary states = dict([('PR', 'Paraná'), ('SC', 'Santa Catarina'), ('RS', 'Rio Grande do Sul')]) print(states) print() # It's versatile to initialize on python prices=dict(banana=1, apple=2.5, avocado=2.3) print(prices) print() # What will happen if the key not in dictionary? # print(prices['strawberry']) # print() # Error... # Better to check fist if "strawberry" not in prices: print('strawberry not in list') else: print(prices['strawberry'])
true
0414663e8c5bdc9519567b7e7bdd416044d4f741
sowndarya1299/guvi
/codekata/strings/weight-string.py
229
4.21875
4
#Given a string 'S' print the sum of weight of the String. A weight of character is defined as the ASCII value of corresponding character. str = input() sum = 0 for i in range(0, len(str)): sum = sum + ord(str[i]) print(sum)
true
b77290513aeb652657d159896858b604c6123600
anitachu99/cssi
/CSSI/python_practice/practice_doNow.py
841
4.15625
4
##print range(10)## ##print range(100)## ##print range(100, 0)## ##print range(100, 1, 1)## ##print range(100, 1, -1)## ##print range(0, 10)## some_numbers =[2, 52, 19, 46, 1000] empty_list = [] for x in [2, 52, 19, 46, 1000]: print (x + 10)/2 presidents = ["George Washington", "John Adams", "Thomas Jefferson", "James Madison", "James Monroe", "John Quincy Adams"] for president in presidents: reversedpresident= " " for letter in president: reversedpresident = letter + reversedpresident print reversedpresidents #another way in mini lab #for Name in presidents: #Name = Name [::-1] #print Name #or.. #print "".joinreversed() bottles = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] for bottle in bottles: print str(bottle) + " bottles of milk on the wall" #bonus question for LOOP #matrix # a=[[1, 2, 3, 3];[4, 5, 6, 6];[7, 8, 9, 9]] # a[0][1]
false
d92438bcf0f2328c6997f999e4fa44b72c603a1a
anikethjr/Python-Games
/Guess the number.py
2,073
4.125
4
#GUESS THE NUMBER import random import math import simplegui secret_number=0 numguess=0#STORES THE USER'S GUESS genrange=100#STORES THE ENTERED RANGE(EITHER 100 OR 1000) numberofguess=0;#STORES THE NUMBER OF GUESSES THE USER CAN MAKE # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number,numberofguess secret_number=random.randrange(0,genrange) #calculating the number of guesses for the given range numberofguess=int(math.ceil(math.log(genrange+1,2))) # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global genrange genrange=100 print "Game range changed to 0 to 100. New game started..." new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global genrange genrange=1000 print "Game range changed to 0 to 1000. New game started..." new_game() def input_guess(guess): global numberofguess numguess=int(guess) numberofguess-=1 print "Guess was",numguess if(numguess>secret_number): print "Lower" if(numberofguess==0): print "You Lose. New game started with range 0 to",genrange new_game() else: print"You have",numberofguess,"guesses remaining" elif(numguess<secret_number): print "Higher" if(numberofguess==0): print "You Lose. New game started with range 0 to",genrange new_game() else: print"You have",numberofguess,"guesses remaining" else: print "Correct!! New game started with range 0 to",genrange new_game() # create frame frame=simplegui.create_frame("Guess the Number",200,200) # register event handlers for control elements and start frame frame.add_button("Range:0-100",range100,50) frame.add_button("Range:0-1000",range1000,50) frame.add_input("Make a Guess",input_guess,50) # call new_game new_game()
true
bf8ac8a0a09ed2ddb41b3717710357b46d758d92
zhizhe214/untitled
/Test.py
575
4.125
4
# 截取字符串 str='0123456789' print("[:]:"+str[:]) print(range(5,10,1)) for i in range(0,10,3): print(i) list=range(10) print(list) list_2=[3,6,12,30] print(list_2) ''' print("[0:]:"+str[0:]) print("[1:]:"+str[1:]) print("[1:1]:"+str[1:1]) print("[1:2]:"+str[1:2]) print("[1:5]:"+str[1:5]) print("[-2:-1]:"+str[-2:-1]) print("[2:5]:"+str[2:5]) print("[:-3]:"+str[:-3]) print("[-3:]:"+str[-3:]) print("[-1:]:"+str[-1:]) print("[-1]:"+str[-1]) print("[-1:-2]:"+str[-1:-2]) print("[-1:-3]:"+str[-1:-3]) print("[-2:0]:"+str[-2:0]) '''
false
4b4b2791f3263be7195db909e1075beae011641e
kavya199922/python_tuts
/Day-3/loops.py
972
4.125
4
#a set of statements are executed continuosly #stops when the looping condition becomes false # i=5 # while i<10:#test expression/looping condition:i<10 # print(i) # i=i+1 # #if else can also be present inside loop # i=1 # while i<10: # if i%2==0: # print("even:" ,i) # else: # print("odd: ",i) # i=i+1 #infinite loop # i=1 # while i<=10: # print(i) # i=i+1 #for loop:iterating/traversing a list,string,tuple,dictionary # l1=[1,2,3,4] # for i in l1:#1 2 3 4 # print(i) # t1=(1,2,3) # for i in t1: # print(i) set1={22,44,44,66} for i in set1: print(i) d={'jonas':'90','adam':'95','magnus':'29'} # for k,v in d.items(): # print(f"Key is {k} and value is {v}") for k in d: print(k,d[k]) #range:(1,10):print multiples of 3 for i in range(1,10,1): if i%3==0: print(i) a=[1,2,3,4] b=[5,6,7,8,1,2,3] new_list = [] for element in a: if element in b: new_list.append(element) print(new_list)
false
e6f32f89003cd4562c93a5e987b626d80f1c9f35
tamara-0527/pallida-basic-exam-trial
/namefromemail/name_from_email.py
757
4.4375
4
# Create a function that takes email address as input in the following format: # firstName.lastName@exam.com # and returns a string that represents the user name in the following format: # last_name first_name # example: "elek.viz@exam.com" for this input the output should be: "Viz Elek" # accents does not matter #print(name_from_email("elek.viz@exam.com")) def creating_email(): email = input("Give me your email address (firstName.lastName@exam.com) ") name_from_email = email.split('.') first_name = name_from_email[0] create_last_name = name_from_email[1].split('@') last_name = create_last_name[0] name = [] name.insert(1, first_name.title()) name.insert(0, last_name.title()) print(name) created_name = ' '.join(name) print(created_name) creating_email()
true
6d6deb942862c9f68c8138913000a5bb1c077803
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise06_04.py
1,106
4.53125
5
''' *4.6 (Health application: BMI ) Revise Listing 4.6, ComputeBMI.py, to let users enter their weight in pounds and their height in feet and inches. For example, if a person is 5 feet and 10 inches, you will enter 5 for feet and 10 for inches. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user to enter weight in pounds weight = eval(input("Enter weight in pounds: ")) # Prompt the user to enter feet feet = eval(input("Enter feet: ")) # Prompt the user to enter inches inches = eval(input("Enter inches: ")) KILOGRAMS_PER_POUND = 0.45359237; # Kilograms per pound METERS_PER_INCH = 0.0254; # Meters per inch FEET_PER_METER = 3.280839895; # Feet per meter # Convert pounds to kilograms kilogrames = weight * KILOGRAMS_PER_POUND # Convert (Feet + inches) to meters meters = feet / FEET_PER_METER + inches * METERS_PER_INCH # Calculate BMI BMI = kilogrames / (meters * meters); # Display the result print("BMI is", BMI); if (BMI < 18.5): print("Underweight") elif (BMI < 25): print("Normal") elif (BMI < 30): print("Overweight") else: print("Obese")
true
bedd8181117035a0514ce00c7066392530fb207d
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter02/Exercise19_02.py
1,227
4.125
4
'''*2.19 (Financial application: calculate future investment value) Write a program that reads in an investment amount, the annual interest rate, and the number of years, and displays the future investment value using the following formula: futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)**numberOfMonths For example, if you enter the amount 1000, an annual interest rate of 4.25%, and the number of years as 1, the future investment value is 1043.33. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' investmentAmount = eval(input("Enter investment amount: ")) # Enter investment amount annualInterestRate = eval(input("Enter annual interest rate: ")) # Enter annual interest rate monthlyInterestRate = annualInterestRate / 1200 # Calculate the monthly interest rate numberOfYears = eval(input("Enter number of years: ")) # Enter number of years numberOfMonths = 12 * numberOfYears # Calculate number of months # Calculate future investment value futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) ** numberOfMonths # Display results print("Accumulated value is ", int(futureInvestmentValue * 100) / 100)
true
7ff0d25547bff31b93fd1895f469e1a1dd67a947
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise01_04.py
1,534
4.15625
4
''' *4.1 (Algebra: solve quadratic equations) The two roots of a quadratic equation ax2 + bx + c = 0 can be obtained using the following formula: r1 = (-b + (b**2 - 4ac)**0.5) / 2a and r2 = (-b + (b**2 - 4ac)**0.5) / 2a b**2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots. Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display one root. Otherwise, display “The equation has no real roots”. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user to enter a, b and c a, b, c = eval(input("Enter a, b, c: ")) # Compute discriminant discriminant = b * b - 4 * a * c # 1'st if the discriminant is positive if discriminant > 0: # Calculate the tow roots r1 = (-b + discriminant ** 0.5) / (2 * a) r2 = (-b - discriminant ** 0.5) / (2 * a) # Display the results print("The equation has two roots", r1, "and", r2) # 2'nd if the discriminant = 0 elif discriminant == 0: # Calculate the root r1 = (-b + discriminant ** 0.5) / (2 * a) # Display the result print("The equation has one root", r1) # 3'rd if the discriminant is negative else: print("The equation has no real roots") # No real roots
true
2be4ef2126ef751b6fa4a2096a38e28d6bec0cd7
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter02/Exercise25_02.py
961
4.1875
4
''' **2.25 (Turtle: draw a rectangle) Write a program that prompts the user to enter the center of a rectangle, width, and height, and displays the rectangle. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' import turtle # Import turtle module # Prompt the user to enter center point centerX, centerY = eval(input("Enter the rectangle center X and Y: ")) # Prompt the user to enter width and height width, height = eval(input("Enter the rectangle width and height: ")) turtle.showturtle() # Show the turtle graphics window # Draw the rectangle turtle.penup() turtle.goto(centerX - (width / 2), centerY - (height / 2)) turtle.pendown() turtle.goto(centerX + (width / 2), centerY - (height / 2)) turtle.goto(centerX + (width / 2), centerY + (height / 2)) turtle.goto(centerX - (width / 2), centerY + (height / 2)) turtle.goto(centerX - (width / 2), centerY - (height / 2)) turtle.done() # Don't close the turtle graphics window
true
c093fce4ca5c533e18f2fa84c4b096b7cf5ed179
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter03/Exercise16_03.py
1,437
4.375
4
''' **3.16 (Turtle: draw shapes) Write a program that draws a triangle, square, pentagon, hexagon, and octagon. Note that the bottom edges of these shapes are parallel to the x-axis. (Hint: For a triangle with a bottom line parallel to the x-axis, set the turtle’s heading to 60 degrees.) /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' import turtle # Import turtle module radius = 50 # The circle radius # Draw the shape turtle.penup() turtle.goto(- radius * 4, 0) turtle.pendown() turtle.begin_fill() turtle.color("red") turtle.setheading(60) turtle.circle(radius, steps=3) turtle.end_fill() turtle.penup() turtle.goto(-radius * 2, 0) turtle.pendown() turtle.begin_fill() turtle.color("blue") turtle.setheading(45) turtle.circle(radius, steps=4) turtle.end_fill() turtle.penup() turtle.goto(0, 0) turtle.pendown() turtle.begin_fill() turtle.color("black") turtle.setheading(180 / 5) turtle.circle(radius, steps=5) turtle.end_fill() turtle.penup() turtle.goto(radius * 2, 0) turtle.pendown() turtle.begin_fill() turtle.color("green") turtle.setheading(180 / 6) turtle.circle(radius, steps=6) turtle.end_fill() turtle.penup() turtle.goto(radius * 4, 0) turtle.pendown() turtle.begin_fill() turtle.color("yellow") turtle.setheading(180 / 7) turtle.circle(radius, steps=7) turtle.end_fill() turtle.hideturtle() # Hide the turtle turtle.done() # Don't close the turtle graphics window
true
df9197a316b44625e66c4b455c3619a434f43e54
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter03/Exercise12_03.py
751
4.625
5
''' **3.12 (Turtle: draw a star) Write a program that prompts the user to enter the length of the star and draw a star. (Hint: The inner angle of each point in the star is 36 degrees.) /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' import turtle # Import turtle module # Prompt the user to enter the length of the star lenght = eval(input("Enter the length of the the star:")) # Draw the star turtle.forward(lenght) turtle.right(180 - 36) turtle.forward(lenght) turtle.right(180 - 36) turtle.forward(lenght) turtle.right(180 - 36) turtle.forward(lenght) turtle.right(180 - 36) turtle.forward(lenght) turtle.right(180 - 36) turtle.hideturtle() # Hide the turtle turtle.done() # Don't close the turtle graphics window
true
a1ea2e0538bbe7947a31cd6a45535401c181e09d
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter02/Exercise08_02.py
1,127
4.4375
4
''' 2.8 (Science: calculating energy) Write a program that calculates the energy needed to heat water from an initial temperature to a final temperature. Your program should prompt the user to enter the amount of water in kilograms and the initial and final temperatures of the water. The formula to compute the energy is Q = M * (finalTemperature – initialTemperature) * 4184 where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is measured in joules /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user for inputting the amountt of water in kilograms kilograms = eval(input("Enter the amount of water in kilograms: ")) # Prompt the user for inputting the initial temperature initialTemperature = eval(input("Enter the initial temperature: ")) # Prompt the user for inputting the final temperature finalTemperature = eval(input("Enter the final temperature: ")) # Compute the energy energy = kilograms * (finalTemperature - initialTemperature) * 4184 # Display the results print("The energy needed is", energy)
true
1376ce3a057283c92fd171694c9c39d1f6d419c3
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise14_04.py
763
4.5
4
''' 4.14 (Game: heads or tails) Write a program that lets the user guess whether a flipped coin displays the head or the tail. The program randomly generates an integer 0 or 1, which represents head or tail. The program prompts the user to enter a guess and reports whether the guess is correct or incorrect. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' import random random = random.randint(0, 1) # Generate random 0 or 1 # Prompt the user to enter to enter filing status guess = eval(input("guess whether the flip of a coin results in" \ + "a head or a tail, 0 for head and 1 for tail: ")) # Check the if the guess is correct and diplay the result print("Your guess is:", "Correct" if random == guess else "incorrect")
true
12c778ebee6d70f0c169be578a93a4091936d522
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise03_04.py
749
4.375
4
''' *3.3 (Algebra: solve 2 * 2 linear equations) A linear equation can be solved using Cramer’s rule given in Programming Exercise 1.13. Write a program that prompts the user to enter a, b, c, d, e, and f and displays the result. If ad - bc is 0, report that “The equation has no solution.” /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user to enter a, b, c, d, e and f a, b, c, d, e, f = eval(input("Enter a, b, c, d, e, f: ")) if (a * d - b * c) == 0: # The equation has no solution print("The equation has no solution") else: # Other than calculate x and y and display the results x = (e * d - b * f) / (a * d - b * c) y = (a * f - e * c) / (a * d - b * c) print("x is", x, "and y is", y)
true
850c3d7c453cc0bb9342fb45d4b2bbb4f3d93096
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise23_04.py
961
4.25
4
''' **4.23 (Geometry: point in a rectangle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is outside the rectangle, as shown in Figure 4.8b. (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical distance to (0, 0) is less than or equal to 5.0 / 2. Test your program to cover all cases.) /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Assign the rectangle width and height WIDTH = 10.0 HEIGHT = 5.0 # Asking for entering a point x, y = eval(input("Enter a point with two coordinates: ")) # Check if in the point inside the rectangle and display the result print("Point (" + str(x) + ", " + str(y) + ") is " + \ ("" if x <= WIDTH / 2 and y <= HEIGHT / 2 else "not ") + \ "in the rectangle")
true
bc6bd04a911109e3af514c6d5f9556bd8191d3f8
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter05/Exercise30_05.py
2,227
4.5625
5
''' **5.30 (Display the first days of each month) Write a program that prompts the user to enter the year and first day of the year, and displays the first day of each month in the year. For example, if the user entered the year 2013, and 2 for Tuesday, January 1, 2013, your program should display the following output: January 1, 2013 is Tuesday ... December 1, 2013 is Sunday /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user to a year year = eval(input("Enter a year: ")) # Prompt the user to enter the first day of year firstDay = eval(input("Enter first day of the year (0 for Sunday, " + " .. , 6 for Saturday): ")) dayOfWeek = "" # Initialize day of week name monthName = "" # Initialize month name monthDays = 0 # Initialize the number of month days print("Year months first days:") for n in range(1, 12 + 1): if n == 1: monthName = "January" monthDays = 31 elif n == 2: monthName = "February" monthDays = 29 if year % 400 == 0 or \ (year % 4 == 0 and year % 100 != 0) else 28 elif n == 3: monthName = "March" monthDays = 31 elif n == 5: monthName = "May" monthDays = 31 elif n == 7: monthName = "July" monthDays = 31 elif n == 8: monthName = "August" monthDays = 31 elif n == 10: monthName = "October" monthDays = 31 elif n == 12: monthName = "December" monthDays = 31 elif n == 4: monthName = "April" monthDays = 30 elif n == 6: monthName = "June" monthDays = 30 elif n == 9: monthName = "September" monthDays = 30 elif n == 11: monthName = "November" monthDays = 30 dayOfWeek = "Sunday" if firstDay == 0 else "Monday" if firstDay == 1 \ else "Tuesday" if firstDay == 2 else "Wednesday" if firstDay == 3 \ else "Thursday" if firstDay == 4 else "Friday" if firstDay == 5 \ else "Saturday" print(" ", monthName, "1,", year, "is", dayOfWeek) # Shift to first day of next month firstDay = (firstDay + monthDays) % 7
true
16f9680c590f526e645389869aa6e00ba688320d
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise32_04.py
1,139
4.1875
4
''' *4.32 (Geometry: point on line segment) Exercise 4.31 shows how to test whether a point is on an unbounded line. Revise Exercise 4.31 to test whether a point is on a line segment. Write a program that prompts the user to enter the x- and y-coordinates for the three points p0, p1, and p2 and displays whether p2 is on the line segment from p0 to p1. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Asking to enter three points for p0, p1, and p2 x0, y0, x1, y1, x2, y2, = eval(input("Enter three points for p0, p1, and p2: ")) # Calculate the position position = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) # point is on a line segment if position = 0 and x2 is between x0 and x1 if position == 0 and x2 >= min(x0, x1) and x2 <= max(x0, x1): print("(" + str(x2) + ", " + str(y2) + ") is on the line segment from (" + str(x0) + ", " + str(y0) + ") to (" + str(x1) + ", " + str(y1) + ")") # Otherwise it is not on the line segment else: print("(" + str(x2) + ", " + str(y2) + ") is not on the line segment from (" + str(x0) + ", " + str(y0) + ") to (" + str(x1) + ", " + str(y1) + ")")
true
015b37137ec496152f8b49b28c47d2a911cd6853
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
/chapter04/Exercise26_04.py
629
4.15625
4
''' 4.26 (Palindrome number) Write a program that prompts the user to enter a three-digit integer and determines whether it is a palindrome number. A number is a palindrome if it reads the same from right to left and from left to right. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Prompt the user to enter a three-digit integer number = eval(input("Enter a three-digit integer: ")) # Extract 1st and 3rd digits digit1 = number // 100 digit2 = number % 100 // 10 digit3 = number % 10 # check if they are equal and display the result print(number, "is", ("" if digit1 == digit3 else "not"), "a palindrome")
true
80243c3ba1465dc399621f51140a4f82d516f767
pointschan/pylearning
/simpleClass_2.py
1,221
4.15625
4
__author__ = 'pointschan' """ Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class. Shared data can have possibly surprising effects with involving mutable objects such as lists and dictionaries. For example, the tricks list in the following code should not be used as a class variable because just a single list would be shared by all Dog instances """ class Dog_publictricks: tricks = [] # mistaken use of a class variable def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) class Dog_privatetricks: def __init__(self, name): self.name = name self.tricks = [] # creates a new empty list for each dog def add_trick(self, trick): self.tricks.append(trick) f = Dog_publictricks("Fido") b = Dog_publictricks("Buddy") f.add_trick("roll over") b.add_trick("play dead") print f.name, f.tricks print b.name, b.tricks d = Dog_privatetricks("Fido_2") e = Dog_privatetricks("Buddy_2") d.add_trick("roll over") e.add_trick("play dead") print d.name, d.tricks print e.name, e.tricks
true
7bfc08b7e486ad736d281219840ddc9d8f2e677d
andredoumad/dailyCodingProblemPython
/20_08_06_Google.py
2,720
4.125
4
# Andre Doumad ''' This problem was asked by Google. Suppose we represent our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.ext The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note: The name of a file contains at least a period and an extension. The name of a directory or sub-directory will not contain a period. ''' import unittest class Solution(object): def solve(self, n): nlist = [] level = 0 result = 0 for name in n.split('\n'): print(nlist, level) tabs = name.split('\t') if len(tabs) -1 == level: if nlist: i = nlist.pop() print('popping nlist ', i) print('tabs[-1] ', tabs[-1]) nlist.append(tabs[-1]) elif len(tabs) -1 > level: print('tabs[-1] ', tabs[-1]) nlist.append(tabs[-1]) else: for i in range(level - len(tabs) + 2): if nlist: nlist.pop() nlist.append(tabs[-1]) if '.' in tabs[-1]: result = max(result, len('/'.join(nlist))) level = len(tabs)-1 return result class unitTest(unittest.TestCase): def test_a(self): solution = Solution() print('''dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext''') result = solution.solve('dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext') print('RESULT: ' + str(result)) if __name__ == '__main__': unittest.main()
true
42f5e2219c551a10cbf7d9a69673ec1c9055ecd3
poplarsunshine/Python
/Test/Pandas/series.py
1,826
4.25
4
import pandas as pd groceries = pd.Series(data = [30, 6, "Yes", "No"], index = ["eggs", "apples", "milk", "bread"]) print("groceries=\n", groceries) print('Groceries has shape:', groceries.shape) print('Groceries has dimension:', groceries.ndim) print('Groceries has a total of', groceries.size, 'elements') print('The data in Groceries is:', groceries.values) print('The index of Groceries is:', groceries.index) # 如果你处理的是非常庞大的 Pandas Series, # 并且不清楚是否存在某个索引标签,可以使用 in 命令检查index是否存在该标签: x = 'bananas' in groceries y = 'bread' in groceries print('Is bananas an index label in Groceries:', x) print('Is bread an index label in Groceries:', y) # 为了清晰地表明我们指代的是索引标签还是数字索引, # Pandas Series 提供了两个属性 .loc 和 .iloc,帮助我们清晰地表明指代哪种情况。 # 属性 .loc 表示位置,用于明确表明我们使用的是标签索引。 # 属性 .iloc 表示整型位置,用于明确表明我们使用的是数字索引。 print('groceries:', groceries["eggs"]) print('groceries:\n', groceries[["eggs"]]) print('groceries:\n', groceries[[0, 1]]) print('groceries:\n', groceries.loc[["eggs", "apples"]]) print('groceries:\n', groceries.iloc[[0, 1]]) # .drop() 方法删除 Pandas Series 中的条目 # 关键字 inplace 设为 True,原地地从 Pandas Series 中删除条目 print('Original Grocery List:\n', groceries) print('We remove apples (out of place):\n', groceries.drop('apples')) print('Grocery List after removing apples out of place:\n', groceries) print('Original Grocery List:\n', groceries) print('We remove apples (out of place):\n', groceries.drop('apples', inplace=True)) print('Grocery List after removing apples out of place:\n', groceries)
false
b108788740efb0fa2680edd310ceb05777ea402a
felsen/project-eular
/multiples_of_three_five.py
815
4.28125
4
# If we list all the natural numbers below 10 that are # multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def main(): multiplies_3 = range(0, 10) mul_3 = [] for i in multiplies_3: if (i % 3 == 0) or (i % 5 == 0): mul_3.append(i) return sum(mul_3) def method1(): multiplies_5 = range(0, 1000) mul_5 = [] for i in multiplies_5: if (i % 3 == 0) or (i % 5 == 0): mul_5.append(i) return sum(mul_5) def method2(): multiplies_5 = range(0, 1000) mul_5 = 0 for i in multiplies_5: if (i % 3 == 0) or (i % 5 == 0): mul_5 += i return mul_5 if __name__ == '__main__': print main() print method1() print method2()
false
ec82dae70aace99171e2d84f54f06c27728fa368
madelinepet/data-structures-and-algorithms
/sorting_algos/mergesort.py
989
4.25
4
def mergesort(input_list): """ Takes in a list and splits it into halves recursively, then compares parts of the list to each other and merges them sorted into another list """ output = [] if len(input_list) > 1: mid = len(input_list) // 2 first_half = input_list[:mid] second_half = input_list[mid:] sorted_first_half = mergesort(first_half) sorted_second_half = mergesort(second_half) i = 0 j = 0 while i < len(sorted_first_half) and j < len(sorted_second_half): if sorted_first_half[i] < sorted_second_half[j]: output.append(sorted_first_half[i]) i += 1 else: output.append(sorted_second_half[j]) j += 1 if i < len(sorted_first_half): output.extend(sorted_first_half[i:]) else: output.extend(sorted_second_half[j:]) return output else: return input_list
true
a73ccfe652469d2bfb7d3abc44531e1a0e404a3f
Jayasurya30/Python-Programs
/Simple Calculator.py
590
4.1875
4
print("**************SIMPLE CALCULATOR**************") print("1.Addition") print("2.Subtraction") print("3.multiplication") print("4.division") S=int(input("Select the option")) A=int(input("Enter the first number:")) B=int(input("Enter the second number:")) if S==1: C=A+B print("Addition of the number is:",C) elif S==2: D=A-B print("Subtraction of the number is:",D) elif S==3: E=A*B print("Multiplication of the number is:",E) elif S==4: F=A/B print("Divison of the number is:",F) else: print("given option is invalid")
true
a47a8503b23a4928e0c48a42c7a5fb577ff675a9
nrockweiler/bioinformatics_wkshp_washu
/python/lessons/analyze_heights-solution3.py
902
4.375
4
#!/usr/bin/python3 # This script analyzes the height of Molly and her friends inches_in_meter = 39.4 # the number of inches in a meter inches = 64 # Molly's height in inches meters = 64/39.4 # Molly's height in meters heights = [1.65, 1.75, 1.55, 1.78, 1.83] # list of height of Molly's friends heights.append(meters) # height of height of Molly's friends and Molly # calculate the mean of all of the heights total = 0 for height in heights: total = total + height mean = total/len(heights) sum_diffsq = 0 for height in heights: diff = height-mean diff_sq = diff**2 sum_diffsq = sum_diffsq + diff_sq variance = sum_diffsq/(len(heights)-1) print("variance is more than 0.01:") if variance > 0.01: print("True") else: print("False") print("The mean and the variance are approximately equal: ") if abs(mean-variance) < 0.01: print("True") else: print("False")
true
ec6a7acb8b5eb11e6eff56da47170d84a3fcae5e
shumavik/Study
/python/example.py
351
4.125
4
def arifm(a,b,operation): if operation == "+": print(a+b) elif operation == "-": print(a-b) elif operation == "*": print(a*b) elif operation == "/": print(a/b) x = int(input("Enter first number:")) y = int(input("Enter second number:")) arifm(x, y, input("Enter operation:+,-,*,/\n"))
false
fdc29c2d2eaf378aa315c34480464bb5e9e1d589
madhuhanamagoudar/Python_Project
/Numberguesser.py
933
4.125
4
import random def guesss_num(): #function for guessing the number print("Try to guess that number") for i in range(1,4): #Run for 3 times print("Enter the number between 1 to 50 ") global guess guess=int(input("Enter the number:")) if(guess>secretnumber): print("Number is too high") elif(guess<secretnumber): print("Number is too low") else: break choice=input("You want to play?") while(choice == "yes"): print("I am Currently Thinking of a number") secretnumber=random.randint(1,50) #Creates a random integer guesss_num() if(guess== secretnumber): print("Congratulations!! You guessed it right ") else: print("Better Luck next time ") print("The actual number was "+str(secretnumber)) #says what was the number choice=input("You Want to Continue?") else: exit()
true
dae0356a62e8449b7c08f4e13d934d41f85426f7
FlyMaple/iplaypy-100
/python_project/021.py
752
4.28125
4
# Python練習題問題及要求如下: # 問題簡述:一隻小猴子吃桃子的問題。 # 話說,一隻小猴子第一天摘下若干個桃子,並吃了一半。感覺到吃的還不癮,於是又多吃了一個; # 第二天早上,又將剩下的桃子吃掉一半,又多吃了一個。 # 以後每天早上,都吃了前一天剩下的一半零一個。 # 玩蛇網python問題:請問,到了第10天早上想再吃時,卻發現只剩下一個桃子了。求第一天共摘了多少? # Python解題思路分析:這道題,需要採取逆向思維的方法來從後往前推算,思維清晰,思路活躍。 m = 1 for i in range(10): print('第 {:2d} 天有 {:4d} 個桃子'.format(10 - i, m)) m = (m + 1) * 2
false
05afd4e89a8e6da667ddfc37e956e69c2e7c306f
Shakawat-dev/python-all-docs
/practice.py
1,183
4.125
4
# Find out the given Bangla words meaning # myWordsList = { 'patil':'container', 'mog':'jar', 'baksho':'box' } print('Options are :',myWordsList.keys()) a = input('Enter your Bangla words: ') print('your given word meaning is :', myWordsList[a]) # program of unique number # num1 = int(input('Enter your number 1\n')) num2 = int(input('Enter your number 2\n')) num3 = int(input('Enter your number 3\n')) num4 = int(input('Enter your number 4\n')) num5 = int(input('Enter your number 5\n')) num6 = int(input('Enter your number 6\n')) num7 = int(input('Enter your number 7\n')) num8 = int(input('Enter your number 8\n')) uniqueNum = {num1, num2, num3, num4, num5, num6, num7, num8} print('The list of your entered number are:',uniqueNum) # add user input into a emty string # favLang = {} a = input('Enter your favorite language sonali\n') b = input('Enter your favorite language ropali\n') c = input('Enter your favorite language masum\n') d = input('Enter your favorite language khan\n') favLang['sonali'] = a favLang['ropali'] = b favLang['khan'] = c favLang['khan'] = d print(favLang) # check the set's value # s = {6, 6, 12, 'Harry', tuple([1, 3])} print(type(s))
false
dd672667c5ccb9dc39a6be317f3c920c359971f3
aofeng/PythonDemo
/src/cn/aofeng/demo/oop/Inheritance.py
1,294
4.21875
4
# coding:utf8 # 在子类的__init__方法执行时,并不会自动执行父类的__init__方法,需在子类的代码中显式调用,这与Java不同 # 使用super实现继承从Pytho2.3版本开始支持,比经典的继承方式更加容易使用,且可维护性更好 class Human(object): def __init__(self, name): self.name = name self.sex = "unkown" def printName(self): print "name:", self.name def printSex(self): print "sex:", self.sex def sayHi(self): print "风一样的人" class Male(Human): # 指定继承自Human def __init__(self, name): super(Male, self).__init__(name) # 通过super调用父类Human的初始化方法 self.sex = "Male" def sayHi(self): print "风一样的男人" class Female(Human): # 指定继承自Human def __init__(self, name): super(Female, self).__init__(name) # 通过super调用父类Human的初始化方法 self.sex = "Female"; def sayHi(self): super(Female, self).sayHi() # 通过super方式调用父类的方法 print "风一样的女人" male = Male("XiaoMing") female = Female("Mary") male.printName() male.printSex() male.sayHi() female.printName() female.printSex() female.sayHi()
false
47808cb1a8789ee846267919fe2ffaa36d3cac18
wy471x/learningNote
/python/excise/basic/test/even_or_odd.py
225
4.34375
4
#!/usr/bin/env python # coding=utf-8 num = input("Enter a number,and I'll tell you if it's even or odd:") num = int(num) if num%2 == 0: print("\n" + str(num) + " is even!") else: print("\n" + str(num) + " is odd!")
true
4292dd5f375e33e2d136f9993d6acab2d557859d
krupa253/Python_basics
/62.Constructor_in_inheritance2.py
474
4.125
4
# When you create object of sub class it will call init of sub class first, if you have call super class then it will # first call init of super class then call init of sub class class A: def __init__(self): print("in A init") def feature1(self): print("Feature 1 Working") class B(A): def __init__(self): super().__init__() print("in B init") def feature1(self): print("Feature 1 Working") a1 = B()
true
66db4529127715a57d7ce20ecb5c83a5f357d71a
russhughes/st7789py_mpy
/examples/ttgo_tdisplay_rp2040/toasters/toasters.py
2,177
4.15625
4
""" toasters.py An example using bitmap to draw sprites on the display. Spritesheet from CircuitPython_Flying_Toasters https://learn.adafruit.com/circuitpython-sprite-animation-pendant-mario-clouds-flying-toasters """ import random from machine import Pin, SoftSPI import st7789py as st7789 import t1, t2, t3, t4, t5 TOASTERS = [t1, t2, t3, t4] TOAST = [t5] class toast(): ''' toast class to keep track of a sprites locaton and step ''' def __init__(self, sprites, x, y): self.sprites = sprites self.steps = len(sprites) self.x = x self.y = y self.step = random.randint(0, self.steps-1) self.speed = random.randint(2, 5) def move(self): if self.x <= 0: self.speed = random.randint(2, 5) self.x = 135 - 64 self.step += 1 self.step %= self.steps self.x -= self.speed def main(): """ Initialize the display and draw flying toasters and toast """ spi = SoftSPI( baudrate=20000000, polarity=1, phase=0, sck=Pin(18), mosi=Pin(19), miso=Pin(13)) tft = st7789.ST7789( spi, 135, 240, reset=Pin(23, Pin.OUT), cs=Pin(5, Pin.OUT), dc=Pin(16, Pin.OUT), backlight=Pin(4, Pin.OUT), rotation=0) tft.fill(st7789.BLACK) # create toast spites in random positions sprites = [ toast(TOASTERS, 135-64, 0), toast(TOAST, 135-64*2, 80), toast(TOASTERS, 135-64*4, 160) ] # move and draw sprites while True: for man in sprites: bitmap = man.sprites[man.step] tft.fill_rect( man.x+bitmap.WIDTH-man.speed, man.y, man.speed, bitmap.HEIGHT, st7789.BLACK) man.move() if man.x > 0: tft.bitmap(bitmap, man.x, man.y) else: tft.fill_rect( 0, man.y, bitmap.WIDTH, bitmap.HEIGHT, st7789.BLACK) main()
true
ef31fda4261465fb4537e5e86f3728df5ba2b09c
jessemckenna/LeetCode
/Python/482-license-key-formatting.py
1,974
4.125
4
''' You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above. ''' #class Solution(object): def licenseKeyFormatting(S, K): """ :type S: str :type K: int :rtype: str """ n = len(S) if n == 0 or n <= K: return S.upper().replace("-", "") # count number of alphanumeric characters alnums = sum(i.isalnum() for i in S) hyphens = S.count("-") if alnums + hyphens < n: print("String contains non-alphanumeric, non-hyphen characters") return # move values to new list result = [] index = 0 alnumsPlaced = 0 groupLen = 0 firstGroup = alnums % K if firstGroup > 0: while groupLen < firstGroup: # create undersized first group if needed if S[index].isalnum(): result.append(S[index].upper()) groupLen += 1 alnumsPlaced += 1 index += 1 result.append("-") while alnumsPlaced < alnums: # create subsequent groups groupLen = 0 while groupLen < K: if S[index].isalnum(): result.append(S[index].upper()) alnumsPlaced += 1 groupLen += 1 index += 1 result.append("-") result = result[:len(result) - 1] # remove trailing hyphen result = ''.join(result) return result print(licenseKeyFormatting("a-a-a-a-", 1))
true
edd31492b4374c91e6c1dad3977a64603d82865f
vnikov/Solving-100-exercises
/Code/80.py
2,101
4.375
4
#Create a script that lets the user create a password until they have satisfied three conditions: #Password contains at least one number, one uppercase letter and it is at least 5 chars long #Give the exact reason why the user has not created a correct password def CheckLen (password): if len(password) >= 5: global LenRes LenRes = True print ('Password length is good.') return (LenRes) else: LenRes = False print ('Password is too short.') return (LenRes) def FindNumber(password): if any (char.isdigit() for char in password): global NumRes NumRes = True print ('Password has at least one digit.') return (NumRes) else: NumRes = False print ('Password must have at least one digit.') return (NumRes) def CheckUpper(password): if any (char.isupper() for char in password): global UppRes UppRes = True print ('Password has at least one uppercase letter.') return (UppRes) else: UppRes = False print ('Password must have at least one uppercase letter.') return (UppRes) def PasswordChecker(): while True: password = raw_input('Please enter password: ') CheckLen(password) FindNumber(password) CheckUpper(password) if LenRes and NumRes and UppRes is True: print 'Password succesfully created!' break else: print ('Please try again.') PasswordChecker() # his answer # while True: # notes = [] # psw = input("Enter password: ") # if not any(i.isdigit() for i in psw): # notes.append("You need at least one number") # if not any(i.isupper() for i in psw): # notes.append("You need at least one uppercase letter") # if len(psw) < 5: # notes.append("You need at least 5 characters") # if len(notes) == 0: # print("Password is fine") # break # else: # print("Please check the following: ") # for note in notes: # print(note)
true
f5268894735e40c75bf3cb5b1fca22be173f0c50
oganesyankarina/GB_Python
/Урок5Файлы/task2.py
578
4.125
4
"""2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ f_obj = open('task2_file.txt', encoding='utf-8') text = [line.strip() for line in f_obj] f_obj.close() print(f'Количество строк в файле: {len(text)}') for line in text: print(f'Строка: {line}') print(f'Количество слов в строке: {len(line.split())}')
false
5adf6699b4533b10ebe68a3edef983f6e7ef74b6
musslebot/algs
/Chapter 2/sort.py
2,620
4.375
4
import math def insertion_sort(A): """ Put a sequence's elements in ascending order, using insertion sort. """ for j in range(1, len(A)): key = A[j] i = j - 1 while i >= 0 and key < A[i]: A[i+1] = A[i] i -= 1 A[i+1] = key def reverse_insertion_sort(A): """ Put a sequence's elements in descending order, using insertion sort. """ for j in range(1, len(A)): key = A[j] i = j - 1 while i >= 0 and key > A[i]: A[i+1] = A[i] i -= 1 A[i+1] = key def selection_sort(A): """ Put a sequence's elements in ascending order, using selection sort. """ for i in range(0, len(A)-1): j = i for k in range(i+1, len(A)): if A[k] < A[j]: j = k if j != i: key = A[i] A[i] = A[j] A[j] = key def merge_sort(A, p=None, r=None): """ Put a sequence's elements in ascending order, using merge sort. """ def merge(A, p, q, r): """ Merge two subsequences (defined by indices p, q, and r) into a sequence. """ # Define subsequences L = A[p:q+1] + [float("inf")] R = A[q+1:r+1] + [float("inf")] # Merge i = 0 j = 0 for k in range(p, r+1): if L[i] <= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 if p is None: p = 0 if r is None: r = len(A) - 1 if p < r: q = int(math.floor((p+r)/2)) merge_sort(A, p, q) merge_sort(A, q+1, r) merge(A, p, q, r) if __name__ == "__main__": import copy import random print("Generating random sequence of 100 numbers and expected sort..."), original = [random.randint(0, 100) for _ in range(100)] expected = sorted(original) print("Done") print("Testing insertion_sort..."), sequence = copy.deepcopy(original) insertion_sort(sequence) assert sequence == expected print("Passed") print("Testing reverse_insertion_sort..."), sequence = copy.deepcopy(original) reverse_insertion_sort(sequence) assert sequence == sorted(original, reverse=True) print("Passed") print("Testing selection_sort..."), sequence = copy.deepcopy(original) selection_sort(sequence) assert sequence == expected print("Passed") print("Testing merge_sort..."), sequence = copy.deepcopy(original) merge_sort(sequence) assert sequence == expected print("Passed")
false
24f4ef2c6d6bb7119e7bab5aeb8f8b54439385d8
MichaelJFodor/Python-Course
/Data Types and Variables/assignment3.py
2,315
4.25
4
### PART 1 ### # What would the following print? Uncomment to see your answer # print("101 % 1=", 101%1) # print("101 % 10=", 101%10) # print("101 % 100=", 101%100) # print("101 % 1000=", 101%1000) a = 5 a %= 7 #print(a) b = 12 b %= a #print(b) c = 5 c %= b + 1 #print(c) ### PART 2 ### # Define a list named "Animal Cell" # Initialize it with the data: "Mito", "Golgi", "Ribos", "Nucleus", "E.R.", and "Lysos" # REMEMBER you use [brackets] to define a list # Create an variable named "i" and initialize it to 0 (i in this case is short for "index" which tracks the index # of each value in your list) # Print every element of "Animal Cell" to the console using the "i" variable (you will need to use + ) # Challenge: Without creating a new list, how can you append a new value to the back of your list in Python3? # Append "Perox" to your already existing list ### PART 3 ### # Define a list named "Sugar List" and initialize it with the values "Dex", "Fruct", "Gluc", "Lact", "Sucr" and "Malt" # Define a variable named "My Fav Ose" and assign it the value of your favorite choice using the [] operator # Find the length of the Sugar List and assign it to a variable. # Challenge: Using the variable you just make (of list size), print to the console the last element in Sugar List # without creating a new variable! ### PART 4 ### # Define a variable named "User Name" and initialize it to: "Bob" # Define a variable named "Password" and initialize it to: "123abc" # Define a variable named "Zip" and initialize it to: 12345 <-- an int, not a string! # Define a variable named "In College" and initialize it to: False # Define a variable named "Coolness Level" and initialize it to: 3.6 # Challenege: Define a variable named "Account List" and initialize it to contain the values using only the variables you # defined from above # Find the length of the list and store it in a variable # Print to the console the entire list using only one variable name # Access the last element of the list using the [] operator and your length variable, and change its value to 4.6 but # not create a new variable # Print to the console the entire list using only one variable name (Ensure that the last element is now 4.6)
true
c2c85b9e19e2ff60c9815bc0d246304d6cd57f6f
MichaelJFodor/Python-Course
/Data Types and Variables/assignment2.py
2,696
4.25
4
### Part 1 ### Casting # Create a variable named “Number of Colors” and assign it the integer value 3 # Multiply Number of Colors by 5, and store it in a variable named “More Colors” # Divide More Colors by 10 and store it into a variable named “Fraction Of Colors” # Cast Fraction of Colors into an integer and store it into a variable named “Whole Color” # Cast Whole Color into a boolean and store it into a variable named “Is Color” # Challenge: Print to the console the type of EACH variable you wrote, the Name of each variable, and the value of each variable using ONLY 5 print statements, and NO new variables. ### Part 2 ### Operators # You are not allowed to create any new variables; you must reuse the variable x # You are given x = 5, make use of the += operator to make x equal to 7, then print x # Use -= to make x equal to 2 , then print x # Use **= to make x equal to 8 , then print x # Use /= to make x equal to 4 , then print x ### Part 3 ### Strings # Create a variable named “User Name” and assign it the the string of YOUR name # Find out how to use the len() function. Try searching “How to use len() in Python”. Make a variable named “Name Length” and assign it the length of your name. # Create a variable named “Start Intro” and assign it the value “Hello! My Name is” # Create a variable named “Middle Intro” and assign it the value “, and my name is exactly” # Create a variable named “End Intro” and assign it the value “letters long!” # Using only one print statement, print a statement to the console that reads “Hello! My name is Michael , and my name is exactly 7 letters long!”, but using only the 5 variables you created. ### Part 4 ### More operators # Make variable mol_0 = 0.09 # Make variable mol_1 = 0.12 # Make variable mol_2 = 0.2 # Make variable liters_0 = 0.8 # Make variable liters_1 = 0.5 # Make variable liters_2 = 1.0 # Store the molarity from each number pair (mol_0, liters_0,...mol_1, liters_1,....) into variables named molarity_0, molarity_1, and molarity_2. # Convert each volume based variable into mL and name them mL_0, mL_1, mL_2 (you must use arithmetic operations and the liters variables, you cannot simply set these mL variables to be the answer. # Cast each mL variable into an int ### Part 5 ### Logic bool t = True bool f = False # Guess what the following will print! print(t and t) print(t and 1) print(t and f) print(not t) print(not f) print(f or t) print(f or 0) print(t or f) print(f and t) print(t or t)
true
0d9cbc495235cdbbf5abb80d2b72a5691f6fb3d0
barleen-kaur/LeetCode-Challenges
/DS_Algo/sorting/frequencySortChar.py
815
4.1875
4
''' 451. Sort Characters By Frequency : Medium Q. Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. ''' class Solution: def frequencySort(self, s: str) -> str: chdict = {} for ch in s: if ch not in chdict: chdict[ch] = 1 else: chdict[ch] += 1 sorteddict = sorted(chdict.items(), key= lambda k:k[1], reverse=True) print(sorteddict) string = '' for ch, freq in sorteddict: string += ch*freq return string
true
8fdf8ed0741d198b09b0d749104f21368de1dfc6
danhuyle508/data-structures-and-algorithms_1
/code401challengespython/llMerge/ll_merge.py
1,199
4.21875
4
class LinkedList(): head = None def insert(self, value): """ a function to insert into the list """ if not self.head: self.head = Node(value) else: current = self.head while current._next: current = current._next current._next = Node(value) def merge(self, list_2): curr_1 = self.head curr_2 = list_2.head new_head = curr_1 while curr_1._next or curr_2._next: temp_1 = curr_1._next temp_2 = curr_2._next curr_1._next = curr_2 new_head._next = curr_1 curr_1 = temp_1 curr_2 = temp_2 return new_head def print(self): """ a print function to print out the complete list """ if self.head: output = '' current = self.head while current: output += current.value + ',' current = current._next return output return -1 class Node(): def __init__(self, value): self.value = value self._next = None
true
86dacb644d4d4c2a7273056281d5c6316190e780
alTaWBC/python
/program_flow_control_in_python/challenge.py
600
4.125
4
options = """Please choose your option from the list below: 1. Learn Python 2. Learn Java 3. Go swimming 4. Have dinner 5. Go to bed 0. Exit""" option = "" while option != "0": if option == "1": print("You learned Python") elif option == "2": print("You learned Java") elif option == "3": print("You went swimming") elif option == "4": print("You had dinner") elif option == "5": print("zzzzzzzz") else: print(options) option = input("Please choose an option from the menu: ").casefold() else: print("Have a nice day")
true
1a5184c25f378c8d948dab596bb086f34d91f8a7
alTaWBC/python
/functions/fibonacci.py
617
4.3125
4
def fibonacci(nth_fibonacci: int, first=0, second=1) -> int: """Returns the nth value of fibonacci sequence starting in values first, second Args: nth_fibonacci (int): number to determine first (int, optional): value to start. Defaults to 0. second (int, optional): value to start. Defaults to 1. Returns: int: nth value of fibonacci sequence """ value = min(nth_fibonacci, second) for _ in range(1, nth_fibonacci): value = first + second first = second second = value return value for i in range(36): print(i, fibonacci(i))
true
0a2315bd729036f459722493c020a48fe31244d7
whatliesbeyond/Python
/battleship-game.py
1,627
4.3125
4
# Battleship Game with your PC # Instructions: Save this file in any directory, Open your terminal or command prompt, go to that directory. Type "python battleship-game.py" # The game starts. User has to guess the Row (between 0 to 4) and Column (between 0 to 4). Total turns to guess = 4 # # from random import randint board = [] for x in range(5): board.append(["O"] * 5) # using repetition operator to create rows in list format def print_board(board): # function to print battleship board for row in board: print " ".join(row) # using join function to print rows in space delimited format print "Let's play Battleship!" print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col for turn in range(4): print "Turn", turn + 1 guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sunk my battleship!" break else: if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "Oops, that's not even in the ocean." elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." else: print "You missed my battleship!" board[guess_row][guess_col] = "X" # Print (turn + 1) here! print_board(board) if turn == 3: print "Game Over"
true
1407a634888c9b15bc130adbfdc779ab1597f3c4
gcgongchao/PythonBasic
/Basic8.py
1,050
4.25
4
#set可以被看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集,并集等操作 #set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变 #对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”. s=set([1,1,2,3,4,5,4,3,6]) print(s) s1=set([1,2,3]) s2=set([2,3,4]) print(s1&s2) print(s1|s2) #再议不可变对象:在Python中,对于不变对象来说,调用对象自身的任意方法,也不会改变该对象自身的内容。相反, #这些方法会创建新的对象并返回,这样,就保证了不可变对象本身永远是不可变的。 #使用key-value存储结构的dict在Python中非常有用,选择不可变对象作为Key很重要,最常用的Key是字符串. a=['c','b','a'] a.sort() print(a) a1='abc' b=a1.replace('a','A') print(b) print(a1) s1=set([1,2,(12,2,4)]) print(s1) s2=set([1,2,(3,4,[5,6])]) print(s2)
false
96a82268705e5e671d9e3e58dc8f8ce70b93ede8
vijaysawant/Python
/Nikhil/decoratorDemo.py
1,879
4.34375
4
""" PEP8 Simple rule - Function - syntax, args, kwargs, return types, return multiple values 1. Functions are first class objects - Can be passed as an argument to another Function - Can be returned from a Function - can be assigned to a variable - function can be nested 2. Decorator Given any string add header tag <h1> </h1> input : Welcome output : <h1> Welcome </h1> """ from functools import wraps def italic(original_func): @wraps(original_func) # Recommended if something depends on original function attributes, metadata def wrapped(employee_name): res = original_func(employee_name) return "<i>" + res + "</i>" return wrapped import time def timeit(original_func): @wraps(original_func) # Recommended if something depends on original function attributes, metadata def wrapped(employee_name): start = time.time() res = original_func(employee_name) end = time.time() - start print(f"finished in {end}") return res return wrapped def headify(original_func): @wraps(original_func) def wrapped(employee_name): res = original_func(employee_name) return "<h1>" + res + "</h1>" return wrapped @timeit @italic @headify # This is equivalen to : google_welcome = headify(google_welcome) def google_welcome(employee_name): time.sleep(2) return "Welcome " + employee_name + " to Google" @italic @headify # # This is equivalen to : amazon_welcome = headify(amazon_welcome) def amazon_welcome(employee_name): return "Welcome " + employee_name + " to Amazon" """ google_welcome = headify(google_welcome) google_welcome = italic(google_welcome) amazon_welcome = headify(amazon_welcome) amazon_welcome = italic(amazon_welcome) """ print(google_welcome.__name__) print(google_welcome("Vijay Sawant")) print(amazon_welcome("Sir Vijay Sawant")) # snap
true
8a3753e3d8c3f5835197bc7edf9fb45c0be8d65b
vijaysawant/Python
/Fun4_VariableNumOfArgs.py
457
4.25
4
# # Program to demonstrate concept of Variable Number of Arguments of user defined function # #! C:\Python\python.exe def fun(* var): print(type(var)) for x in var: print x fun(1,2,3) # passing numbers as arguments fun(["a","abc",3],5)# passing list and a number as arguments ''' Output- <type 'tuple'> 1 2 3 <type 'tuple'> ['a', 'abc', 3] 5 ''' # # Variable number of arguments contain * in function argument list #
true
f90b791f46e7c10d36e726dd8963e1fc29440492
vijaysawant/Python
/SpecialNumber.py
566
4.125
4
""" Program to check given number is special number or not. """ def CheckSpecialNumber(Num): sum = 0 facto = 0 originalNum = Num while Num >= 1: facto = findFactorial(int(Num % 10)) sum = sum + facto Num = Num / 10 if originalNum == sum: return 1 else: return 0 def findFactorial(Num): facto = 1 while Num: facto = facto * Num Num -= 1 return facto if __name__ == "__main__": Num = input("Enter Number : ") if CheckSpecialNumber(Num): print "Special Number" else: print "Not a special Number"
true
43133f157b042b89af60995af1c66fb8e5d3a418
vijaysawant/Python
/RE_Example1.py
1,050
4.15625
4
''' Wap to accept srch pattern, replace pattern and input string in which the search pattern is to be search and replace by replace pattern Hint - sub(), or subn() ''' import re """ def RE_Srch_And_Replace(srch_pattern, replace_pattern, input_string): return re.sub(srch_pattern, replace_pattern, input_string) def main(): input_string = input("Enter input string :") srch_pattern = input("Enter search pattern :") replace_pattern = input("Enter replace pattern :") print RE_Srch_And_Replace(srch_pattern, replace_pattern, input_string) if __name__ == "__main__": main() """ import re def RE_Srch_And_Replace(srch_pattern, replace_pattern, input_string,cnt): return re.sub(srch_pattern, replace_pattern, input_string,cnt) def main(): input_string = input("Enter input string :") srch_pattern = input("Enter search pattern :") replace_pattern = input("Enter replace pattern :") cnt = input("Enter replace count :") print RE_Srch_And_Replace(srch_pattern, replace_pattern, input_string,cnt) if __name__ == "__main__": main()
true
30782a27cfbe9352bc85f52258b4af4298625a8f
bormaley999/Udacity_Python_Intro
/scripting/udacity_46_python_intro.py
748
4.34375
4
# Udacity Intro to Python # Section 46 Quiz: Flying Circus Cast List """Write a function called create_cast_list that takes a filename as input and returns a list of actors' names. """ def create_cast_list(filename): cast_list = [] with open("flying_circus_cast.txt") as f: # use with to open the file filename for actor_name in f: # use the for loop syntax to process each line cast_list.append(actor_name.split(",")[0]) # and add the actor name to cast_list # name = line.split(",")[0] -> another solution # cast_list.append(name) -> another solution return cast_list cast_list = create_cast_list('flying_circus_cast.txt') for actor in cast_list: print(actor)
true
4eb38af98e5eb6ea0c327aaa144183e57fdc561c
bormaley999/Udacity_Python_Intro
/scripting/match_flower_name_1.py
894
4.15625
4
# Udacity Intro to Python # Section 50 Practice Question """ Question: 1. Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. 2. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. 3.It should then use it to print the flower name with the same first letter (from dictionary created in the first function). """ flowers_file = "flower.txt" flowers_list_dict = {} # define type first_letter = '' with open(flowers_file) as fp: for cnt, line in enumerate(fp): key = line[0] value = line.split(": ")[1] flowers_list_dict[key] = value def input_func(): name = str(input("First Name: ")) first_letter = name[0] dict_value = flowers_list_dict[first_letter] print(dict_value) input_func()
true
9bb49d8f2c8fdbf4d5f1f7d1fb01ecc510413458
bormaley999/Udacity_Python_Intro
/functions/udacity_37_python_intro.py
724
4.21875
4
# Udacity Intro to Python # Section 37 Quiz: Population Density Function """ Write a function named population_density that takes two arguments, population and land_area, and returns a population density calculated from those values """ # test cases for your function def population_density(population, land_area): return population/land_area def population_density(population, land_area): return population/land_area test1 = population_density(10, 1) expected_result1 = 10 print("expected result: {}, actual result: {}".format(expected_result1, test1)) test2 = population_density(864816, 121.4) expected_result2 = 7123.6902801 print("expected result: {}, actual result: {}".format(expected_result2, test2))
true
d23cf145e20335af380fc103dc24d37f8ec33d14
bosen365/PythonStudy
/oop/Flower.py
1,167
4.15625
4
# !/usr/bin/env python3 # -*- coding:utf-8 -*- '面向对象编程实例' __author__ = "click" import sys class Flower(object): # 变量前加上"__"表示该变量为私有变量,外部函数不能修改该变量的值 def __init__(self, color, name): self.__color = color self.__name = name def printFlower(self): print("Flower属性分别为 %s %s" % (self.__color, self.__name)) def getColor(self): return self.__color def setColor(self, color): self.__color = color; def setName(self, name): self.__name = name def getName(self): return self.__name if __name__ == '__main__': flower = Flower("绿色", "绿萝") # 以下代码无效 flower.__name = "hua" print("flower.__name->=" + flower.__name) # 为什么flower.name 打印为"化",而printFlower方法确实"绿萝"呢? 因为python解析器已经将对象的__name解释为_Student__name # 使用get set方法 # flower.setName("花花") flower.height = 10 flower.age = 2 flower.printFlower() print(hasattr(flower, "__name")) print(getattr(flower, "__name"))
false
91a2a033301e08b7e077a8d72be1b35ef9925a4a
kairoaraujo/STGAdm
/stgadm/fields.py
2,559
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re class Fields(object): """This class verify if the fields used is blank or contain spaces. Args: field (str): The filed variable, like 'name', 'change' etc... textfield (stg): The question for the field, like 'Whats de LPAR name', 'Whats the change number' etc . """ def __init__(self, field, textfield, variable=''): """Initial to get field and textField arguments. """ self.field = field self.textfield = textfield self.variable = variable def chkfieldstr(self): """Check field strings doesn't has a blank or spaces. """ while True: self.variable = raw_input('{0}'.format(self.textfield)) if ':' in self.variable: self.variable = self.variable.replace(':', '') if (self.variable.isspace()) or (self.variable == '') or \ (' ' in self.variable): print("{0}can not be blank or contain spaces.".format( self.textfield)) elif (self.variable[0].isdigit()) and (self.field == 'change'): print("{0}can not start with number.".format(self.textfield)) elif not re.match("^[A-Za-z0-9_]*$", self.variable): print("{0}can be only letters, numbers and _.".format( self.textfield)) else: break def strvarout(self): """Returns the answer to question field. """ return self.variable class YesNo(object): """A simple class to do questions and check the answer is y/n (yes or no). Args: question(str): The question do want to do like 'It is correct?'. answer(str): initial answer (default answer) y or n. """ def __init__(self, question, answer): """Get the args. """ self.question = question self.answer = answer def check(self): """Text menu to do question and check the answer. """ check_ok = 0 while check_ok == 0: self.answer = raw_input('{0}'.format(self.question)) if (self.answer == 'y') or (self.answer == 'Y'): self.answer = 'y' check_ok = 1 elif (self.answer == 'n') or (self.answer == 'N'): self.answer = 'n' check_ok = 1 else: print('Please use y or n!') check_ok = 0 return self.answer
true
59a98ee28be051144fc3482a825807b240182f6a
poonam197shukla/gitDemo
/stringsDemo.py
540
4.21875
4
#strings #string is actually a list in Python str1 ="poonam197shukla@gmail.com" str2="This is my email" str3="poonam" print(str1[0]) print(str1[0:6]) #concatenation in strings print(str1+str2) #to check if one string is present in another string or not(substring) print(str3 in str1) #splitting of string var=str1.split(".") print(var) print(var[0]) #to remove white spaces from string str4=" great " #print(str4.strip()) #to remove only left side white spaces #print(str4.lstrip()) #to remove only left side white spaces print(str4.rstrip())
true
8e88c1fbdda1e11551b2364b384d9fc8b5337270
poonam197shukla/gitDemo
/classesAndObjects.py
591
4.125
4
#classes and objects #let asssume below class as parent class class calculator: num=100 #default constructor def __init__(self,a,b): self.firstNumber=a self.secondNumber=b print("I am constructor") def addNewNumber(self): print("It is executing method inside class") def add(self): return self.firstNumber+self.secondNumber+calculator.num #creation of object one cal1=calculator(2,3) cal1.addNewNumber() print(cal1.add()) #print(cal1.num) #creation of object two cal2=calculator(4,5) #cal2.addNewNumber() #print(cal2.num)
true
2980fc940297b5c14683275939923f773366499d
ZAKERR/-16-python-
/软件第四次作业/软件161/张宇2016021159/README.txt
689
4.21875
4
#!/usr/bin/python #-*-coding:utf-8-*- #编写人:单明亮 #编写时间:20180927 #功能;计算器实现 def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("选择运算:") choice = input("输入你的选择(加/减/乘/除):") s = int(input("输入第一个数字: ")) m = int(input("输入第二个数字: ")) if choice == '加': print(s, "+", m, "=", add(s, m)) elif choice == '减': print(s, "-", m, "=", subtract(s, m)) elif choice == '乘': print(s, "*", m, "=", multiply(s, m)) elif choice == '除': print(s, "/", m, "=", divide(s, m))请上传代码和截图!
false
af76add1946aade31a36673599a3584c83261149
nathmelop/PythonDataScience
/Scripts - guanabara/comando.py
1,421
4.125
4
nome = input('Qual é o seu nome?') idade = input('Qual é a sua idade?') peso = input ('Qual é o seu peso?') print(nome, idade, peso) nome = input ('Qual é o seu nome?') print('Olá', nome , '! Prazer em te conhecer!') desafio 02 dia = input('Que dia você nasceu?') mes = input ('Que mês você nasceu?') ano = input ('Qual ano você nasceu?') print(dia,'/',mes,'/',ano) print('Você nasceu no dia', dia,'de', mes,'de',ano,'.Correto?') Desafio 03 numero = input('primeiro numero') numero2 = input('segundo numero') soma = int (numero) + int (numero2) print('A soma é ' + str (soma)) n1 =int(input('digite um valor:')) n2 =int(input('digite outro valor:')) s = n1 + n2 print('A soma vale', s) n1 =int(input('digite um valor:')) n2 =int(input('digite outro valor:')) s = n1 + n2 print('A soma entre',n1,'e',n2,'vale',s) print('A soma entre {} e {} vale {}'.format(n1,n2,s)) #tipo que coloca no comando n1 =float(input('digite um valor:')) print(type(n1)) Ordem de precendentes: 1 - () 2 - ** 3 - * / // % 4 - + - nome = input ('Qual é o seu nome?') print('Olá prazer em te conhecer {}!!'.format(nome)) num1 = int(input('Digite um valor:')) num2 = int(input('Digite outro valor:')) sum = num1 + num2 print('A soma entre {} e {} é igual a {} !!'.format(num1,num2,sum)) num1 = int(input('Digite um valor:')) num2 = int(input('Digite outro valor:')) print('A soma é {} !!'.format(num1+num2))
false
a0f61a01de78f5006e7bfa326fe0d3d407ccf94b
arvakagdi/UdacityNanodegree
/LinkedLists/AgeInDays2.py
2,787
4.25
4
'''Get the numebr of days between given dates''' def Leapyear (year): if year % 400 == 0: return 29 if year % 100 == 0: return 28 if year % 4 == 0: return 29 else: return 28 def DaysInMonth (month,year): list31 = [1, 3, 5, 7, 8, 10, 12] list30 = [4, 6, 9, 11] if month in list31: return 31 elif month in list30: return 30 else: return Leapyear(year) def nextDay(year, month, day): if day != DaysInMonth(month,year): return (year, month, day + 1) else: if month != 12: return (year, month + 1, 1) else: return (year + 1, 1, 1) def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: return day1 < day2 return False def daysBetweenDates(year1, month1, day1, year2, month2, day2): assert not dateIsBefore(year2, month2, day2, year1, month1, day1) days = 0 while dateIsBefore(year1, month1, day1, year2, month2, day2): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days print (daysBetweenDates(1900, 1, 1, 1999, 12, 31)) '''Test Stubs''' def test(): test_cases = [((2012, 1, 1, 2012, 2, 28), 58), ((2012, 1, 1, 2012, 3, 1), 60), ((2011, 6, 30, 2012, 6, 30), 366), ((2011, 1, 1, 2012, 8, 8), 585), ((1900, 1, 1, 1999, 12, 31), 36523), ((2012,2,28,2012,2,29),1), ((2012, 1, 1, 2013, 1, 1), 366), ((2013, 1, 24, 2013, 6, 29), 156)] # for (args, answer) in test_cases: # result = daysBetweenDates(*args) # if result != answer: # print ("Test with data:", args, "failed") # else: # print("Test case passed!") for (args,ans) in test_cases: test = daysBetweenDates(*args) if test == ans: print("Test Passed") else: print ("Test case:", args, " failed with answer:", test, "expected answer:", ans) assert nextDay(2013,1,1) == (2013,1,2) assert nextDay(2013,2,28) == (2013,3,1) assert nextDay(2012,12,31) == (2013,1,1) print(Leapyear(1900)) print(Leapyear(2012)) print(Leapyear(2013)) assert dateIsBefore(1900,1,1, 2019,2,4) == True assert dateIsBefore(1909,3,1,1909,3,31) == True assert dateIsBefore(1909,2,31, 1909,2,1) == False test()
false
de5f5690a805fb079f96c3bb70f1fbfc5c0caeb3
VFEUVRAY/TrainingPython
/42AI/md00/ex03/count.py
933
4.125
4
def text_analyser(text : str, *args): """text_analyser(text : str): Parameters: text (str): text you want to be analysed prints various informations about text passed as argument: number of lowercase letter, number of uppercase letters, number of spaces, number of punctuation characters """ if (len(args)): print("ERROR") return lowerCount = 0 upperCount = 0 punctCount = 0 spaceCount = 0 for c in text: if (c.isupper()): upperCount += 1 elif (c.islower()): lowerCount += 1 elif (c.isspace()): spaceCount += 1 elif (c.isprintable() and not c.isalnum()): punctCount += 1 print(text) print("- ", upperCount," upper letters") print("- ", lowerCount," lower letters") print("- ", spaceCount," spaces") print("- ", punctCount," punctuation marks")
true
1dd9650219fdd467aa1ac562100e6e670a5a6a66
rosomaxa/interviews
/strings/decode_string.py
2,268
4.15625
4
"""Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Examples: s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef". """ class Solution(object): def decodeString(self, s): stack = [] current_num = 0 current_str = '' for ch in s: if ch == '[': stack.append(current_str) stack.append(current_num) current_str = '' current_num = 0 elif ch == ']': prev_num = stack.pop() prev_str = stack.pop() current_str = prev_str + prev_num * current_str elif ch.isdigit(): current_num += current_num * 10 + int(ch) else: current_str += ch return current_str def decodeString1(self, s): """ :type s: str :rtype: str """ stack = [[1, '']] start = 0 while start < len(s): this_char = s[start] if '0' <= this_char <= '9': digit_end = start while '0' <= s[digit_end] <= '9': digit_end += 1 stack += [[int(s[start:digit_end]), '']] start = digit_end elif this_char == ']': digit, str_ = stack.pop() stack[-1][1] += str_ * digit else:sentence-screen-fitting stack[-1][1] += this_char start += 1 return stack[-1][1] if __name__ == '__main__': assert Solution().decodeString('3[a]2[bc]') == 'aaabcbc' assert Solution().decodeString('3[a2[c]]') == 'accaccacc' assert Solution().decodeString('2[abc]3[cd]ef') == 'abcabccdcdcdef'
true
2b6a99e9ca658e6f1cc574e56292dd95a63adb96
mattmiller87/practice
/Kirk_Byers_python_for_network_engineers/week2/week2exercise1.py
1,605
4.1875
4
''' I. Create a script that does the following A. Prompts the user to input an IP network. Notes: 1. For simplicity the network is always assumed to be a /24 network 2. The network can be entered in using one of the following three formats 10.88.17.0, 10.88.17., or 10.88.17 B. Regardless of which of the three formats is used, store this IP network as a list in the following format ['10', '88', '17', '0'] i.e. a list with four octets (all strings), the last octet is always zero (a string). Hint: There is a way you can accomplish this using a list slice. Hint2: If you can't solve this question with a list slice, then try using the below if statement (note, we haven't discussed if/else conditionals yet; we will talk about them in the next class). if len(octets) == 3: octets.append('0') elif len(octets) == 4: octets[3] = '0' C. Print the IP network out to the screen. D. Print a table that looks like the following (columns 20 characters in width): NETWORK_NUMBER FIRST_OCTET_BINARY FIRST_OCTET_HEX 88.19.107.0 0b1011000 0x58 ''' ip_addr = raw_input("Please enter an IP address: ") print "The IP Address you entered is: " + ip_addr ip_parts = ip_addr.split(".") ip_parts[3] = "0" ip_fix = ".".join(ip_parts) first_octet_binary = bin(int(ip_parts[0])) first_octet_hex = hex(int(ip_parts[0])) print "%-20s %-20s %-20s" % ("NETWORK_NUMBER","FIRST_OCTET_BINARY","FIRST_OCTET_HEX") print "%-20s %-20s %-20s" % (ip_fix,first_octet_binary,first_octet_hex)
true
7c0938af0cf47653a4c4c5abcd32f90c821c57dc
israelmessias/Calculator
/main.py
1,988
4.21875
4
from calculator import Calculation #I imported the calculation class import os calc = Calculation() #name given to Calculator class continued = ('s','n', 'S', 'N') #tupla criada que tenha a opção de recomeçar ou quebrar while True: operation = int(input("\t\tEscolha a operação:\n\t1 - (Soma) 2 - (Subtração) 3 - (Multiplicação)\n\t4 - (Divisão) 5 - (Potenciação) 6 - (Radiação) \n\n\t\t")) while operation > 6: #if the whole number is greater than 6 print("Tente novamente D;\n\n") break else: #if the integers are less than or equal to 6, you will be given two options of numbers you want to calculate num1 = float(input("Digite o primeiro numero: ")) num2 = float(input("Digite o segundo numero: ")) if operation == 1: result = calc.addition(num1, num2) print("O resultado da soma é: ", result) elif operation == 2: result = calc.subtraction(num1, num2) print("O resultado de subtração é: ", result) elif operation == 3: result = calc.multiplication(num1, num2) print("O resultado da multiplicação: ", result) elif operation == 4: result = calc.division(num1, num2) print("O resultado da divisão é: ", result) elif operation == 5: result = calc.potentiation(num1, num2) print("O resultado da potenciação: ", result) elif operation == 6: result = calc.radiation(num1) print("O resultado da radiação é: ", result) continued = str(input("Deseja continua? [s/n]\n ")) if continued == 's' or continued == 'S': continue elif continued == 'n' or continued == 'N': print("Até mais (:") break else: print("Opção invalida!") continued = str(input("\tDeseja continua? [s/n]\n "))
false
d4389298fdc63684d692d1e1c6c90b63f18d91fc
vinodhmj/projects
/python/twinprime.py
1,413
4.5
4
#!/usr/bin/env python3 #---------------------------------------------------------------------------- # Created By : V. Jayakrishnan # Created Date: # version ='1.0' #---------------------------------------------------------------------------- def isPrime(num): """Check if the number is prime""" if num> 1: for n in range(2,num): if (num % n) == 0: return False return True else: return False #---------------------------------------------------------------------------- def twinPrime(num): """Function returns the largest twin prime number p, for p<=n""" # https://en.wikipedia.org/wiki/Twin_prime output = None; # Loop backwards from the incoming number to reach 2 for value in range(num, 2, -1): if isPrime(value) and (isPrime(value+2) or isPrime(value-2)): output = int(value); break return output #---------------------------------------------------------------------------- def main(): # test twinPrime method assert twinPrime(1) == None assert twinPrime(50) == 43 # print the results print("Twin prime of 1: ",twinPrime(1)) print("Twin prime of 50: ", twinPrime(50)) #---------------------------------------------------------------------------- # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
true
f3e2b81b7a3c9baccb120bddab45dea0c6632c56
bagaki/Python
/Full Stack/day22/day22面向对象练习.py
1,402
4.25
4
# 非常明显的处理一类事物,这些事物都具有相似的属性和功能 # 当有几个函数,需要反反复复传入相同的参数的时候,就可以考虑面向对象 # 这些参数都是对象的属性 # 小明, 10岁, 男, 上山去砍柴 class Person(object): """docstring for Person""" def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def doSomething(self): print('{},{}岁,{},砍柴'.format(self.name, self.age, self.sex)) # circle 属性 半径 两个方法:求周长和面积 # 2pir pir**2 from math import pi class Circle(object): def __init__(self, r): self.r = r def area(self): return pi*(self.r**2) def perimeter(self): return 2*pi*self.r c1 = Circle(5) print(c1.area()) print(c1.perimeter()) # 定义类 # init方法 # self是什么 self拥有属性都属于对象 # 类中可以定义静态属性 # 类中可以定义方法,方法都有一个必须传的参数self # 实例化 # 示例、对象 # 对象查看属性 # 对象调用方法 # 正方形 周长和面积 class Squir(object): def __init__(self, a): self.a = a def area(self): return self.a * self.a def perimeter(self): return self.a * 4 squir = Squir(9) area1 = squir.area() per1 = squir.perimeter() print(area1, per1) # 完成人狗大战 # 默写 交互文件
false
a5a7be35f1c7a16470344be2eac3ad03d96a2170
bagaki/Python
/Full Stack/day55/day55今日面试题.py
868
4.15625
4
""" 问 字符串格式化:%和format 有什么区别 Python新版本推荐使用format. python2.6 新加入的format语法支持 3.6新特性: f-string f"{name} is {age}" """ c = (250, 250) command1 = "向它开炮:%s" % (c,) print(command1) command2 = "向它开炮:{}".format(c) print(command2) print(f"向它开炮:{c}") class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "{self.name} is {self.age} years old".format(self=self) p1 = Person("Alex", 9000) print(p1) date = [11, 22] print("{0[0]} -- {0[1]}".format(date)) print("{:>10}".format(19)) print("{:0>10}".format(19)) print("{:s>10}".format(19)) # zfill print("18".zfill(10)) print("{:.2f}".format(3.1415926)) print("{:,}".format(3442398329))
false
d9e25a2e70c60347bee80e7455e7a0ad5258910b
fernaspiazu/python-codecademy
/bitwise_operators/or_bitwise.py
626
4.21875
4
__author__ = 'fumandito' """ A BIT of This OR That The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1. For example: a: 00101010 42 b: 00001111 15 ================ a | b: 00101111 47 Note that the bitwise | operator can only create results that are greater than or equal to the larger of the two integer inputs. So remember, for every given bit in a and b: 0 | 0 = 0 0 | 1 = 1 1 | 0 = 1 1 | 1 = 1 Meaning 110 (6) | 1010 (10) = 1110 (14) """ print bin(0b1110 | 0b101)
true
928f956ac229a7e5cdd3cb1c1fc7268c9152e79c
fernaspiazu/python-codecademy
/advanced/list_comprehension.py
649
4.125
4
__author__ = 'fumandito' # Create list with even numbers from 0 to 50 evens_to_50 = [i for i in range(51) if i % 2 == 0] print evens_to_50 doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0] # even_squares list should include the squares of the even numbers between 1 to 11. # Your list should start [4, 16, 36...] and go from there. even_squares = [x ** 2 for x in range(1, 12) if (x ** 2) % 2 == 0] print even_squares # The comprehension should consist of the cubes of the numbers 1 through 10 # only if the cube is evenly divisible by four. cubes_by_four = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0] print cubes_by_four
true
dd53a72fb100cb6059b451f298c7f17b6ea3bb6d
fernaspiazu/python-codecademy
/exercises/anti_vowel.py
260
4.125
4
__author__ = 'fumandito' def anti_vowel(text): final_text = "" vowels = ['a', 'e', 'i', 'o', 'u'] for letter in text: if letter.lower() not in vowels: final_text += letter return final_text print anti_vowel("Hey you!")
false
2828cabed16bf817f28d8fb06741c95b1c1d4710
Syntactical01/python-scripts
/get_max_quantity.py
1,137
4.1875
4
# Given a max budget give the biggest quantity we can get for that budget # Solution uses bisect's binary search # Log(n) solution where `n` is of `sys.maxsize`. import sys import bisect class Search(): def __init__(self, get_cost): self.get_cost = get_cost def __getitem__(self, quantity): # index is the quantity """ Implement [] for this class. When bisect calls, this returns the cost for the given index. """ return self.get_cost(quantity) def __len__(self): """ bisect uses len() as one of its first calls, so we will say the maximum quantity size will be the max int size for the system the script runs on. """ return sys.maxsize def get_cost_func(quantity): return quantity**2 + 3 * quantity + 100 budget = 1358841213 # bisect.bisect returns where an item should be inserted, # bit we want the value right before that insertion point # which is why we do -1 max_quantity = bisect.bisect(Search(get_cost_func), budget) - 1 print(get_cost_func(max_quantity), budget, get_cost_func(max_quantity + 1))
true
25b11f4ab0b84ac99f44a76fdd03fc31b47ed333
imagelee/fluent_python
/decorators_closures/registration.py
524
4.1875
4
registry = [] """ 1. A real decorator is usually defined in one module and applied to functions in other modules. 2. In practice, most decorators define an inner function and return it. """ def register(func): print('register(%s)' % func) registry.append(func) return func @register def f1(): print('f1') @register def f2(): print('f2') def f3(): print('f3') def main(): print('main') print('registry ->', registry) f1() f2() f3() if __name__ == '__main__': main()
true
2069c9102683b3b7df7f14cb4863b2488eab48b5
MrRossMBAS/LearnArcade
/Resources/Feelings Menu/feelings_menu_template_with_loop.py
1,927
4.4375
4
# This is the feelings menu exemplar. # # https://drive.google.com/drive/folders/1tD1FfW9UpQc-_9hjIiFpSaZiscEaCtbv # # Output a welcome message. print() print("############################") print("# #") print("# QUOTES FOR YOUR FEELINGS #") print("# #") print("############################") print() print("Welcome. You tell me how you are feeling and I will give you a quote.") print() # We set this to True. As long as it is true we run the next loop. # To stop the loop we just set this to False. run_feelings = True # Starting the loop. while run_feelings: # We could also use while run_feelings == True. while run_feelings is shorter! print("You can choose from the following list of feelings. Which one best matches your mood right now?") print() # Output a feeling print("A: I feel really happy.") print("B: I feel really sad.") print("C: I feel a bit worried.") print("D: I feel excited.") print("Q: To quit.") print() # Output instructions print("Enter the letter that corresponds the most closely to how you feel.") # Creates a variable called feeling that stores the users input. # Notice the space. It's important. feeling = input("Choose a feeling from the options (A, B, C, D) or Q to quit: ") # Process the user input and respond. if feeling == "A": print() print("You can destroy your now, by worrying about tomorrow.") print() print("Janis Joplin") print() if feeling == "A": # This is for worry print() print("You can destroy your now, by worrying about tomorrow.") print() print("Janis Joplin") print() elif feeling == "Q": print("OK, it was fun while it lasted.") # Stop the loop run_feelings = False else: print("I don't understand.")
true
d3ae227f721a9fcd50e8134eeeb8391fc8557f46
ChloeRuan/HelloWorld
/app016.py
303
4.125
4
""" # nested loop in python # what coordinates? (x, y). (0.0) for x in range (4): for y in range (3): print(f'({x}, {y})') """ # exercise,, print a 'F' numbers = [5, 2, 5, 2, 2] for x_count in numbers: output = '' for count in range(x_count): output += 'x' print(output)
false
a878bcba2c4bc6b2bf9c737ff69133e846a04a58
ChloeRuan/HelloWorld
/app004.py
459
4.125
4
course = "python's course for Beginners" course = 'python course for "Beginners"' print(course) course = ''' Hi John, test Thank you, The support team ''' print(course) course = 'python for Beginners' print(course[0]) # this is index, if run, it shows P print(course[-1]) # the last character from the end print(course[-2]) print(course[0:3]) # get the index from 1st to 3rd another = course[:] biyi = ''' Gorgeous, Angel Forever ''' print(biyi)
true
34b802706be11d34237746ae50a03404c40bee10
k2khan/CS1300
/Chapter_02/In-class/Problem7.py
433
4.1875
4
# Find the distance between two points x1 = float(input("What is the x coordinate of the first point? ")) y1 = float(input("What is the y coordinate of the first point? ")) x2 = float(input("What is the x coordinate of the second point? ")) y2 = float(input("What is the y coordinate of the second point? ")) distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 print("The distance between the two points is", str(distance) + ".")
true
3d82758a540c309f906479932bd7a411f1432835
evmiguel/udacity_ds_algo
/P0/Task1.py
974
4.1875
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 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ # Algorithm: # For each in (sending texts, receiving texts, sending calls, receiving calls) # add to set # return set length phone_number_set = set() # Add the numbers from sending and receiving text for line in texts: phone_number_set.add(line[0]) phone_number_set.add(line[1]) # Add the numbers from sending and receiving calls for line in calls: phone_number_set.add(line[0]) phone_number_set.add(line[1]) print("There are {0} different telephone numbers in the records.".format(len(phone_number_set)))
true
c300760f35d788a9e3beb351eae46e53f612cb19
evmiguel/udacity_ds_algo
/Problems_vs_Algorithms/problem1.py
1,003
4.375
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ assert number > -1 if isinstance(number, float): number = int(number) left = 0 right = number while left < right: mid = (left + right)//2 if mid*mid > number: right = mid - 1 elif mid*mid < number: left = mid + 1 else: return mid return left # Test integers print ("Pass" if (3 == sqrt(9)) else "Fail") # Pass print ("Pass" if (0 == sqrt(0)) else "Fail") # Pass print ("Pass" if (4 == sqrt(16)) else "Fail") # Pass print ("Pass" if (1 == sqrt(1)) else "Fail") # Pass print ("Pass" if (5 == sqrt(27)) else "Fail") # Pass print ("Pass" if (5 == sqrt(27)) else "Fail") # Pass # Test float print ("Pass" if (1 == sqrt(1.1)) else "Fail") # Pass try: sqrt(-1) except AssertionError: pass
true
cb0d0f408d99c74d6b927bc71bcdcd7b19d9e535
Nicolasopf/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
1,256
4.1875
4
#!/usr/bin/python3 """ class Square that inherits from Rectangle """ from models.rectangle import Rectangle class Square(Rectangle): """ Class Square is expected to print a square. I hope reach the goal. """ def __init__(self, size, x=0, y=0, id=None): """ Superman """ super().__init__(size, size, x, y, id) @property def size(self): """ Return the width """ return self.width @size.setter def size(self, size): """ Set the size of width and height """ self.width = size self.height = size def __str__(self): """ Prints the strings """ i1 = '(' + str(self.id) + ') ' + str(self.x) + '/' i2 = str(self.y) + ' - ' + str(self.width) return "[Square] " + i1 + i2 def update(self, *args, **kwargs): """ Update the values """ dic = ['id', 'size', 'x', 'y'] if args and args[0] is not None: for i in range(len(args)): setattr(self, dic[i], args[i]) else: for k in kwargs: setattr(self, k, kwargs[k]) def to_dictionary(self): """ Return a dic """ return {'id': self.id, 'size': self.width, 'x': self.x, 'y': self.y}
true
2b8e4e704e7e47e05af6bd313802b88996b78365
luckydimdim/bobel-algo
/python/anagrams/index.py
1,364
4.15625
4
import re from pprint import pprint # --- Description # Check to see if two provided strings are anagrams of eachother. # One string is an anagram of another if it uses the same characters # in the same quantity. Only consider characters, not spaces # or punctuation. Consider capital letters to be the same as lower case # # --- Examples # anagrams('rail safety', 'fairy tales') --> True # anagrams('RAIL! SAFETY!', 'fairy tales') --> True # anagrams('Hi there', 'Bye there') --> False def anagrams1(a, b): mapA = str_to_map(a) mapB = str_to_map(b) if len(mapA.keys()) != len(mapB.keys()): return False for letter, count in mapA.items(): if not letter in mapB: return False if count != mapB[letter]: return False return True def str_to_map(value): result = {} value = value.lower() value = re.sub("\W", "", value) for char in value: if not char in result: result.update({char: 1}) else: result[char] += 1 return result def anagrams(a, b): normalizedA = sorted(re.sub("\W", "", a.lower())) normalizedB = sorted(re.sub("\W", "", b.lower())) return normalizedA == normalizedB print(anagrams('a b!c', 'B c~a!')) normalizedA = sorted(re.sub("\W", "", 'a b!c'.lower())) b = ['a', 'b', 'c'] pprint(normalizedA)
true
dd7a0f583a28740deb31caf4f969a20a2fff5eb5
angelineflorajohn/basic-python-coding-problems
/regularPolygon.py
995
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 14 19:08:26 2019 @author: angelineflorajohn """ ''' A regular polygon has n number of sides. Each side has length s. The area of a regular polygon is: (0.25 * n * s**2) / tan(pi/n) The perimeter of a polygon is: length of the boundary of the polygon Write a function called polysum that takes 2 arguments, n and s. This function should sum the area and square of the perimeter of the regular polygon. The function returns the sum, rounded to 4 decimal places. ''' import math # math library contains the functions to perform mathematical functions def polysum(n, s): ''' Input: n is the number of sides of a regular polygon ,s is the length of the side of the polygon Output: adding the area and square of the perimeter of the regular polygon rounded to 4 decimal places ''' area = (0.25 * n * s**2) / math.tan(math.pi/n) perimeter = n * s return round(area + perimeter**2, 4)
true