blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2fb8ce9f6ce719f4903127076c9582db1bab1034
django-group/python-itvdn
/домашка/starter/lesson 3/Alex_Osmolowski/FuncValue.py
228
4.125
4
import math x = input("Введите значение Х: ") x = float(x) if - math.pi <= x <= math.pi: y = math.cos(3*x) print("y = Cos(3x) = {}".format(y)) else: y = x print("y = x = {}".format(y))
false
21dda200a1ad54a3facb2892e4646967c87da327
django-group/python-itvdn
/домашка/starter/lesson 6/Marukhniak Denys/Lesson_6_4.py
435
4.25
4
# Задание # Напишите рекурсивную функцию, которая вычисляет сумму натуральных чисел, которые # входят в заданный промежуток. def foo(a, b, res): res += a a += 1 if a <= b: return foo(a, b, res) else: return res # a = int(input('From ')) # b = int(input('to ')) a = 3 b = 5 print(foo(a, b, res=0))
false
a35eb6b937034d3addc77726a50ac29e742c6820
django-group/python-itvdn
/домашка/essential/lesson 3/Dmytro Marianchenko/t_2.py
1,753
4.1875
4
def operations(a, b): """ Operations with input numbers """ while True: operation = input("What operation do you need:\n1. If add enter '+' \n2. If subtract enter '-' \n3. If " "multiplication enter '*' \n4. If division enter '/'\n5. If exponentiation enter '^' \n>> ") if operation == "+": r = a + b return r elif operation == "-": r = a - b return r elif operation == "*": r = a * b return r elif operation == "/": try: r = a / b return r except ZeroDivisionError: r = "no result" return r elif operation == "^": try: r = a ** b return r except ZeroDivisionError: r = "no result" return r else: print("Wrong operation choice... try again") def inp_nums(x): """ Rule of initialisation inserted number """ while x is None: try: x = float(input("enter a number:\n>> ")) except ValueError: print("It is not a number... try again") return x def main(): """ Main program """ num1 = None num2 = None num1 = inp_nums(num1) print("and second number") num2 = inp_nums(num2) result = operations(num1, num2) result_end = result % 1 if result_end == 0: print(round(result)) else: print(result) to_do = input("If you want to continue press 'Enter' or input 'exit':\n>> ") if to_do == exit: exit() else: main() if __name__ == '__main__': main()
false
2c9b58064ab9e14745f8be10ad96b7e98af65911
django-group/python-itvdn
/домашка/starter/lesson 5/Alex_Osmolowski/hw_5_add.py
1,234
4.375
4
# Создайте программу, которая состоит из функции, которая принимает три числа и возвращает # их среднее арифметическое, и главного цикла, спрашивающего у пользователя числа и # вычисляющего их средние значения при помощи созданной функции. def average3(x1, x2, x3): return (x1 + x2 + x3)/3 def main(): while True: op = input("Введите опреацию: ") if op.lower() == "exit": # выход return elif op == "avg": # среднее арифметическое трёх чисел x1 = input("Введите первое число x1 = ") x1 = float(x1) x2 = input("Введите второе число x2 = ") x2 = float(x2) x3 = input("Введите третье число x3 = ") x3 = float(x3) print("Среднее арифметическое трёх введённых чисел: {}".format(average3(x1, x2, x3))) if __name__ == '__main__': main()
false
85cc9e7571335011818b5c12d4e06c0e74e0e2ff
django-group/python-itvdn
/домашка/starter/lesson 6/Dmytro Marianchenko/t_2.py
680
4.25
4
#это еще один способ кроме [::-1}, но правда сложнее, но еще один вариант))) def palindrome(word="mom"): if len(word) == 3: if word[0] == word[2]: print(f"Слово '{word}' полиндром") else: print(f"Слово '{word}' не полиндром") elif word[0] == word[-1] and palindrome(word[1:-1]): print(f"Слово '{word}' это полиндром =)") else: print(f"Слово '{word}' не полиндром") word = input("Введи сло и я попробую угадать полиндром это или неи: ") palindrome(word)
false
a8c74c5a2cdfdbbf43de4fda2580bb87fc5694af
django-group/python-itvdn
/домашка/starter/lesson 5/Vitalii_K/foo_calc(task3).py
1,746
4.1875
4
def calc_add(a, b): return a + b def calc_sub(a, b): return a - b def calc_mult(a, b): return a * b def calc_div(a, b): if b != 0: return a / b else: return "Divisor must not be zero! OBVIOUSLY!" while True: print("Enter '1' if u want to calculate.", "Enter '0' if u want to exit.", sep='\n') j = input() if j == "1": op = input("Enter operation ('+', '-', '*', '/'): ") if op != "+" and op != "-" and op != "*" and op != "/": print("Read the parentheses part, plese...") else: x = input("Enter the number: ") try: x = float(x) except ValueError: print("You wanna try to calculate things other than numbers?" "\nNot on my watch!") continue x = round(x) y = input("Enter the number: ") try: y = float(y) except ValueError: print("You wanna try to calculate things other than numbers?" "\nNot on my watch!") continue y = round(y) if op == "+": print(f"{x} + {y} = {calc_add(x, y)}") elif op == "-": print(f"{x} - {y} = {calc_sub(x, y)}") elif op == "*": print(f"{x} * {y} = {calc_mult(x, y)}") elif op == "/": if y != 0: print(f"{x} / {y} = {calc_div(x, y)}") else: print(calc_div(x, y)) elif j == "0": break else: print("It is a simple choise...\nDon’t overcomplicate things...") input("Oh boy, that escalated quickly...")
true
ec6ab23e48d0e8c6d838e7a04dbb55e232f4a922
django-group/python-itvdn
/домашка/essential/lesson 1/MaximKologrimov/Task Dop.py
1,250
4.53125
5
# Задание # Создайте класс, описывающий автомобиль. Создайте класс автосалона, содержащий в себе список # автомобилей, доступных для продажи, и функцию продажи заданного автомобиля. class Cars: def __init__(self, car_new, color_new, maxspeed_new): self.car = car_new self.color = color_new self.maxspeed = maxspeed_new def __str__(self): return f'Марка Авто: {self.car}\n' \ f'Цвет: {self.color}\n' \ f'Максимальная скорость: {self.maxspeed}' def __repr__(self): return f'Марка Авто: {self.car}; ' \ f'Цвет: {self.color}; ' \ f'Максимальная скорость: {self.maxspeed}' car1 = Cars('Ford', 'Black', 320) car2 = Cars('Mazda', 'Red', 240) print(car1) print() print(car2) print() class Market(): def price(self, price_new): self.price = price_new p1 = Market() p1.price(30000) p2 = Market() p2.price(20000) list = [car1.car, p1.price, car2.car, p2.price] print(list)
false
be5efa14fb63149c56ab803accce47330f5ae671
django-group/python-itvdn
/домашка/starter/lesson 3/Dmytro Marianchenko/t_2.py
293
4.25
4
import math print("Введите значение 'x':") x = int(input("")) if -math.pi <= x <=math.pi: y = math.cos(3*x) print(f"Ответ: {y}") elif x < -math.pi or x > math.pi: y = x print(f"Ответ: {y}") input("Для завершения нажмите 'Enter'...")
false
a36704f61931057f842ba2cb0bc2a2d0b77dd7d8
django-group/python-itvdn
/домашка/starter/lesson 3/Dmytro Marianchenko/t_4.py
1,596
4.1875
4
import math print("Выберите пожалуйста НОМЕР МЕНЮ необходимой операции:") print("1. '+'","2. '-'","3. '*'","4. '/'","5. '%'","6. Площадь круга", sep="\n") oper = input("") if oper == "1": #сложение print("введите первое число:") x = int(input("")) y = int(input("")) print(f"Ответ: {x + y}") elif oper == "2": #разница print("введите первое число:") x = int(input("")) y = int(input("")) print(f"Ответ: {x - y}") elif oper == "3": #умножение print("введите первое число:") x = int(input("")) y = int(input("")) print(f"Ответ: {x * y}") elif oper == "4": #деление print("введите первое число:") x = int(input("")) y = int(input("")) print(f"Ответ: {x / y}") elif oper == "5": print("введите число от которого необходимо высчитать процент:") x = int(input("")) print("введите количество процентов в целым числом:") y = int(input("")) pers = x*(y/100) print(f"Ответ: {round(pers,2)}") elif oper == "6": print("введите радиус:") r = int(input("")) s = math.pi*(r**2) print(f"Ответ: {round(s,2)}") else: print(f"операция {oper}, при необходимости появится в следующей версии =)") print("Для завершения нажмите кнопку 'Enter'...")
false
21f9f280ef5d788c64b929a14ca1c1fc739016cf
django-group/python-itvdn
/домашка/starter/lesson 6/MaximKologrimov/Task 1.py
1,685
4.1875
4
# Задание 1 # Прочитайте в документации по языку Python информацию о перечисленных в резюме данного # урока стандартных функциях. Проверьте их на практике. def foo(a): """ Задание 1 Прочитайте в документации по языку Python информацию о перечисленных в резюме данного урока стандартных функциях. Проверьте их на практике. """ a += 1 return a x = 5 y = -5 real = -7 imag = 7 z = 7.1234567 s = 'Abraham' print('abs(x) =', abs(x)) print('bin(x) =', bin(x)) print('bool(x) =', bool(x)) print('callable(f) =', callable(foo), callable(x)) print('chr(code) =', chr(1052)) print('complex(real, imag) =', complex(real, imag)) print('dir(obj) =', dir(print)) print('float(x) =', float(x)) print('format(x, fmt) =', '{}, {}'.format(y, x)) print('help(obj) =', help(print)) print('hex(x) =', hex(x)) print('id(obj) =', id(foo)) #input('who are you?') print('int(x) =', int(x)) print('len(s)', len(s)) print('max(arg1, arg2, …) =', max(2, 77, 10)) print('min(arg1, arg2, …) =', min(2, 77, 10)) print('oct(x) =', oct(x)) print('ord(c) =', ord('m')) print('pow(x, n) =', pow(x, imag)) print('print()') print('range() =', min(range(77)),',', max(range(77))) print('repr(obj) =', repr(help)) print('reversed(iterable):', list(reversed(s))) for i in reversed(range(7)): print(i) print('round(number, ndigits) =', round(z,2)) print('sorted(iterable) =', sorted(s)) print('str(x) =', type(str(x)), type(x)) print(foo.__doc__)
false
1620a9cd97e0d9940eddad7852d682c54c4e8e51
django-group/python-itvdn
/домашка/starter/lesson 7/Marukhniak Denys/Lesson_7_4.py
482
4.34375
4
# Создайте список, введите количество его элементов и сами значения, выведите эти значения на # экран в обратном порядке. cloud = [] element = 0 length = int(input('Enter length of list: ')) for i in range(length): element = input(f'Enter {i+1} element of list: ') cloud.append(element) print('Your list with reversed elements:') for i in cloud[::-1]: print(i, end=' ')
false
eaa903dfea9fdb6184ce351ea87798c906504fec
django-group/python-itvdn
/домашка/starter/lesson 5/Marukhniak Denys/Lesson_5_2.py
514
4.21875
4
# Задание 2 # Создайте две функции, вычисляющие значения определённых алгебраических выражений. # Выведите на экран таблицу значений этих функций от -5 до 5 с шагом 0.5. def f1(x1=-5): y = x1 ** 2 return y def f2(x2=-5): y = 1-x return y x = -5 print(f" x | y=x^2 | y=1-x") while x < 5: x += 0.5 print('{} | {:4.2f} | {:4.2f}'.format(x, f1(x), f2(x)))
false
8132d6fb46f2ee1b9edafe88addf3394289d88b5
django-group/python-itvdn
/домашка/starter/lesson 4/KologrimovMaxim/Task dop.py
423
4.3125
4
#Задание #Создайте программу, которая рисует на экране прямоугольник из звёздочек заданной #пользователем ширины и высоты. x = int(input('Введите высоту: ')) y = int(input('Введите ширину: ')) print() for h in range(x): for w in range(y): print('*', end='') print()
false
b7984b9952e622516e17766668f8401c787fe308
ericjiang107/Practice-Questions
/PermutationString.py
1,256
4.1875
4
''' Problem Challenge: Permutation in a String (hard) Given a string and a pattern, find out if the string contains any permutation of the pattern. Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations: abc acb bac bca cab cba If a string has ‘n’ distinct characters it will have n!n! permutations. Example 1: Input: String="oidbcaf", Pattern="abc" Output: true Explanation: The string contains "bca" which is a permutation of the given pattern. Example 2: Input: String="odicf", Pattern="dc" Output: false Explanation: No permutation of the pattern is present in the given string as a substring. Example 3: Input: String="bcdxabcdy", Pattern="bcdyabcdx" Output: true Explanation: Both the string and the pattern are a permutation of each other. Example 4: Input: String="aaacb", Pattern="abc" Output: true Explanation: The string contains "acb" which is a permutation of the given pattern. ''' def permutation(String, Pattern): empty_dic = {} window_start = 0 match = 0 for letter in range(len(String)): if String[letter] not in empty_dic: empty_dic[String[letter]] = 1 else: empty_dic[String[letter]] += 1
true
d98b6ee393e45ef9c6919442fe362f84e2e2024e
CoolM0nk3y/Functions
/pay.py
1,022
4.15625
4
#calculate basic pay def calculate_basic_pay(hours,rate): total = hours * rate return total #calculate the over time pay def calculate_overtime(hours,rate): over_time = hours - 40 basic_pay = 40 * rate overtime_pay = over_time * rate * 1.5 total = overtime_pay + basic_pay return total # the statment def calculate_total_pay(hours,rate): if hours <= 40: total = calculate_basic_pay(hours,rate) else: total = calculate_overtime(hours,rate) return total # Get the data from the user def get_data(): hours = int(input("Please enter the numbers of hours you do: ")) rate = int(input("Please enter the rate of pay you have: ")) return hours , rate #calculate basic pay def calculate_pay(): hours,rate = get_data () total_pay = calculate_total_pay (hours,rate) dis_pay (total_pay) #display the total def dis_pay (total_pay): print(total_pay) #main program calculate_pay()
true
e5466b52c74df1e3445d2753a97fc34d2c4bdf19
Azarkasb/LearnPython
/UseLessProjects/Mosalas.py
630
4.21875
4
''' Barname baraye tashkis noe mosalas bar asas azla ''' # AZ a = int(input('Pls enter the first side ... ')) b = int(input('Pls enter the second side ... ')) c = int(input('Pls enter the third side ... ')) if a + b <= c or a + c <= b or b + c <= a: print('Impossible') elif a == b and a == c: print('Equilateral Triangle') elif a == b or b == c: if a**2 + b**2 == c or b**2 + c**2 == a**2 or a**2 + c**2 == b**2: print('Isosceles Right Triangle') else: print('Isosceles Triangle') elif a**2 + b**2 == c or b**2 + c**2 == a**2 or a**2 + c**2 == b**2: print('Right Triangle') else: print('Normal Triangle')
false
bebc8bbdb3f3ea2e03da7f70663bc5d202b672b9
jtcgen/PythonPuzzles
/balance.py
2,566
4.125
4
''' Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit population is at stake, so Beta reads the challenge: There is a scale with an object on the left-hand side, whose mass is given in some number of units. Predictably, the task is to balance the two sides. But there is a catch: You only have this peculiar weight set, having masses 1, 3, 9, 27, ... units. That is, one for each power of 3. Being a brilliant mathematician, Beta Rabbit quickly discovers that any number of units of mass can be balanced exactly using this set. To help Beta get into the room, write a method called answer(x), which outputs a list of strings representing where the weights should be placed, in order for the two sides to be balanced, assuming that weight on the left has mass x units. The first element of the output list should correspond to the 1-unit weight, the second element to the 3-unit weight, and so on. Each string is one of: "L" : put weight on left-hand side "R" : put weight on right-hand side "-" : do not use weight To ensure that the output is the smallest possible, the last element of the list must not be "-". x will always be a positive integer, no larger than 1000000000. Test cases ========== Inputs: (int) x = 2 Output: (string list) ["L", "R"] Inputs: (int) x = 8 Output: (string list) ["L", "-", "R"] ''' from math import log, ceil, floor import sys def answer(x): lgx = log(x,3) # All powers of 3 if 3**floor(lgx) == x: return ['-' if i != lgx else 'R' for i in range(int(lgx+1))] # range of powers of 3 to look at up_bnd = ceil(lgx) low_bnd = floor(lgx) branch = 3**up_bnd - x # If diff between upper bnd and x is greater than x, answer will contain up to lower bnd if branch > x: ans = ['-'] * (low_bnd+1) diff = answer(x-(3**low_bnd)) else: # Answer will contain upper bnd ans = ['-'] * (low_bnd+2) diff = answer((3**up_bnd)-x) # Populate result for i in range(low_bnd+1): if i < len(diff): if branch > x: ans[i] = '-' if diff[i] == '-' else 'R' if diff[i] == 'R' else 'L' else: ans[i] = '-' if diff[i] == '-' else 'L' if diff[i] == 'R' else 'R' else: ans[i] = '-' ans[len(ans)-1] = 'R' return ans if __name__ == '__main__': print(answer(sys.argv[1]))
true
6bfe2d8b1498b161c31f7d2ea809244a104e05e8
Thea-J/python_practice
/tuple.py
513
4.1875
4
# Define a tuple & assign it to a variable t = (1, 2, 3, 4) # Use square-bracket notation to retrieve tuple element # Note: tuple indices start at 0 x = t[0] # Create a new list from a tuple # via list reserved word l = list(t) # Define a range from 0 to inserted_number-1 # via range reserved word r= range(7) #k = (0, 1, 2, 3, 4, 5, 6) # Use square-bracket notation to retrieve range element # Note: range indices start at 0 y= r[5] # Create a new list from a range # via list reserved word z = list(r)
true
fdab5914d1fb693b4ad7e7cdf549e76001b0e9db
portiaportia/csce204-assignment-answers
/12-file-writing/question-game-original.py
1,769
4.25
4
import random FILE_NAME_TRIVIA = "assignments/12-file-writing/trivia.txt" # Reach each line of the file into a dictionary. The dictionary will look like: # Question -> Answer # We use a convert to bool method to convert "true" to True def getQuestions(): questions = {} with open(FILE_NAME_TRIVIA) as file: for line in file: data = line.split(':') question = data[0].strip() answer = data[1].strip() questions[question] = convertToBool(answer) return questions # Converts a string representation of a boolean to a Boolean def convertToBool(answer): if answer == "true": return True else: return False # Asks the user a random trivia question # Gathers the users answer # if their answer is the stored answer then return true (they won), otherwise return false def playRound(): question = random.choice(list(questions.keys())) userAns = input(f"True or False: {question} ").strip().lower() compAns = questions.get(question) if convertToBool(userAns) == compAns: return True else: return False # Let's play the game print("Welcome to our Trivia Game") # Load all the questions from the file questions = getQuestions() # Loop as long as the user wants to keep playing while True: command = input("(P)lay or (Q)uit: ").strip().lower() # if they enter q, quit the game if command == "q": break # if they enter an invalid command, indicate that elif command != "p": print("Invalid command") continue # otherwise play around, if playRound is true, they won if playRound(): print("Yay, you got it!") else: print("Sorry, incorrect") print("Goodbye")
true
c20ebef4edfce9a0dbb6eded6b23a2b9829b7f7c
sjriddle/CTCI
/2/a23.py
446
4.125
4
## Implement an algorithm to delete a node in the middle (i.e any node but the ## first or last node, not necessarily the exact middle) of a singly linked list, ## given only access to that node ## EXAMPLE ## Input: The node c from linked list a->b->c->d->e->f ## Output: Nothing is returned, but the new linked list is a->b->d->e->f # Memory: O(1) # CPU: O(1) def delete_node(node): node.data = node.next.data node.next = node.next.next
true
f45163ea2a7e32eb46f138321fe860c4ad356a12
Yamikaze123/Nguyen-Tien-Hoang-c4t3-session-3-hw
/Fruit.py
562
4.21875
4
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } print() print("Fruits' price and stock information:") print() for price in prices: print(price) print("price:", prices[price]) print("stock:", stock[price]) print() print() print("Money made:") print() total = 0 for price in prices: print(price, end=": ") multi = prices[price] * stock[price] print(int(multi)) total = total + multi print() print("Total:", total)
true
c858740aca4412c22f714ae3e19d063c10383f54
AsgardRodent/MyPy
/arguments.py
1,143
4.1875
4
def print_name_age(name = "someone", age = "ancient"): print("hi my name is ", name ,"i am ", age, " years old") print_name_age("gaurav", 20) print_name_age("regigas") print_name_age("supahotfire", 28) print_name_age(age=32) # to solve the above error u can directly replace the line(4) with the following code which just [rints all the data as itself # print("hi my name is ", name ,"i am ", age , " years old") ----> this is to be replaced # as a back up the default line is provided below :D # print("hi my name is " + name + " i am " + str(age) + " years old")--------> default line # in line(9) only 32 is passed which will be replaced by the name since it as per the definition/the parameters provided to the function # so the keyword "None" is used to skip a parameter hence the new line will be :D # print_name_age(None,32) ------> new line # print_name_age(32)---------> default line # none --> bool # this error can be sorted using key arguments like #print_name_age(age = 32) # REMEMBER KEY ARGUMENTS CAN BE PASSED IN ANY MANNER AS YOU LIKE ,SINCE THEY ARE DEFINED TO A SPECIFIC VALUE
true
6d10d06f34d99747f20a97e50a7fd3ab6eba4c66
moonlimb/scheme_to_js_translator
/refs/game/comp_guess.py
1,468
4.28125
4
import random # Human will make random number # Computer will make an initial constant guess: 50 constant. And print this number. # The human will give feedback to computer if number guess is too hi or too low # THe computer will then make a new guess, which is a middle number in the new range. # the computer will repeat the process until it reaches the final number # count the number of guesses def human_feedback(): return raw_input("\nIs my guess 'too high', 'too low', or 'perfect'? ") def smart_CS_guess(): CS_guess = 50 count = 1 # human_answer = a certain number too_high = "too high" too_low = "too low" perfect = "perfect" print "Hi. My name is Max the computer. I made my first guess: %d." %CS_guess human_input = human_feedback() #The computer does thinking below: low_bound = 1 high_bound = 100 while (human_input != perfect): if (human_input != too_high) and (human_input != too_low): print "EPIC FAIL! Type in a sensible reply, you're not a clever human." break elif human_input == too_high: high_bound = CS_guess - 1 print low_bound, high_bound else: #human_input == too_low: low_bound= CS_guess+1 print low_bound, high_bound CS_guess = (low_bound + high_bound)/2 count+=1 print count print "This is my new guess: %d." %CS_guess human_input = human_feedback() print "Congratulations Max! %d is the correct number. You got it in %d trials." %(CS_guess, count) smart_CS_guess()
true
f7dae2376580f4e0e11a51fa9858e1bed7588e4a
bloobloons/codewars
/Thinkful - List Drills: Longest word.py
250
4.1875
4
# Write a function longest() that takes one argument, a list of words, # and returns the length of the longest word in the list. def longest(words): lengths = [] for each in words: lengths.append(len(each)) return max(lengths)
true
5a263cb2680ab8313b234d847dba5d09e23c2d47
Nep-DC-Exercises/day-3
/box.py
481
4.1875
4
# Given a height and width, input by the user, print a box consisting of * characters as its border. width = int(input("Enter width of box > ")) height = int(input("Enter height of box > ")) star = "*" i = 0 mid = width - 2 while i < height: if i == 0: # top of box print(width * star) elif i == height - 1: # bottom of box print(width * star) elif i >= 1 or i < height - 1: # middle rows of box print("*" + mid * " " + "*") i += 1
true
08e7fa564f63818b5727ddc51905ec097e185d83
Nep-DC-Exercises/day-3
/blastoff4.py
255
4.1875
4
# Make sure user doesn't enter a number larger than 20 i = int(input("Enter the number to start counting from. >> ")) if i <= 20: while i >= 0: print(i) i -= 1 else: print("That number was too high. It can't be larger than 20.")
true
ed7e13bf6e91d2ab770f60b9c406d91663298947
EricNg314/Code-Drills
/Python/day-01/04/challenge-prompt.py
837
4.15625
4
# Declare a variable of bobaShop with an input and a string of "Welcome to the Boba Shop!" # Check if bobaShop is equal to true # Write a print with a string of "Hello" # Declare a variable of beverage with an input and a string of "What kind of boba drink would you like ?" # Declare a variable of sweetness with an input and a string of "How sweet do you want your drink 0,50,100,200 ?" # Now check # if sweetness equals to 50 print "half sweetened" # else if sweetness 100 print "normal sweet" # else if sweetness 200 print "super sweet" # else print with a string of "non-sweet" # then print with a string of "your order of " variable beverage and a string of " boba with a sweet level of " and variable of sweetness # and print string of "goodbye".
true
c180f9481c1e727b53060f5f6a018f829457f2d7
YuJianMuNaiYi/Python
/day1/do_set.py
441
4.15625
4
s = set([1, 2, 3]) print(s) # 重复元素在set中自动被过滤 t = set([1, 1, 2, 2, 3, 3, 4, 5, 6]) print(t) # 添加元素 t.add(7) t.add(3) t.add(8) t.add(7) print(t) # 移除元素 t.remove(3) print(t) # set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作 print(s & t) print(s |t) #对于可变对象 a=['c', 'b', 'a'] a.sort() print(a)
false
e272790061c5be0d13216da2474c2dd89cc22e58
EricaGuzman/PersonalProjects
/Python/payCheck/payCheck.py
1,354
4.125
4
#Erica Guzman #This program calculates user's weekly paycheck import math #Define main def main(): #Declare and initilaize float variables weeklySalesAmount = commission = grossPay = netPay = socialSecurity = federalTax = 0.0 #constant for base pay basePay = 400.00 #display Welcome message: print("Welcome to your weekly paycheck generator!"); weeklySalesAmount = float(input("Enter the dollar amount of sales made for the week: ")); #calculations: commission = weeklySalesAmount * .06 grossPay = weeklySalesAmount + basePay + commission socialSecurity = grossPay * .06 federalTax = grossPay * .12 netPay = grossPay -(socialSecurity + federalTax) #print paycheck print ("*" * 40) print("Base Pay:\t ${:,.2f}" .format (basePay)); print("Sales:\t\t ${:,.2f}" .format (weeklySalesAmount)); print("Commission:\t ${:,.2f}" .format (commission)); print("Gross Pay:\t ${:,.2f}" .format (grossPay)); print(); print("Deductions: "); print ("*" * 40) print("Social security: ${:,.2f}" .format (socialSecurity)); print("Federal Tax:\t ${:,.2f}" .format (federalTax)); print ("*" * 40) print("Net Pay:\t ${:,.2f}" .format (netPay)); #display Goodbye print(); print("Thank you for using the paycheck generator! \n Have a nice day!!"); main()
true
a5fe8b3a234987a1f13545bac3d096808d37108a
npraveen35/Python_Codes
/basic_codes/leap_year.py
778
4.15625
4
#!/usr/bin/python ''' All the years that are perfectly divisible by 4 are called as Leap years except the century years. Century year's means they end with 00 such as 1200, 1300, 2400, 2500 etc (Obviously they are divisible by 100). For these century years we have to calculate further to check the Leap year: If the century year is divisible by 400 then that year is a Leap year If the century year is not divisible by 400 then that year is a Not Leap year ''' #V1: This code reads input from user and test for leap year num=int(input("Enter Year:")) def leap_year(year): return ( year % 4 == 0 and year % 100 != 0) or year % 400 == 0 print num,"is leap year" if leap_year(num) else "not a leap year" #V2 use calender module #import calendar #print calendar.isleap(num)
true
02629ad2ac00dc8e0c8d274bd5c1c114ce1b62dc
npraveen35/Python_Codes
/basic_codes/words_in_line.py
255
4.25
4
#!/usr/bin/env python3 #v1 COUNTS NUMBER OF WORDS IN A SENTENCE: def count_words(str): return len(str.split(' ')) #splits the str with space & creates list sentence = "An Apple a day keeps a Doctor away !!" print (count_words(sentence)) #Output is 9
true
32de88abc8173d997907f1a87d23c8ba7bd0520b
LiamLead/to-do-list
/to-do-list.py
1,755
4.25
4
print("TO DO LIST\n") class Queue(object): def __init__(self): self.storage = [] def enqueue(self, new_element): self.storage.append([new_element]) def display_all(self): return self.storage def display_one(self): return self.storage[-1] def dequeue(self): return self.storage.pop(0) def delete_all(self): return self.storage.clear() def append(self): add = str(input("Add: ")) self.storage.append([add]) q = Queue() q.enqueue("Breakfast") q.enqueue("Go to work") q.enqueue("Lunch") print(q.display_all()) drink_coffee = "Drink Coffee" buy_chocolate = "Buy Chocolate" drink_milk_tea = "Drink Milk Tea" go_to_run = "Go To Run" clear_list = "Empty the list" show_list = "Check your list" add_own_item = "Add your Own Item" print("") print("0: " + show_list) print("1: " + drink_coffee) print("2: " + buy_chocolate) print("3: " + drink_milk_tea) print("4: " + go_to_run) print("5: " + clear_list) print("6: " + add_own_item) print("9: Exit the program") while True: choice = int(input("\nChoose one thing to add to the 'to do list': ")) if choice == 1: q.enqueue(drink_coffee) print(f"{q.display_one()}, Added to the list.") elif choice == 2: q.enqueue(buy_chocolate) print(f"{q.display_one()}, Added to the list.") elif choice == 3: q.enqueue(drink_milk_tea) print(f"{q.display_one()}, Added to the list.") elif choice == 4: q.enqueue(go_to_run) print(f"{q.display_one()}, Added to the list.") elif choice == 5: q.delete_all() elif choice == 0: print(q.display_all()) elif choice == 6: q.append() elif choice == 9: break
false
bd840a9f621e4791a9440de95ecb1eb65a564d65
amrutbadiger/python
/exercise1.py
224
4.21875
4
""" Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. """ a=str(input("Enter your First name:")) b=str(input("Enter your Last name:")) print (b,a)
true
c26ba526f16220c89265c688c06b0df838039302
amrutbadiger/python
/exer4.py
220
4.15625
4
""" A program to calculate rate of interest. """ p=int(input("Enter the principal amount(P):")) r=float(input("Enter the rate of interest(R):")) t=int(input("Enter the period(T):")) i=(p*r*t)/100 print("Interest is:",i)
true
5ba74f2ecef7a540f5f448eea2b8bcebbcb4b736
amrutbadiger/python
/dict2.py
903
4.5625
5
''' Assign a dictionary item's value to a variable using a key that's a string. Then append that value to a list ''' list_of_ages=[] info={"first name": "Bob", "second name": "Mark", "age": 56} age=info["age"] list_of_ages.append(age) print(list_of_ages) ''' Assign a dictionary item's value to a variable using a key that's a string. Then create a dictionary that contains only that value. ''' dict={"name": "Bob", "last name": "Mark", "address": "Parkinson Street"} value=dict["name"] new_dict={"my_name": value} print(new_dict) ''' Targeting the second item by its key, assign the second item's value to a variable and display it. ''' relatives ={"father": "Bob", "mother": "Lucy", "sister": "Rose",} a_relative = relatives["mother"] print(a_relative) # In a single line of code,target the third item and display its value. states = {1: "goa", 2: "assam", 3: "sikkim", 4: "kerala"} print(states[3])
true
643a0c33d238121046ff0e2762afff7bb31579a8
Elegant-Smile/PythonDailyQuestion
/Answer/Gorit的题解/2019-5-13/字符输出星期.py
621
4.375
4
#字符输入星期 str=input("请输入一个字符:\n") if str is 'm' or str is 'M': print("Monday") elif str is 'T' or str is 't': str1=input("请继续输入第二个字符:\n") if str1 is 'u' or str1 is 'U': print("Tuesday") elif str1 is 'h' or str1 is 'H': print("Thursday") elif str is 'W' or str is 'w': print("Wednesday") elif str is 'f' or str is 'F': print("Friday") elif str is 's' or str is 'S': str2=input("请继续输入第二个字符") if str2 is 'A' or str2 is 'a': print("Saturday") elif str2 is 'u' or str2 is 'U': print("Sunday")
false
7a1d91657e4d0c8be5286ad97f6d24e6aae53993
Elegant-Smile/PythonDailyQuestion
/Answer/Yuzhou_1shu/20190524_2_hypotenuse.py
363
4.21875
4
import math def hypotenuse(a, b): ''' :param a: 直角边 :param b: 直角边 :return: 斜边长 ''' return math.sqrt(a ** 2 + b ** 2) if __name__ == '__main__': a = int(input("请输入一条直角边:")) b = int(input("请输入另一条直角边:")) print("The right triangle third side's length is", hypotenuse(a, b))
false
7bcce8de03e1d817be8ffcca8a42b1dd20bd595c
Elegant-Smile/PythonDailyQuestion
/Answer/weixiao/first_answer20190611.py
1,175
4.125
4
# 给定任意一个整数,打印出该整数的十进制、八进制、十六进制(大写)、二进制形式的字符串。 num = input('please input a number>>>') dec_num = int(num) print(dec_num) print(oct(dec_num)) print(hex(dec_num).upper()) print(bin(dec_num)) # 给用户三次输入用户名和密码的机会,要求如下:‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬ # 1)如输入第一行输入用户名为‘Kate’,第二行输入密码为‘666666’,输出‘登录成功!’,退出程序;‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬ # 当一共有3次输入用户名或密码不正确输出“3次用户名或者密码均有误!退出程序。” def check(): n = 0 while n < 3: name = input('>>>') password = input('>>>>') if name == 'Kate' and password =='666666': print('登录成功') break else: n += 1 if __name__ == '__main__': check()
false
c6e89c0feafa587a62fc6297c1f71d128bb1588c
NancyKou/python_lianxi
/python_oo/homework2/student.py
1,248
4.125
4
#定义私有属性,双下划线加变量名 #调用私有属性或私有方法,则双下划线加类型加 点,则可以找到私有方法或私有比属性 class Student: #定义一个Student类 def __init__(self,name,score): #初始化参数 self.name = name #定义实例变量name self.score =score #定义实例变量score def grade(self): #定义一个类方法grade if self.score >= 90: #如果分数大于等于90分 print(self.name,',your grade is A!') #打印xx学生的等级为A elif self.score >= 60: #如果分数大于等于60分 print(self.name,',your grade is B.') #打印xx学生的等级为B else: print(self.name,',your grade is C.') #否则打印xx学生的等级为C def work(self): #定义一个类方法work print(f'{self.name}学习很努力!') #打印XX学生学习很努力。 stu1 = Student('dannie',90) #实例化一个学生1,给init中定义的参数传入name和score参数 stu2 = Student('Alex',59) #实例化一个学生2,给init中定义的参数传入name和score参数 stu1.grade() #调用grade方法,打印学生1的等级 stu2.work() #调用work方法,打印学生2的努力程度
false
17c74c591e48ba4e8c575541b7c50677dba6dd84
janekob/pp1
/02-ControlStructures/zadania/18.py
207
4.21875
4
for x in range(31): if(x%3==0 and not x%5==0): print("three") elif(x%5==0 and not x%3==0): print("five") elif(x%3==0 and x%5==0): print('bingo') else: print(x)
false
00f4cf0d311e3d87a4403b81a02818af6f9255b7
celopesp/PROITEC
/criptotexto.py
1,704
4.15625
4
"""César é um detetive que investiga uma série de roubos que acontecem em sua cidade. Em todo lugar que um crime acontece, a pessoa que cometeu tal crime deixa uma mensagem escrita, formada por letras maiúsculas e minúsculas. César conseguiu achar um padrão nestas mensagens e agora extrai um texto oculto em cada mensagem e pede a sua ajuda para tentar descobrir quem está cometendo tais crimes. Entrada A entrada é composta por vários casos de teste. A primeira linha contém um número inteiro C (2 <= C <= 99) relativo ao número de casos de teste. Nas C linhas seguintes, haverá mensagens codificadas, todas com um mesmo padrão em relação ao exemplo abaixo. Saída Para cada caso de teste de entrada do seu programa, você deve imprimir o texto extraído da mensagem original. """ valido = False while(valido == False): C = int(input("digite a quantidade de palavras que deseja descriptografar:")) if(C>1 and C<100): valido = True lista = [] for contador in range (1, C+1): palavra = input(f"digite a {contador}ª palavras que deseja descriptografar:") tamanho_palavra = len(palavra) palavra_ordenada = "" reverso = -1 for contador_ordenar_palavra in range (tamanho_palavra-1, -1, -1): palavra_ordenada += palavra[reverso] reverso -= 1 lista.append(palavra_ordenada) for contador in range (0, C): tamanho_palavra = len(lista[contador]) palavra = lista[contador] descriptografada = "" for aux in range(0,tamanho_palavra): if(palavra[aux].islower()): descriptografada += palavra[aux] print(f'descriptografada:{descriptografada}')
false
9799d78ef1457b5853596bb39994810970e77c47
zedfoxus/stackoverflow-answers
/order-flights/flights-recursion.py
845
4.15625
4
def next_leg(flights, source): """Find and append next flight to trip""" for leg in flights: if leg[0] == source: trip.append(leg) source = leg[1] flights.remove(leg) next_leg(flights, source) def previous_leg(flights, destination): """Find and prepend previous flight to trip""" for leg in flights: if leg[1] == destination: trip.insert(0, leg) destination = leg[0] flights.remove(leg) previous_leg(flights, destination) flights = [ ['Minneapolis', 'Las Vegas'], ['LA', 'Chicago'], ['Las Vegas', 'Seattle'], ['Chicago', 'Atlanta'], ['Atlanta', 'NY'], ['NY', 'Minneapolis'], ] trip = [flights[0]] flights.pop(0) next_leg(flights, trip[0][1]) previous_leg(flights, trip[0][0]) print(trip)
false
64856f52540d3b445232b03820e0f02e7ac29eae
00wendi00/Python-initiation
/algorithm/search_fibonacci.py
1,704
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : search_fibonacci.py # @Author: Wade Cheung # @Date : 2018/7/3 # @Desc : 斐波拉契查找 from algorithm.Fibonacci import fibonacci_create def fibonacci_search(lis, key): """斐波拉契查找, 平均性能,要优于二分查找。但是在最坏情况下,比如这里如果key为1,则始终处于左侧半区查找,此时其效率要低于二分查找 :param lis: :param key: :return: """ fib = fibonacci_create(100) low = 0 high = len(lis) - 1 # 为了使得查找表满足斐波那契特性,在表的最后添加几个同样的值 # 这个值是原查找表的最后那个元素的值 # 添加的个数由fib[k]-i-1决定 k = 0 while high > fib[k] - 1: k += 1 print(k) i = high while fib[k] - 1 > i: lis.append(lis[high]) i += 1 print(lis) times = 0 while low <= high: times += 1 # 为了防止fib列表下标溢出 if k < 2: mid = low else: mid = low + fib[k - 1] - 1 print('low=%s, mid=%s, high=%s' % (low, mid, high)) if key < lis[mid]: high = mid - 1 k -= 1 elif key > lis[mid]: low = mid + 1 k -= 2 else: if mid <= high: print('times: %s' % times) return mid else: print('times: %s' % times) return high print('times: %s' % times) return False if __name__ == '__main__': LIST = [1, 5, 7, 8, 22, 54, 99, 123, 200, 222, 444] result = fibonacci_search(LIST, 222) print(result)
false
0a49e0d5e5eeda698c11c100a4a3fb8f8cc6a9d6
dhruvsharma95/intro-to-python
/day3/recap.py
2,891
4.28125
4
""" program to check if the number (say 'n') given as input is a prime a prime no. is the one which has only 1 and the numbers itself as its divisors 1 is not a prime no. eg. n = 2, 3, 5, 7, ... idea: start a loop from 2 to n/2, if n is divisble by the divisor => not prime because a no. cannot be divided by a no. > n/2 except n """ n = int(input()) checked = 0 for divisor in range(2, n//2 + 1): if (n % divisor == 0): print("No is not prime!") checked = 1 # no need checking further, can break the loop here itself break # the above code doesn't say that 1 is not a prime because loop won't run even once # to handle that case, we can add the extra condition: if (n == 1): print("No is not prime!") checked = 1 # in cases where checked is false or equal to 0, can say it is prime! if (not checked): print("No is prime!") """ program to print the following pattern: * * * * * * * * * * ... idea: As you can observer, we are looping in two directions, row wise and column wise 1st row has 1 star 2nd row has 2 stars 3rd row has 3 stars and so on... the outer loop would represent looping over the rows and in the inner loop, we will loop over the elements in the rows, i.e. columns Always better to use loop variable 'r' or 'row' for looping on rows and the loop variable 'c' or 'col' to loop on columns for easy understanding and debugging of your code ! """ num_rows = n for row in range(1, num_rows + 1): # r_th row will have r stars for col in range(1, row + 1): print('*', end=' ') # endline print('') # is it possible to do the same thing using one loop, think? # idea is the same: print 1 char in 1st row, 2 chars in 2nd row, ... line_num = 1 printed_on_cur_row = 0 while (line_num <= num_rows): if (printed_on_cur_row < line_num): print('*', end=' ') printed_on_cur_row += 1 else: print('') # reset count of stars on cur_row to be zero printed_on_cur_row = 0 # increment the line_num, i.e. move to next row line_num += 1 """ function to return maximum of three numbers idea: let numbers be a, b, c when can a be the max? when a >= b and a >= c similarly for b and c so, write three conditions, and return the answer if that condition is true also, you can use if elif else as well! """ def maximum_of_three(num_one, num_two, num_three): if (num_one >= num_two and num_one >= num_three): return num_one if (num_two >= num_one and num_two >= num_three): return num_two if (num_three >= num_one and num_three >= num_two): return num_three return -1 n1 = 3 n2 = 7 n3 = 1 res = maximum_of_three(n1, n2, n3) print(res) # idea: assign max = a, now check if b >= max, max = b, again if c >= max, max = c def maximum_of_three_simple(n1, n2, n3): maxi = n1 if (n2 >= maxi): maxi = n2 if (n3 >= maxi): maxi = n3 return maxi res = maximum_of_three(n1, n2, n3) print(res)
true
e8566d6e9626c1f5d04d524071ca158cb535677e
Vahi-vai/python-bootcamp
/task13 - all exercises.py
890
4.40625
4
# Exercise 1 import re def is_allowed_specific_char(string): charRe = re.compile(r'[^a-zA-Z0-9.]') string = charRe.search(string) return not (string) c = input("Enter anything") print(is_allowed_specific_char(c)) #Exercise 2 import re a = input("Enter any word") b = re.search("ab",a) print(b) # Exercse 3 j = input("Enter a sentence") res= re.finditer(r"([0-9]{1,3})", j) print(" words end with") for i in res: print(i.group(0)) # Exercise 4 import re results = re.finditer(r"([0-9]{1,3})", "i got 93 in maths, 96 in chemistry and 100 in physics") print("Number of length 1 to 3") for n in results: print(n.group(0)) # Exercise 6 import re def text_match(text): if re.search("^[A-Z]*$", text): return ("all the letters in the entered word is uppercase") o = input("Enter a word") print( text_match(o))
true
562fc5da1d34291a12e1e32ca7b179166b10c2c4
javierunix/ca_computerscience
/CS101/functions/challenges.py
2,576
4.21875
4
# Create a function named divisible_by_ten() that takes a list of numbers named nums as a parameter. # Return the count of how many numbers in the list are divisible by 10. def divisible_by_ten(nums): counter = 0 # define and initialize counter for num in nums: # iterate over list if num % 10 == 0: # if number is divisible by ten counter += 1 # increment counter return counter # print(divisible_by_ten([20, 25, 30, 35, 40])) # Create a function named add_greetings() which takes a list of strings named names as a parameter. # In the function, create an empty list that will contain each greeting. Add the string 'Hello, ' in front of each name in names and append the greeting to the list. # Return the new list containing the greetings. def add_greetings(names): greetings = [] for name in names: greetings.append("Hello, %s" %name) return greetings # print(add_greetings(["Owen", "Max", "Sophie"])) #Write a function called delete_starting_evens() that has a parameter named lst. # The function should remove elements from the front of lst until the front of the list is not even. The function should then return lst. # For example if lst started as [4, 8, 10, 11, 12, 15], then delete_starting_evens(lst) should return [11, 12, 15]. def delete_starting_evens(lst): while (len(lst) > 0 and lst[0] % 2 == 0): lst = lst[1:] return(lst) # print(delete_starting_evens([4, 8, 10, 11, 12, 15])) # print(delete_starting_evens([4, 8, 10, 14, 18, 20])) # Create a function named odd_indices() that has one parameter named lst. # The function should create a new empty list and add every element from lst that has an odd index. # The function should then return this new list. def odd_indices(lst): new_list = [] for i in range(1, len(lst), 2): # iterate from index 1, in 2 position steps new_list.append(lst[i]) return new_list # print(odd_indices([4, 3, 7, 10, 11, -2])) # Create a function named exponents() that takes two lists as parameters named bases and powers. # Return a new list containing every number in bases raised to every number in powers. def exponents(bases, powers): # the function accepts as arguments two lists: bases and powers new_list = [] # new list to store the exponents for base in bases: # iterate through bases for power in powers: # iterate through powers new_list.append(base ** power) # append to new list the exponential number return new_list print(exponents([2, 3, 4], [1, 2, 3]) )
true
e28a3cdba85b68d2a09da8486c745c22ce4ea9e8
javierunix/ca_computerscience
/CS102/BinarySearch/binary_iterative.py
821
4.1875
4
def binary_search(sorted_list, target): left_pointer = 0 right_pointer = len(sorted_list) # fill in the condition for the while loop while left_pointer < right_pointer: # calculate the middle index using the two pointers mid_idx = (left_pointer + right_pointer) // 2 mid_val = sorted_list[mid_idx] if mid_val == target: return mid_idx if target < mid_val: # set the right_pointer to the appropriate value right_pointer = mid_idx if target > mid_val: # set the left_pointer to the appropriate value left_pointer = mid_idx + 1 return "Value not in list" # test cases print(binary_search([5,6,7,8,9], 9)) print(binary_search([5,6,7,8,9], 10)) print(binary_search([5,6,7,8,9], 8)) print(binary_search([5,6,7,8,9], 4)) print(binary_search([5,6,7,8,9], 6))
true
4aecc602de2fc81ee18ef45eaf70639c99c8f268
javierunix/ca_computerscience
/CS102/DepthFirstTrees/TreeNode.py
1,918
4.15625
4
from collections import deque class TreeNode: def __init__(self, value): self.value = value # data self.children = [] # references to other nodes def __repr__(self): return self.value def add_child(self, child_node): # creates parent-child relationship print("Adding " + child_node.value) self.children.append(child_node) def remove_child(self, child_node): # removes parent-child relationship print("Removing " + child_node.value + " from " + self.value) self.children = [child for child in self.children if child is not child_node] def traverse(self): # moves through each node referenced from self downwards nodes_to_visit = [self] while len(nodes_to_visit) > 0: current_node = nodes_to_visit.pop() print(current_node.value) nodes_to_visit += current_node.children def print_tree(root): stack = deque() stack.append([root, 0]) level_str = "\n" prev_level = 0 level = 0 while len(stack) > 0: prev_level = level node, level = stack.pop() if level > 0 and len(stack) > 0 and level <= stack[-1][1]: level_str += " "*(level-1)+ "├─" elif level > 0: level_str += " "*(level-1)+ "└─" level_str += str(node.value) level_str += "\n" level+=1 for child in node.children: stack.append([child, level]) print(level_str) def print_path(path): # If path is None, no path was found if path == None: print("No paths found!") # If a path was found, print path else: print("Path found:") for node in path: print(node.value) sample_root_node = TreeNode("A") two = TreeNode("B") three = TreeNode("C") sample_root_node.children = [three, two] four = TreeNode("D") five = TreeNode("E") six = TreeNode("F") seven = TreeNode("G") two.children = [five, four] three.children = [seven, six]
true
832d4063787cbe9ed48ac8a72aa27be8b89aea83
swaroop9ai9/problemsolving
/generator.py
2,301
4.46875
4
# Python generators are the functions that return the traversal object and used to create iterators. # It traverses the entire items at once # The generato can also be an expression in which syntac is similar to list comprehension # There is a lot of complexity in creating iteration in python, we need to implement __iter__() and __next__() method to keep track of internal states # Generator plays an essential role in simplifying this process. # If no value it raises "StopIteration" exception # Syntax to create a generator function # Similar to normal function, but uses 'yeild' keyword instead of return import time def simple_even(): for i in range(10): print("gen_func") time.sleep(2) if(i%2==0): yield i # Successive function call using for loop, this returns the even number list for i in simple_even(): print("loop") time.sleep(2) print(i) # The yeild keyword, is responsible for controlling the flow of the generator function. # It pauses the function execution by saving all states and yielded to the caller, # Later resumes execution, when a successive function is called. # But, a return statement returns a value and terminates the whole function, (only one return can be used). time.sleep(3) print("Multiple Yield's") def multiple_yield(): str1="First String" yield str1 str2 = "second string" yield str2 str3="Third String" yield str3 obj = multiple_yield() print(next(obj)) time.sleep(2) print(next(obj)) time.sleep(2) print(next(obj)) # In Generator functions are called, the normal function is paused immediately and control transferred to the caller # Local variable and their states are remembered between succesive calls # StopIteration exception is raised automatically when the function terminates # Generator Expression: Could be created easily without useer-defined function. # Similar to Lambda function, which created an anonymous generator function # Very similar to list comprehension, but square braces are replaced with () print("Generator Expression") lis = [1,2,3,4,5,78] a = (x**3 for x in lis) print(a) print(next(a)) print(next(a)) # Advantages of Generators # 1) Easy to implement # 2) Memory Efficient # 3) Pipelining with Generators # 4) Generate Infinite Sequence
true
2d143b66b04ee61acdcc848f7b6e51c60aacc993
vinkrish/ml-jupyter-notebook
/DS & Algorithm/Stack/StackArraySize.py
1,632
4.15625
4
class EmptyStackError(Exception): pass class StackFullError(Exception): pass class Stack: def __init__(self, max_size = 10): self.items = [None] * max_size self.count = 0 def is_empty(self): return self.count == 0 def is_full(self): return self.count == len(self.items) def size(self): return self.count def push(self, item): if self.is_full(): raise StackFullError('Stack is full, can\'t push') self.items[self.count] = item self.count += 1 def pop(self): if self.is_empty(): raise EmptyStackError('Stack is empty, can\'t pop') x = self.items[self.count-1] self.items[self.count-1] = None self.count -+ 1 return x def peek(self): if self.is_empty(): raise EmptyStackError('Stack is empty, can\'t peek') return self.items[-1] def display(self): print(self.items) stack = Stack() print('Check if stack is empty :') check_stack = stack.is_empty() print(check_stack) print('Pushing element to stack :') stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) stack.push(6) stack.push(7) stack.push(8) stack.push(9) stack.push(10) stack.display() print('Is stack full :') full = stack.is_full() print(full) print('Pop element from stack :') pop = stack.pop() print(pop) stack.display() print('Peek at stack :') peek = stack.peek() print(peek) stack.display() print('Size of stack :') size = stack.size() print(size) print('Check if stack is empty :') check_stack = stack.is_empty() print(check_stack)
false
5573c2210cc86fc41e421581e462961320cc7439
HDLahlou/pythonTetris
/playground/initWindow.py
1,532
4.15625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- #imports TK=k and Frame class, and the constant BOTH #Tk is used to create a root window #Frame is container for other widgets from tkinter import Tk, BOTH from tkinter.ttk import Frame #Example class inherits Frame container widget #calls constructor of our inherited class in the _init_() class Example(Frame): def __init__(self): super().__init__() #delegates creation of the user interface to the initUI() self.initUI() def initUI(self): #Set title of window, master attribute gives access to the root window Tk self.master.title("Simple") #pack() method one of 3 geometry managers in Tkinter #organizes widgets into horizontal and vertical boxes, here goes the frame widget #Frame accessed through self attribute in Tk root window #expands in both directions, taking whole client space of the root window self.pack(fill=BOTH, expand=1) def main(): #root window created, main app window, must be created before any widgets root = Tk() #sets size and positions it on the screen 1) width 2) height 3) X 4) Y coord root.geometry("250x150+300+300") #Creates instance of application class app = Example() #main loop, event handling starts from this point, receives events from the window system #dispatches them to application widgets root.mainloop() if __name__ == '__main__': main()
true
635490925bbf77cc19972bfff875466095b590c0
xuedagong/hello
/leetcode/python/BinaryTreeLevelOrderTraversal_II.py
1,252
4.15625
4
''' Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ my_lst=self.make_q([root], []) my_lst.reverse() return my_lst def make_q(self,root_lst,global_lst): one_list=[] new_root_lst=[] for item in root_lst: if item is not None: one_list.append(item.val) new_root_lst.append(item.left) new_root_lst.append(item.right) if len(one_list)>0: global_lst.append(one_list) if len(new_root_lst)>0: return self.make_q(new_root_lst,global_lst) else: return global_lst if __name__ == '__main__': print 1
true
d122d474b7de57df01d4e8fe789d5f3e7cab137a
carvalhopedro22/Programas-em-python-cursos-e-geral-
/Programas do Curso/Desafio 9.py
228
4.125
4
n = int(input('Digite um numero: ')) print('Tabuada do numero digitado a seguir\n:') print(n * 0) print(n * 1) print(n * 2) print(n * 3) print(n * 4) print(n * 5) print(n * 6) print(n * 7) print(n * 8) print(n * 9) print(n * 10)
false
d9a7a6d5c685b4de80f54c86d563408bb7cbedc3
fwang1395/LeetCode
/python/LinkList/DeleteNode.py
1,656
4.28125
4
#!/usr/bin/python # _*_ coding=UTF_* _*_ ''' Delete Node in a Linked List Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: 4 -> 5 -> 1 -> 9 Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. Note: The linked list will have at least two elements. All of the nodes' values will be unique. The given node will not be the tail and it will always be a valid node of the linked list. Do not return anything from your function. ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None # def setNext(self,y): # self.next = y # def getNext(self): # return self.next # def getValue(self): # return self.val class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ if node.next is not None: nextNode = node.next node.val = nextNode.val node.next = nextNode.next if __name__ == '__main__': node3,node2,node1 = ListNode(3),ListNode(2),ListNode(1) node1.setNext(node2) node2.setNext(node3)
true
8813688d22baf6497f9a255a679dd82d4a5adeed
405620294/python_classwork
/basic grammar/計算bmi.py
525
4.125
4
# 計算BMI BMI:weight/height(m)^2 #型態:數字(整數、小數)、字串 #要注意回傳值得型態,可以回傳數字英文等等,或是有意義的0 height = float(input("請輸入你的身高")) weight = float(input("請輸入你的體重")) print("身高是:", height) print("體重是:", weight) print("bmi:", weight / (height / 100) ** 2) BMI = weight / (height / 100) ** 2 if BMI > 25: print("過重") print("少吃多動") elif 25 > BMI >18: print("正常") else: print("過輕")
false
8482f36a3647203c03c4ccb954ce726f79bf236b
mehedi2258/Pythonist-DP01
/2ndClass.py
2,090
4.59375
5
#Python Class2 (28-02-2017) '''a = 12 b = 5.5 sum = a+b print (sum) print(type(a)) print(type(b)) print(type(sum))''' '''a = 12 b = 5.5 print(a) print(float(b)) print(b) print(int(b))''' '''c = 6.5 print(round(c)) d = 6.4 print(round(d)) e = -5.5 print(round(e)) f= 5.5 print(round(f)) #How to Ceil print(math.ceil(c)) #ceil print(math.ceil(d)) #ceil print(math.ceil(e)) #ceil print(math.ceil(f)) #ceil #How to Floor print(math.floor(c)) #floor print(math.floor(d)) #floor print(math.floor(e)) #floor print(math.floor(f)) #floor''' #print double or more lines '''a= """Mehedi Hasan Milon """ print(a)''' #Add int & String '''a= 'Python programming class. ' b = 'We use pycharm 3.5' print(a+b) a= 'Python programming class.' b = ' We use pycharm 3.5' print(a+b) a= 'Python programming class.' b = 'We use pycharm 3.5' print(a+' '+b) ''' #Add String & Int ''' x = 'Python Programming Class' y = 2 print(x+str(y)) x = 1.0 y = ' Python Programming Class' print(str(x)+(y)) a = '10' b = 10 print(int(a)+b) print(float(a)+b) ''' #Print Output ''' a = 7 b = 3 sum = a+b print(sum) print(str(a) + '+' + str( b) +' = ' +str(sum)) print(a,'+',b,'=',sum) print('{}+{}={}'.format(a,b,sum)) ''' '''a = input('Enter the 1st number: ') b = input('Enter the second number: ') sum = int(a) + int(b) print(sum)''' '''a = int(input('Enter the 1st number: ')) b = int(input('Enter the second number: ')) sum = (a) + (b) print('sum = ',sum,end='')''' '''a = int(input('Enter 1st number: ')) b = int(input('Enter 2nd number: ')) print(a+b)''' '''a = input('Enter 1st number: ') b = input('Enter 2nd number: ') print(a+b)''' '''a = int(input('Enter 1st number: ')) b = int(input('Enter 2nd number: ')) print(a*b)''' '''a = int(input('Enter 1st number: ')) b = int(input('Enter 2nd number: ')) print(a/b)''' '''a = int(input('Enter 1st number: ')) b = int(input('Enter 2nd number: ')) print(a%b)'''
false
54138dd34573193910a644a42cd518d8ccb5941b
clevercarl/udemy.ds
/preprocessing_data.py
2,003
4.34375
4
# Data Preprocessing # Importing the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the Dataset dataset = pd.read_csv('Data.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,3].values # x are independent variables # y is the dependent variable # Missing Data: Taking care of it from sklearn.preprocessing import Imputer # sklearn is a giant library with helpful ML tools # preprocessing is package that helps with preprocessing datasets # Imputer is a class that helps to take care of missing data imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) imputer = imputer.fit(x[:,1:3]) #using imputer on the second & third column, upperbound is excluded that is why its 3 instead of 2 (ending at two and not going to 3) x[:,1:3] = imputer.transform(x[:,1:3]) # Encoding Categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder # LabelEncoder is a class that changes the categorical variables into a hierarchy of numeric values # OneHotEncoder is a class that creates dummy variables # Encode country column labelencoder_x = LabelEncoder() x[:,0] = labelencoder_x.fit_transform(x[:,0]) onehotencoder = OneHotEncoder(categorical_features = [0]) # 0 represents the index for the country column x = onehotencoder.fit_transform(x).toarray() # Encode purchase column labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) # Splitting dataset into test and train from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0) # random_state is like setting the seed # test_size 0.2 means that the test set contains 20% of the dataset # Feature Scaling from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() x_train = sc_x.fit_transform(x_train) x_test = sc_x.transform(x_test)
true
b3f6be1cba245f468e37e4e28d2e55076e6d9111
konjoinfinity/python-checkpoint
/oop.py
2,747
4.1875
4
# 1: Define a Vehicle class with the following properties and methods: # - `vehicle_type` # - `wheel_count` # - `name` # - `mpg`, a 'dict', with the following properties: # - `city` # - `highway` # - `combined` # - `get_vehicle_type` should return the `vehicle_type` # - `get_vehicle_drive` if the `wheel_count` for that class is "no wheels!" then # it should return "no wheels send it back to the shop" # otherwise it should return "I have {self.wheel_count} wheel drive" as a formatted string # # Your Vehicle class should take one extra argument in the __init__ method (a `dict`) with the above # attributes. Define the properties on the class from the dict that is passed in. # # Here's an example of the dict that will be passed in to your class: # # vehicle_dict_vehicle = { # "vehicle_type": "Vehicle", # "wheel_count": 'no wheels!', # "mpg": { # "city": 19, # "highway": 30, # "combined": 27 # }, # "name": "Unidentified Flying Object", # } class Vehicle: def __init__(self, vehicle_type, wheel_count, mpg, name): self.vehicle_type = vehicle_type self.wheel_count = wheel_count self.name = name self.mpg = {city, highway, combined} def get_vehicle_type(self): print(self.vehicle_type) def get_vehicle_drive(self): if self.wheel_count == "no wheels!": print("no wheels send it back to the shop") else: print(f"I have {self.wheel_count} wheel drive") # #2: Create a Motorcycle class that inherits from the Vehicle class and has the # following properties and methods: # - all the properties inherited from the Vehicle class # - method: `pop_wheelie` if `wheel_count` is not equal to 2 then it should return False # otherwise return "popped a wheelie!" class Motorcycle(Vehicle): def __init__(self, wheel_count): self.vehicle_type = vehicle_type self.wheel_count = wheel_count self.name = name self.mpg = {city, highway, combined} def pop_wheelie(self): if self.wheel_count != 2: print(False) else: print("popped a wheelie!") # #3: Define a Car class that inherits from the Vehicle class with the following properties and methods: # - all the properties inherited from the Vehicle class # - property: `wheel_count` defaults to 4 # - method: `can_drive` that should return 'Vrrooooom Vroooom' # #4: Define a Truck class that inherits from the Vehicle class with the following properties and methods: # - all the properties inherited from the Vehicle class # - method: `rev_engine` that should return a string 'rreevv!' # Commit when you finish working on these questions!
true
551010ad5f5ecc55e90a9d7dea65343d62f7ab15
marvage/Practice-Python
/problem10.py
1,498
4.3125
4
#List Overlap Comprehensions #Exercise 10 (and my Solution) from www.practicepython.com #This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. #Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. (Hint: Remember list comprehensions from Exercise 7). #The original formulation of this exercise said to write the solution using one line of Python, but a few readers pointed out that this was impossible to do without using sets that I had not yet discussed on the blog, so you can either choose to use the original directive and read about the set command in Python 3.3, or try to implement this on your own and use at least one list comprehension in the solution. #Extra: #Randomly generate two lists to test this import random #generate random lists randomlist1 = random.sample(range(10),5) randomlist2 = random.sample(range(10), 5) #list comparisons/comprehensions results = list(set(i for i in randomlist1 if i in randomlist2)) print "These are the random lists" print randomlist1, randomlist2 print "This is the overlap with duplicates removed:" print results
true
3581ebe6bca3cb2713e4d6601af4cce3f7a53bf9
fishofweb/python-programs
/thesaurus.py
993
4.375
4
print("Welcome to the Thesaurus App!\n") print("Choose a word from the thesaurus and I will give you the synonym.\n") my_dict = {"hot": ["warm", "fire"], "cold": ["chilly","cool"], "happy": ["content","glad"], "sad": ["gloomy","bad mood"], } print("Here are the words in the thesaurus:") for key in my_dict: print("\t\t- "+key) word = input("What word would you like a synonym for: ").lower().strip() if word not in my_dict.keys(): print(word,"is not in thesaurus") quit() for key,value in my_dict.items(): if word == key: print("Synonym of", key, "is",value[0]) choice = input("Would you like to see the whole thesaurus (yes/no): ").lower().strip() if choice == "yes": for k , v in my_dict.items(): print("Synonyms of",k,"are:") for val in v: print("\t\t-"+val) else: print("Thank you for using this app , Good Bye") quit() print("Thank you for using this app , Good Bye")
false
149d21cefd2181335ed048e0b881498668cc5421
fishofweb/python-programs
/database-admin.py
1,685
4.1875
4
print("Welcome to the Database Admin Program.\n") db = { "admin":"12345678", "shanza": "shanza1000", "sadaf": "sadaf1000", "ammara": "ammara1000", "mahnoor": "mano1000", "saniya": "saniya1000", "maryam": "maryam1000", "sonia": "sonia1000", } username = input("Enter your username: ").lower().strip() password = input("Enter your password: ").lower().strip() if username not in db.keys(): print("incorrect username") quit() if password not in db.values(): print("incorrect password") quit() if username == 'admin' and password == '12345678': print("welcome", username, "here is you database\n\n") for k , v in db.items(): print(k) print("user:",k,"\tpassword:",v) for user,passwd in db.items(): if user == username and password == passwd and username != 'admin' and password != '12345678': print("Hello",username,"You are logged in!") print("\n") change_pwd = input("Would you like to change your password(y/n): ").lower().strip() if change_pwd == 'y': new = input("Type your new password: ") if len(new)<8: print("Password is too short , type atleast 8 characters.") break new_confirm = input("Type your new password again: ") if new == new_confirm: db[username] = new_confirm print("your password is changed to", new_confirm) else: print("password mismatched") break else: print("ok your password is still", passwd) break print("\tUsername:",username,"\t\tpassword:",password)
false
94adddb0057e94366e19429f008a064a82bb88bf
krishols/pedal
/pedal/utilities/text.py
1,844
4.5
4
""" Utilities for handling English Language rules. """ def add_indefinite_article(phrase): """ Given a word, choose the appropriate indefinite article (e.g., "a" or "an") and add it the front of the word. Matches the original word's capitalization. Args: phrase (str): The phrase to get the appropriate definite article for. Returns: str: Either "an" or "a". """ if phrase[0] in "aeiou": return "an "+phrase elif phrase[0] in "AEIOU": return "An "+phrase elif phrase[0].lower() == phrase[0]: return "a "+phrase else: return "A "+phrase def escape_curly_braces(result): """ Replaces all occurrences of curly braces with double curly braces. """ return result.replace("{", "{{").replace("}", "}}") def safe_repr(obj, short=False, max_length=80) -> str: """ Create a string representation of this object using :py:func:`repr`. If the object doesn't have a repr defined, then falls back onto the default :py:func:`object.__repr__`. Finally, if ``short`` is true, then the string will be truncated to the max_length value. Args: obj (Any): Any object to repr. short (bool): Whether or not to truncate to the max_length. max_length (int): How many maximum characters to use, if short is True. """ try: result = repr(obj) except Exception: result = object.__repr__(obj) if short and len(result) >= max_length: result = result[:max_length] + ' [truncated]...' result = result return result def chomp(text): """ Removes the trailing newline character, if there is one. """ if not text: return text if text[-2:] == '\n\r': return text[:-2] if text[-1] == '\n': return text[:-1] return text
true
e802ccdf928c5da395ff846aba1f29338cc3321c
puneeth-techie/python-example
/cel_fan_To_fan_cel.py
484
4.21875
4
#Converting Celsius to Fahrenheit #Formula Fahrenheit = (Celsius * 1.8) + 32 Celsius = float(input('Enter the Celsius: ')) Fahrenheit = (Celsius * 1.8) + 32 print('%0.2f Celsius is equal to %0.2f Fahrenheit\n'%(Celsius, Fahrenheit)) #Converting Fahrenheit to Celsius #Formula Celsius = (Fahrenheit - 32) / 1.8 Fahrenheit = float(input('Enter the Fahrenheit value: ')) Celsius = (Fahrenheit - 32) / 1.8 print('%0.2f Fahrenheit is equal to %0.2f Farhenheit'%(Fahrenheit, Celsius))
false
ed2dee91f663f2dcd34b7b4c1f428bd7d1e918cb
LightbulbProductions/thinkpython
/function_demo.py
785
4.15625
4
def subtractor(a, b): """I subtract b from a and return the result""" print("I'm a function. My name is {}".format(subtractor.__name__)) print("I'm about to subtract {} and {}\n\n".format(a,b)) return a - b # i output a value by using the return statement if __name__ == '__main__': subtractor(3, 2) def function3(a=1, b=1): """I'm a function that calls other functions """ print("I'm {} and I'm about to call subtractor function".format(function3.__name__)) total = subtractor(a,b) print("I'm {} and I'm about to call print_function".format(function3.__name__)) print_function() print("I'm {} and I'm about return total".format(function3.__name__)) return total if __name__ == '__main__': total = function3() print("total is {}".format(total))
true
d0a9f3d4b33d1685a62bc506c2dc071f824d06d5
PrzemyslawMichalski/bootcamp_python
/różne/arytmetyka.py
647
4.15625
4
# 1. przypisz do zmiennych x i y # jakieś wartości liczbowe # 2. korzystajac z funkcji print # wypisz na ekranie podstawowe dzialania # arytmetyczne (dodawanie, odejmowanie, dzielenie # mnożenie, dzielenie całkowitem, reszta z dzielenia # potęgowanie ) # 3. uruchom program kilka razy dla różnych wartośći x i y """ dsd """ x = 10 y = 15 print("x=", x, "y=", y) # wywolanie print print("dodawanie:", x + y) print("odejmowanie:", x - y) print("mnożenie:", x * y) print("dzielenie:", x / y) print("dzielenie całkowite:", x // y) print("dzielenie modulo:", x % y) print("potęgowanie:", x ** y) # ctrl + alt + l
false
3bde2884de5102feae48b349ee66bf47213e368a
S1nEat3r/PythonJourney
/script.py
2,874
4.21875
4
#!/bin/python3 #Variables And Methods quote = "All is fair in love and war." print(quote) print(quote.upper()) #uppercase print(quote.lower()) #lowercase print(quote.title()) #title case print(len(quote)) name = "Simon" #string age = 37 #int(30) height = 5.10 #float float(5.9) print (int(age)) print (int(30.9)) print ("My name is " + name + "I am " + str(age) + " years old") age += 1 print (age) birthday = 1 age += birthday print(age) print('\n') #Functions print ("Here is an example Function:") def who_am_i(): #this is a function name = "Simon" age = 37 print ("My Name is " + name + " I am " + str(age) + " years old.") who_am_i() #adding parameters def add_one_hundred(num): print(num + 100) add_one_hundred(100) #multiple parameters def add(x,y): print (x + y) add(7,7) def square_root(x): print(x ** .5) square_root(64) print (square_root) def nl(): print('\n') nl() #Boolean expressions print ("Boolean expressions:") bool1 = True bool2 = 3*3 == 9 bool3 = False bool4 = 3*3 != 9 print (bool1,bool2,bool3,bool4) print(type(bool1)) nl() #Relational And Boolean Operators greater_than = 7 > 5 less_than = 5 < 7 greater_than_equal_to = 7 >= 7 less_than_equal_to = 7 <= 7 test_and = (7 >5) and (5 > 7) #True test_and2 = (7 > 5) and (5 > 7) #False test_or = (7 > 5) or (5 < 7) #True test_or2 = (7 > 5) or (5 > 7) #True test_not = not True #False test_not2 = not False #True nl() #Conditional Statements def drink(money): if money >= 2: return "You've got yourself a drink" else: return "NO drink for you!" print(drink(3)) print(drink(1)) def alcohol(age,money): if (age >= 21) and (money >= 5): return "We're getting a drink!" elif (age >= 21) and (money < 5): return "Come back with more money" elif (age < 21) and (money >= 5): return "Nice try kid, come back when your 21" else: return "Your too poor and too young kid" print(alcohol(21,10)) print(alcohol(21,4)) print(alcohol(20,4)) nl() #Lists - Have brackets [] movies = ["The Hangover", "Halloween", "The Rock", "The Exorcist", "Top Gun"] print(movies[1]) #returns the second item print(movies[0]) #returns the first item in the list print(movies[1:4]) #returns all items from 2 to 4 print(movies[1:]) # returns all items in the list from second item print(movies[:2]) # returns all item in the list up to the 3rd item print(movies[-1]) # returns last item in the list print(len(movies)) movies.append("Jaws") print(movies) movies.pop(0) print(movies) nl() #Tuples - Do not change, () grades = ("a", "b", "c", "d", "f") print(grades[1]) nl() #Looping #For Loops - start to finish of an iterate vegetables = ["cucumber", "spinach", "cabbage"] for x in vegetables: print(x) #While loops - Execute as long as true i = 1 while i < 10: print(i) i += 1
false
95dbb6c0cd20090caacfda04e7ba966059bf228c
dpk3d/HackerRank
/ParenthesisChecker.py
1,958
4.375
4
""" https://practice.geeksforgeeks.org/problems/parenthesis-checker2744/1 Given an expression string x. Examine whether the pairs and the orders of {,},(,),[,] are correct in exp. For example, the function should return 'true' for exp = [()]{}{[()()]()} and 'false' for exp = [(]). Note: The drive code prints "balanced" if function return true, otherwise it prints "not balanced". Example 1: Input: {([])} Output: true Explanation: { ( [ ] ) }. Same colored brackets can form balanced pairs, with 0 number of unbalanced bracket. Example 2: Input: () Output: true Explanation: (). Same bracket can form balanced pairs, and here only 1 type of bracket is present and in balanced way. Example 3: Input: ([] Output: false Explanation: ([]. Here square bracket is balanced but the small bracket is not balanced and Hence , the output will be unbalanced. """ # Create an empty stack to keep track of opening parentheses. # Loop through each character in the input string. # If the character is an opening parentheses, push it onto the stack. # If the character is a closing parentheses, pop the top element from the stack and # check whether it matches the corresponding opening parentheses for the current closing parentheses. # If the stack is empty and all parentheses have been matched, return True. Otherwise, return False. def isValid(self, s: str) -> bool: stack = [] for char in s: if char == '(' or char == '{' or char == '[': stack.append(char) else: if not stack: return False if char == ')' and stack[-1] == '(': stack.pop() elif char == '}' and stack[-1] == '{': stack.pop() elif char == ']' and stack[-1] == '[': stack.pop() else: return False return not stack
true
5815114592824cfae3a2ae06d555085925fef282
dpk3d/HackerRank
/AmazonBinaryDigit.py
969
4.28125
4
""" Given an array of binary digits, 0 and 1, sort the array so that all 0 are at one end and all the 1 are at other end, which end doesn't matter. To sort the array swap any two adjacent elements. Determine the minimum Number of swap to sort the array. Example: arr=[0,1,0,1] -> with one move switching element 1 and 2 yields [0,0,1,1] Complete the function minMoves below. minMoves has following parameters : int arr[n] : An array of binary digits Return : Minimum number of moves required. """ def minMoves(arr): count = 0 numOfUnplacedZero = 0 for moves in range(len(arr)): if arr[moves] == 0: numOfUnplacedZero += 1 else: count += numOfUnplacedZero return count digits = [1, 1, 1, 1, 0, 1, 0, 1] print("Minimum Number of moves required to sort array is ", minMoves(digits)) # Minimum Number of moves required to sort array is 3 # This is not optimal solution but pases 12 test case out of 13.
true
5c21807e96ea9f9afde868c7c999df24772a71b4
dpk3d/HackerRank
/NumberOfPairs.py
2,251
4.1875
4
""" Given two arrays X and Y of positive integers, find the number of pairs such that x^y > y^x (raised to power of) where x is an element from X and y is an element from Y. """ # Time Complexity O( n * m ) def simpleApproach(arr1, len1, arr2, len2): pairs = 0 for a in range(len1): for b in range(len2): if pow(arr1[a], arr2[b]) > pow(arr2[b], arr1[a]): print("Pairs are ===>", arr1[a], arr2[b]) pairs += 1 return pairs arr1 = [2, 1, 6] arr2 = [1, 5] print("Number of Pairs count ==>", simpleApproach(arr1, 3, arr2, 2)) ## TODO : Need to work on this to handle exception and corner cases def binarySearchToGetIndex(arr, n, element): low = 0 high = n - 1 pairs = -1 while low <= high: mid = low + high // 2 if arr[mid] > element: pairs = mid high = mid - 1 else: low = mid + 1 print("Pairs === >>", pairs) return pairs # Time Complexity O ( n + m) # To Handle Exception and corner cases , need to call binarySearchToGetIndex method in below method. def numberOfPairs(deepArray, moniArray, deepLength, moniLength): zeros = 0 one = 0 two = 0 three = 0 four = 0 deepArray.sort() moniArray.sort() for x in range(moniLength): if moniArray[x] == 0: zeros += 1 if moniArray[x] == 1: one += 1 if moniArray[x] == 2: two += 1 if moniArray[x] == 3: three += 1 if moniArray[x] == 0: four += 1 # Traversing in First Array pairs = 0 for x in range(deepLength): if deepArray[x] == 0: continue elif deepArray[x] == 1: pairs += 1 elif deepArray[x] == 2: pairs += one + zeros pairs -= three pairs -= four else: pairs += one + zeros return pairs deepArray = [2, 1, 6, 8, 9, 0, 10, 11] moniArray = [1, 5, 0, 13, 2, 7, 9, 98] print("Number of Pairs count 2nd Approach ==>", numberOfPairs(deepArray, moniArray, 8, 8)) """ Output: Pairs are ===> 2 1 Pairs are ===> 2 5 Pairs are ===> 6 1 Number of Pairs count ==> 3 Number of Pairs count 2nd Approach ==> 12 """
true
7d51cee9a200c7c2f40fc3657844ca8314e7eba1
dpk3d/HackerRank
/MinimumPlatforms.py
1,353
4.46875
4
""" Given arrival and departure times of all trains that reach a railway station. Find the minimum number of platforms required for the railway station so that no train is kept waiting. Consider that all the trains arrive on the same day and leave on the same day. Arrival and departure time can never be the same for a train but we can have arrival time of one train equal to departure time of the other. At any given instance of time, same platform can not be used for both departure of a train and arrival of another train. In such cases, we need different platforms, """ # Time Complexity O (n + nlogn) def minimumPlatform(arrival, departure, n): platform = 1 required_platform = 1 arrival.sort departure.sort x = 1 y = 0 # Iterating in both array while (x < n and y < n): if arrival[x] <= departure[y]: platform += 1 x += 1 elif arrival[x] > departure[y]: platform -= 1 y += 1 if platform > required_platform: required_platform = platform return required_platform n = 6 arrival = [900, 940, 950, 1100, 1500, 1800] departure = [910, 1200, 1120, 1130, 1900, 2000] print("Platform Required is ===> ", minimumPlatform(arrival, departure, 6)) """ Output: Platform Required is ===> 3 """
true
a2b77186cc914d93ddb699895ea9678cf1655cb5
dpk3d/HackerRank
/MajorityElement.py
1,758
4.15625
4
""" Given an array of size n, find all elements in array that appear more than n/k times. For example, if the input arrays is {3, 1, 2, 2, 1, 2, 3, 3} and k is 4, then the output should be [2, 3]. Note that size of array is 8 (or n = 8), so we need to find all elements that appear more than 2 (or 8/4) times. There are two elements that appear more than two times, 2 and 3. https://www.geeksforgeeks.org/given-an-array-of-of-size-n-finds-all-the-elements-that-appear-more-than-nk-times/ """ def moreThanNbyK(arr, k): number = len(arr) // k unorderedMap = {} # unordered_map initialization for x in range(len(arr)): if arr[x] in unorderedMap: unorderedMap[arr[x]] += 1 else: unorderedMap[arr[x]] = 1 # Traversing the unorderedMap for y in unorderedMap: # Checking if value of a key-value pair is greater than x (where x = len(array) // k) if unorderedMap[y] > number: print(y , end= " ") arr = [1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1] k = 4 moreThanNbyK(arr, k) # Using Boyer-Moore Majority Vote Algorithm - Time complexity - O(N) def majorityElement(arr, k): if not arr: return [] count1, count2, candidate1, candidate2 = 0, 0, 0, 0 for x in arr: if x == candidate1: count1 += 1 elif x == candidate2: count2 += 1 elif count1 == 0: candidate1, count1 = x, 1 elif count2 == 0: candidate2, count2 = x, 1 else: count1, count2 = count1 - 1, count2 - 2 return [x for x in (candidate1, candidate2) if arr.count(x) > len(arr) // k] arr = [3, 1, 2, 2, 1, 2, 3, 3] k = 4 print("Elements appearing more than n/k is : ", majorityElement(arr, k))
true
04c18bf08827463218ebe45699de708766c6f435
dpk3d/HackerRank
/InversionCount.py
2,889
4.15625
4
""" Given an array of integers. Find the Inversion Count in the array. Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum. Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j. """ ############################################################################ def SimpleInversionCount(arr): count = 0 for x in range(len(arr)): for y in range(x + 1, len(arr)): if arr[x] > arr[y]: count += 1 return count arr = [2, 0, 4, 3, 9, 8, 9, 7, 10] print("Inversion count is ==>", SimpleInversionCount(arr)) ############################################################################ def InversionCountMergeSort(input_arr, n): # A resulting_arr is temporary array to store sorted array of merge func. resulting_arr = [0] * n return mergeSort(input_arr, resulting_arr, 0, n - 1) # This Function will use MergeSort to count inversions def mergeSort(input_arr, resulting_arr, left, right): inversion_count = 0 # Making recursive call only if more than one elements are there if left < right: # mid is dividing array into 2 sub arrays mid = (left + right) // 2 # Calculating inversion counts in the left sub array inversion_count += mergeSort(input_arr, resulting_arr, left, mid) # Calculating inversion counts in right sub array inversion_count += mergeSort(input_arr, resulting_arr, mid + 1, right) # Merge 2 sub arrays into a sorted one inversion_count += final_merge(input_arr, resulting_arr, left, mid, right) return inversion_count # Merge two sub arrays into a single sorted sub array def final_merge(input_arr, resulting_arr, left, mid, right): a = left b = mid + 1 c = left inv_count = 0 # No Inversion here while a <= mid and b <= right: if input_arr[a] <= input_arr[b]: resulting_arr[c] = input_arr[a] c += 1 a += 1 else: # Inversion resulting_arr[c] = input_arr[b] inv_count += (mid - a + 1) c += 1 b += 1 # Copying remaining array to left sub array while a <= mid: resulting_arr[c] = input_arr[a] c += 1 a += 1 # Copying remaining array to right sub array while b <= right: resulting_arr[c] = input_arr[b] c += 1 b += 1 # Copying the sorted array into final array for x in range(left, right + 1): input_arr[x] = resulting_arr[x] return inv_count arr = [1, 3, 4, 8, 20, 0, 11, 20, 6, 4, 5] n = len(arr) result = InversionCountMergeSort(arr, n) print("Number of inversions are", result)
true
40380ebad4b1725941f360569bda5e2d4b67cab0
dpk3d/HackerRank
/WordBreak.py
2,943
4.21875
4
""" https://practice.geeksforgeeks.org/problems/word-break1352/1 Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words. Note: From the dictionary B each word can be taken any number of times and in any order. Example 1: Input: n = 12 B = { "i", "like", "sam", "sung", "samsung", "mobile", "ice","cream", "icecream", "man", "go", "mango" } A = "ilike" Output: 1 Explanation: The string can be segmented as "i like". Example 2: Input: n = 12 B = { "i", "like", "sam", "sung", "samsung", "mobile", "ice","cream", "icecream", "man", "go", "mango" } A = "ilikesamsung" Output: 1 Explanation: The string can be segmented as "i like samsung" or "i like sam sung". Expected time complexity: O(s2) Expected auxiliary space: O(s) , where s = length of string A """ def wordBreakDP(given_string, given_dictionary): # dp_arr initialized to all FALSE dp_arr = [False] * (len(given_string) + 1) # Setting to True as a Base case dp_arr[0] = True # This loop will be ahead of inner loop for x in range(1, len(given_string) + 1): # this loop will start at input_string[0] and increment up to x # Checking each time if input_string[y:x] matches in input_dictionary for y in range(x): # dp_arr[y] tells us if we have successfully created a word up to that index. # Checking dp_arr[y] helps us ensure that we're only marking tracker True when words are adjacent. if dp_arr[y] and given_string[y:x] in given_dictionary: dp_arr[x] = True break # control goes to outer loop to increment x return dp_arr[-1] input_dictionary = {"i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"} input_string = "ilikesamsung" print("We can able to break the word : ", wordBreakDP(input_string, input_dictionary)) # We can break the word : True def wordBreakDPAnother(given_string, given_dictionary): # dp_array initialized to all FALSE dp_array = [False] * (len(given_string) + 1) # Setting to True as a Base case dp_array[0] = True for x in range(1, len(given_string) + 1): # check each word in wordDict rather than iterating from 0 to i for word in given_dictionary: if len(word) > x: continue if given_string[x - len(word):x] == word and dp_array[x - len(word)]: dp_array[x] = dp_array[x - len(word)] break return dp_array[len(given_string)] input_dictionary = {"i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"} input_string = "ilikesamsung" print("We can able to break the word : ", wordBreakDPAnother(input_string, input_dictionary))
true
d68bf8c7f1d677d1e5794b4be0da1b2cc37ae015
dpk3d/HackerRank
/sortWithoutUsingFunction.py
911
4.4375
4
""" Sort A Given List/Array. data_list = [-5, -23, 5, 0, 23, -6, 23, 67] """ data_list = [-5, -23, 5, 0, 23, -6, 23, 2, 67] # Using 2 for loops to sort list not recommended solution # Complexity of this approach is n * n for x in range(0, len(data_list)): for y in range(x + 1, len(data_list)): if data_list[x] > data_list[y]: data_list[x], data_list[y] = data_list[y], data_list[x] print("For Loop : Sorted List is ==>", data_list) """ For Loop : Sorted List is ==> [-23, -6, -5, 0, 2, 5, 23, 23, 67] """ # While Loop Another Approach better than using two for loops. new_list = [] while data_list: lowest = data_list[0] for x in data_list: if x < lowest: lowest = x new_list.append(lowest) data_list.remove(lowest) print(" While Loop : Sorted List is ==> ", new_list) """ For Loop : Sorted List is ==> [-23, -6, -5, 0, 2, 5, 23, 23, 67] """
true
ffae53eaa3cc09c504781c26f80e4adc3a55e40c
TobyChen320/CSPT15_HashTables_II
/src/demos/demo2.py
1,694
4.5
4
""" Given a string, sort it in decreasing order based on the frequency of characters. Example 1: ```plaintext Input: "free" Output: "eefr" Explanation: 'e' appears twice while 'f' and 'r' appear once. So 'e' must appear before 'f' and 'r'. Therefore, "eerf" is also a valid answer. ``` Example 2: ```plaintext Input: "dddbbb" Output: "dddbbb" Explanation: Both 'd' and 'b' appear three times, so "bbbddd" is also a valid answer. Note that "dbdbdb" is incorrect, as the same characters must be together. ``` Example 3: ```plaintext Input: "Bbcc" Output: "ccBb" Explanation: "ccbB" is also a valid answer, but "Bbcc" is incorrect. Note that 'B' and 'b' are treated as two different characters. ``` """ # use the counter from collections to save us some time import collections def frequency_sort(s: str) -> str: """ Inputs: s -> str Output: str """ # Your code here # count up all of the occurrences of each letter # ref: https://docs.python.org/3/library/collections.html#collections.Counter letters_count = collections.Counter(s) # create a list to build the string string_build = list() # [] # iterate over the sorted counts (using the ".most_common()" method) extracting the letter and frequency key value pair for letter, frequency in letters_count.most_common(): # letter * frequency # "V" * 5 -> "VVVVV" # append the letter * frequency to the string_build list string_build.append(letter * frequency) # turn the list back in to a string and return it (use a join?) return "".join(string_build) print(frequency_sort("free")) # => "eefr" print(frequency_sort("dddbbb")) # => "dddbbb"
true
52bdaae5ae41eb2045cd11d4df386534a09c5165
mauabe/python-thw
/ex3.py
506
4.125
4
print ("I will now count my chickens") print ("Hens", 25 + 30.0 / 6) print ("Roosters", 100 - 25 * 3 % 4) print ("Now I will count the eggs:") print (3.0 + 2 + 1 - 5.0 + 4 % 2 - 1 / 4.0 + 6.0) print ("Is it true that 3 + 2 < 5 - 7?") print (3 + 2 < 5 - 7) print ("What is 3 + 2?", 3 + 2) print ("What is 5 - 7?", 5 - 7) print ("Oh, that is wha it's False.") print ("How about some more.") print ("Is it greater?", 5 > -2) print ("Is it greater or equal?", 5 >= -2) print ("Is it less or equal?", 5 <= -2)
true
c048d4b596c44f713a76df3686b5ed44cc9275cb
UnSi/2_GeekBrains_courses_algorithms
/Lesson 3/hw/task5.py
822
4.40625
4
# 5. В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. # Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». # Это два абсолютно разных значения. from random import randint MIN_VALUE = -100 rand_array = [randint(MIN_VALUE, 100) for _ in range(50)] print(rand_array) max_number = MIN_VALUE for i, number in enumerate(rand_array): if 0 > number > max_number: max_number = number pos = i print(f"Максимальное отрицательное число: {max_number}, индекс {pos}, позиция: {pos+1}")
false
26896d0a35149e576c7e163e23c331af5794880b
The-Wayvy/Intro_to_CS_MIT_OCW
/pset_02/hangman.py
2,395
4.25
4
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) def print_word(word,guessed_letters): to_print = "" for letter in word: if letter in guessed_letters: to_print += letter else: to_print += "?" return to_print def finished(word,guessed_letters): for letter in word: if letter not in guessed_letters: return False else: return True # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() secret_word = choose_word(wordlist) guesses_remaining = 7 guessed_letters = [] print "Welcome to hangman!" while guesses_remaining > 0: print "==========================================" print "you have",guesses_remaining,"guesses left" print "you've guessed the following letters",guessed_letters print "the word so far:",print_word(secret_word,guessed_letters) guess = raw_input("guess a letter: ") while guess in guessed_letters: print "you already guessed that!" guess = raw_input("guess a letter: ") if guess in secret_word: print "good guess" guessed_letters.append(guess) if finished(secret_word,guessed_letters): print "==================================" print "You win!" print "the word was",secret_word,"!!" break else: print "sorry" guesses_remaining -= 1 guessed_letters.append(guess) else: print "===============================" print "sorry, you lost" print "the word was",secret_word
true
0508f833481927c25028946b78825f3f8736986d
philipteu/Fibonacci-Sequence
/Fibonacci Sequence.py
353
4.125
4
#Fibonacci Sequence def Fibonacci(n): if n < 0: print('Invalid Input') elif n <= 1: return n else: return (Fibonacci(n-1)+ Fibonacci(n - 2 )) #F= Fn-1 + Fn-2 n= int(input('This is Fibonacci Sequence. Enter the iteration: ')) for i in range(n): print(Fibonacci(i)) #0,1,1,2,3,5,8,13,21,34,55
false
46cdb00040fece861462422e46590373a8983cc4
Psandoval93/HigherLowerGame
/HigherLowerGame.py
1,380
4.21875
4
# Import random class import random # Receiving/assigning variables & seed value seed_value = int(input("What seed should be used? ")) random.seed(seed_value) lower = int(input('What is the lower bound?')) upper = int(input('What is the upper bound?')) # Creating loop statement & condition while lower > upper: print('Lower bound must be less than upper bound.') # Receiving user input and assigning variable lower = int(input('What is the lower bound?')) upper = int(input('What is the upper bound?')) # Assigning variable for number to win game rand_num = random.randint(lower, upper) # Assigning variable in order to quit game user_quits = 00 # Receive user input and assigning to variable for guess at winning number user_guess = int(input('What is your guess?')) # Creating loop statement & conditions while user_guess != user_quits: # Creating if, if else, and if else statements with conditions for output if user_guess < rand_num: print('Nope, too low.') user_guess = int(input('What is your guess? ')) elif user_guess > rand_num: print('Nope, too high.') user_guess = int(input('What is your guess? ')) elif user_guess == rand_num: print('You got it!') else: # user_guess == rand_num print('You have quit the game. Thank you for playing')
true
2649ef9301c51fda72a8138bc5be11dd52692f1b
Maryanushka/MITx-6.00.1-2017-
/week2/Problem 2 other solution.py
1,798
4.375
4
# ----------------------------another solution------------------------ # PROBLEM 2: PAYING DEBT OFF IN A YEAR (15 points possible) # Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within # 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant # amount that will be paid each month. # In this problem, we will not be dealing with a minimum monthly payment rate. # The following variables contain values as described below: # balance = 3329 # # annualInterestRate = 0.2 # # # The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: # # lowestPayment = 0 # finding = True # # # def payment(balance, annualInterestRate, lowestPayment): # month = 1 # while month <= 12: # # # Monthly interest rate= (Annual interest rate) / 12.0 # monthlyIntRate = annualInterestRate / 12.0 # # # Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) # balance -= lowestPayment # # # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) # balance += (monthlyIntRate * balance) # # month += 1 # # if balance <= 0: # return lowestPayment # else: # return False # # # while finding == True: # if payment(balance, annualInterestRate, lowestPayment): # finding = False # print # 'Lowest Payment:', payment(balance, annualInterestRate, lowestPayment) # else: # lowestPayment += 10 # payment(balance, annualInterestRate, lowestPayment) # ------------------another solution--------------------------------
true
fa8b56d81d03077d615920df4df46669cfca8b0d
blane612/-variables
/example_code.py
2,062
4.75
5
# author: elia deppe # date: 6/6/21 # # description: example code for variable exercises # Saving a String to a variable. name = 'elia' # ----- Printing the contents of the variable. print('my name is', name) # using regular strings print(f'my name is {name}') # using f-strings # When inserting a variable into an f-string, simply surround the name of the variable with {} # Notice that the color of the curly braces and the variable aren't the same color as the string. This helps us # identify what is and what isn't a string. Notice also that the curly braces aren't printed either, only the contents # of the variable. # ----- Saving a number to a variable. num1 = 7 num2 = 11.5 num3 = -21 print('here are a few numbers:', num1, num2, num3) # regular string print(f'here are a few numbers: {num1}, {num2}, {num3}') # f-string # ----- Overwriting Variables (Re-Use) num1 = 121 num2 = 4.422 num3 = -31.23 # Variables can switch types at any point, so feel free to save whatever you want to any variable! print('here are the same variables, but now with different values:', num1, num2, num3) print(f'here are the same variables, but now with different values: {num1}, {num2}, {num3}') # ----- Saving the Result of an Operation to a Variable num1 = 15 - 2 num2 = 12 / 3 num3 = -2 * 4.5 print('nums:', num1, num2, num3) print(f'nums: {num1}, {num2}, {num3}') # ----- Using Variables in Operations num1 = num2 + num3 num2 = num1 - 15 num3 = num3 * 2 # You can use a variable in an operation that is assigning to itself! print(f'nums: {num1}, {num2}, {num3}') # ----- String Duplication # String duplication is where you duplicate strings using multiplication. # For example, if I wanted to duplicate 'cat' 5 times then: print('cat' * 5) # Yes, you're allowed to do operations in functions, remember that the result is what matters! print('dog' * 3, 'gone' * 3) # If you want to duplicate a string inside a variable, simply multiply the variable by a number cash = '$' hashtag = '#' print(cash * 5, hashtag * 3, cash * 5)
true
6ebc6ad98fa1996c1c20ce7bbdb792c6d1d61d48
RayOct18/effective_python
/46_property_decorator.py
2,058
4.125
4
class Grade2: def __init__(self): self._value = 0 def __get__(self): return self._value def __set__(self, value): if not (0 <= value <= 100): raise ValueError('Grade must be between 0 and 100.') self._value = value class Exam2: def __init__(self): # create different object when Exam2 is created self.math_grade = Grade2() self.writing_grade = Grade2() self.science_grade = Grade2() class Grade: # use dictionary to save different instance's value def __init__(self): self._value = {} def __get__(self, instance, instance_type): if instance is None: return self return self._value.get(instance, 0) def __set__(self, instance, value): if not (0 <= value <= 100): raise ValueError('Grade must be between 0 and 100.') self._value[instance] = value class Exam: # use same object math_grade = Grade() writing_grade = Grade() science_grade = Grade() if __name__ == '__main__': first_exam = Exam() first_exam.writing_grade = 82 first_exam.science_grade = 99 print('Writing', first_exam.writing_grade) print('Science', first_exam.science_grade) second_exam = Exam() second_exam.writing_grade = 88 second_exam.science_grade = 95 print('Writing', second_exam.writing_grade) print('Science', second_exam.science_grade) print('Writing', first_exam.writing_grade) print('Science', first_exam.science_grade) print('=' * 20) first_exam = Exam2() first_exam.writing_grade = 82 first_exam.science_grade = 99 print('Writing', first_exam.writing_grade) print('Science', first_exam.science_grade) second_exam = Exam2() second_exam.writing_grade = 88 second_exam.science_grade = 95 print('Writing', second_exam.writing_grade) print('Science', second_exam.science_grade) print('Writing', first_exam.writing_grade) print('Science', first_exam.science_grade)
true
628820783ca7a797023d5d7d8bfee7fb5b8cd9d5
joaomendonca-py/tip-calculator-start
/main.py
1,525
4.125
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪 #HINT 1: https://www.google.com/search?q=how+to+round+number+to+2+decimal+places+python&oq=how+to+round+number+to+2+decimal #HINT 2: https://www.kite.com/python/answers/how-to-limit-a-float-to-two-decimal-places-in-python print("Welcome to the tip calculator.") bill = input("What was the total bill? ") percentage = input("What percentage tip would you like to give? 10, 12 or 15? ") manyPeople = input("How many people to split the bill? ") bill_int = float(bill) percentage_int = float(percentage) manyPeople_int = int(manyPeople) result = round((bill_int * (1 + (percentage_int / 100))) / manyPeople_int, 2) pay = (f"Each person should pay: {result}") print(pay) """ print("Welcome to the tip calculator!") bill = float(input("What was the total bill? $")) tip = int(input("How much tip would you like to give? 10, 12, or 15? ")) people = int(input("How many people to split the bill?")) tip_as_percent = tip / 100 total_tip_amount = bill * tip_as_percent total_bill = bill + total_tip_amount bill_per_person = total_bill / people final_amount = round(bill_per_person, 2) #FAQ: How to round to 2 decimal places? #https://www.udemy.com/course/100-days-of-code/learn/lecture/17965132#questions/13315048 print(f"Each person should pay: ${final_amount}")"""
true
58c62ed2048d5255e99700d2f0e43ae701849bc6
kuan1/test-python
/30days/day04_string/02_method.py
847
4.4375
4
# Accessing Characters in Strings by Index print('Python'[2]) # Slicing Python Strings print('Python'[0:2]) print('Python'[-3:]) print('Python'[1:]) # Reversing a String print('Python'[::-1]) # Skipping Characters While Slicing print('Python'[0::2]) # capitalize print('python'.capitalize()) # count print('python python'.count('p')) # endswith print('Python'.endswith('on')) # startswith print('Python'.startswith('P')) # find print('thirty days of python'.find('y')) # 5 print('thirty days of python'.find('th')) # 0 print('a'.find('b')) # rfind print('thirty days of python'.rfind('y')) # 16 print('thirty days of python'.rfind('th')) # 17 # index print('abc'.index('a')) print('abc'.index('c')) # print('abc'.index('d')) # join print('|'.join(["a", "b", "c"])) # split print('1,2,3,4'.split(',')) print(type('1,2,3,4'.split(',')))
false
a945f0f5dfd7632cd84b894bde2cc233cd1a71c1
milinilla/Practice
/are_anagrams.py
1,122
4.375
4
def are_anagrams(s1, s2, s3): """ we convert function arguments into the list, as it would be easier to deal with it later on, as every argument needs to be the subject of the same actions """ arr = [s1, s2, s3] """ we check if the length of all arguments doesn't exceed the provided limit of 5 characters """ if not all(len(item)<= 5 for item in arr): return("Sorry, all \"are_anagrams\" function arguments shall be "\ "at most 5 characters long.") """ first, we unify the formating of input data by lowering the case, next we convert every string into the list of characters, which is then sorted in alphabetical order to allow the verification if every string consists of the same characters """ arr = [sorted(list(x.lower())) for x in arr] """ first idea was to just compare every element of the list (arr[0]==arr[1]==arr[2]), but to make the code scalable we compare if the first element of the list appears the same number of times as the number of all list elements """ return(arr.count(arr[0])==len(arr))
true
b7ca6eb34a68da479904f6b93a9dc692f336850e
YvesIraguha/pythonlearning
/simple_game/calculator.py
2,534
4.40625
4
def calculator(): print "Welcome to caclcualator \n you can calculate any number you want" print "Here there are many operations." print "write add to add two numbers" print "Write multiply to multiply two numbers" print "Write divide to make division of two numbers" print "Write substract to substract one number from another" print "Write remainder to know the \n remainder of division of one number with another" print "Write square to square a number. " def addition(): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number + second_number print "From the calculation the result is %s "%result def substraction(): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number - second_number print "From the calculation the result is %s "%result def multiplication (): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number * second_number print "From the calculation the result is %s "%result def division (): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number / second_number print "From the calculation the result is %s "%result def squaring(): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number ** second_number print "From the calculation the result is %s "%result def remainder(): first_number=float(raw_input("Enter the first number: ")) second_number = float(raw_input("Enter the second number: ")) result = first_number % second_number print "From the calculation the result is %s "%result def calculation(): user_command = str(raw_input("Can you write your operation: ")) if user_command== "add": addition() elif user_command=="multiply": multiplication() elif user_command== "divide": division() elif user_command=="substract": substraction() elif user_command=="remainder": remainder() elif user_command=="square": squaring() else: print "Incorrect operation!" move_out = str(raw_input("Do you want to make more calculation: ")) if move_out == "yes": calculation() else: print "Thank you for using this awesome calculator" calculation() calculator()
true
4c508bf06a0d87676b0168988eba6ed00ed47bfa
Andrei-Kulik/python_for_dqe
/Module_1.py
1,869
4.21875
4
# importing 'randint' method for creating new list with random numbers from random import randint # declaring size of list 'n' n = 100 # declaring new empty list 'a' a = [] # loop for creating our new list for i in range(n): # 'append' method for adding new elements to list # 'randint' method for creating a random number from 0 to 1000 a.append(randint(1, 1000)) # sorting algorithm (I used bubble sorting) # index 'i' we will use for further reducing our scope of unsorted numbers for i in range(len(a) - 1): # index 'j' we will use for list elements iterations # we need to find maximum form the list and put it at the end # after we decrease our range() on 'i', because we no longer need to compare sorted items at the end for j in range(len(a) - 1 - i): # comparing element with next element if a[j] > a[j + 1]: # replacing elements with each other a[j], a[j + 1] = a[j + 1], a[j] # declaration variables for counting average values (sum / count = average) even_sum, even_count = 0, 0 odd_sum, odd_count = 0, 0 # loop for counting sum and count for even and odd elements for elem in a: # sum and count for even elements (even % 2 == 0) if elem % 2 == 0: # increasing the sum on element value even_sum += elem # increasing the count on one element even_count += 1 # sum and count for odd elements else: # increasing the sum on element value odd_sum += elem # increasing the count on one element odd_count += 1 # printing final results # added converting to the 'int' type to round float values (* optional) # also added converting average values to the 'str' type for concatenating with the string print('Even average: ', str(int(even_sum / even_count))) print(' Odd average: ', str(int(odd_sum / odd_count)))
true
77be81fd9138f3ef5eed7432a1733f16553f1124
jharp9077/CTI110
/P2HW1_PoundsKilograms_JordanHarper.py
521
4.1875
4
# Calculates the conversion of pounds to kilograms # 4 Febuary 2019 # CTI-110 P2HW1 - Pounds to Kilograms Converter # Jordan Harper # # Get pounds # convert total kilograms # display kilograms # Get the total kilograms pounds = float(input('Enter the number of pounds: ')) # calculate pounds to kilograms by doing the equation pounds times 1kg devided by 2.21 equals total KG kilograms = pounds * 1/2.2046 # display the total amount of kilograms print ('Pounds equals number of kilograms ', kilograms, 'kg')
true
9175767b47d02926234c300f97bc12e256351aad
jharp9077/CTI110
/P4HW2_ PoundsKilos _JordanHarper.py
636
4.1875
4
# Calculates the conversion of pounds to kilograms # 5 March 2019 # CTI-110 P4HW2 - Pounds to Kilograms table # Jordan Harper # # Get pounds # convert total kilograms # display kilograms # Get the total kilograms def kilo_table(): # Defined pounds in the range using start stop step format for pounds in range(100, 301, 10): # Enter the formula held in a variable format kilograms = pounds / 2.2046 # Displays result specifically calling for 2 decimal places. print("{:.2f}".format(kilograms), 'kg') kilo_table()
true
a98dc9f4ad246805c593b5ed0582f7fc8ef6b482
jcattanach/python-practice
/practice6.py
526
4.46875
4
# Ask the user for a string and print out whether # this string is a palindrome or not. user_string = input("Enter a word: ").lower() def reverse(string): new_string = "" for index in range(len(string) -1, -1, -1): new_string = new_string + string[index] return new_string def is_palindrome(reversed): if(reversed == user_string): print("{0} is a palindrome.".format(user_string)) else: print("{0} is NOT a palindrome.".format(user_string)) is_palindrome(reverse(user_string))
true
c3c8e7f98315dd8c316f084f1517d3f583b8d5b8
truptikolte/Learn-Python
/datatype.py
226
4.125
4
str = 'Good Morning' # string data type num = 123 #integer data type fnum = 3.14 # float data type print(str,num,fnum) print(type(str)) print(type(num)) print(type(fnum)) # type function return the data type of any variable
true
50bf2e4bc5e0e0f47378e12a34b4ef23b35c7ab5
Saeed-Jalal/Basics-of-python
/Basics of python.py
1,206
4.34375
4
#Arithmetic Operators num1=60 num2=45 print(num1+num2) print(num1-num2) print(num1*num2) print(num1//num2) print(num1%num2) print(7**3) #Assignemt Operator num3= num1+num2 print(num3) num3+=num2 print(num3) #Comparsion Operator print(num3>num2) print(num2==num3) print(num1!=num2) #Logical Operators A=True B=False print(A and B) print(A or B) print(not A) #Identity Operators X = 5 X is 5 X = 5 X is not 5 #Membership Operators ABC=[1,2,3,4,5,6,7,8,9] 4 in ABC 6 not in ABC #Python has two types of Data 1. Immutable (Numbers, Strings, Tuples) 2. Mutable (Lists, Dictionaries, Sets) #Numbers(Integer,Float and Complex) #Strings name1="My name is Saeed." name2="I am genius." #Concatenation print(name1+name2) #Repetition print(name1*2) #Slicing print(name2[2:7]) #find() print(name1.find('S')) # replace() print(name2.replace("am","can be")) # split() job="Don" print(job.split(",")) # count() print(name1.count("a")) #upper print(name1.upper()) #max print(max(name2)) #min str="HOME" print(min(str)) #isalpha print(name1.isalpha()) #Tuples myTup = ("Home","Office","Car","Computer") #Concatenation print(myTup+("Copter","Ship")) #Reprtition print(myTup*2) #Slicing print(myTup[1:3]) #
true
bccd0f8e1a1ede2fc7ba425da057723a1d4219fd
StarbzYT/Sorting-Algorithms
/Merge_Sort/merge.py
773
4.21875
4
import merging_arrays # merge func to merge two sorted arrays # Pseudocode # Break up the array into halves until you have arrays that are empty or have one element # Once you have smaller sorted arrays, merge those arrays with other # sorted arrays until you are back at the full length of the array # once the array has been merged back together, return the merged (and sorted!) array def merge(arr): if len(arr) <= 1: # base case return arr mid = len(arr) // 2 # floored left = merge(arr[0:mid]) # 0 to mid (exclusive) right = merge(arr[mid::]) # mid to end return merging_arrays.merge(left, right) # keep merging left and right sorted arrays print(merge([1, 18, 6, 41, 3, 100])) # [1, 3, 6, 18, 41, 100]
true
610519db921e71a98636862398b2351bd2041b61
dilayercelik/CSE160-Data-Programming-UW
/Lists Check-in/make_out_word.py
748
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon May 18 19:45:20 2020 @author: dilayerc """ # Practice # Given an "out" string length 4, such as "<<>>", and a word, # return a new string where the word is in the middle of the out string, # e.g. "<<word>>". # Examples: ## make_out_word('<<>>', 'Yay') → '<<Yay>>' ## make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>' ## make_out_word('[[]]', 'word') → '[[word]]' # Answer def make_out_word(out, word): new_string = out[:2] + word + out[2:] return new_string # Tests print(make_out_word('<<>>', 'Yay')) # correct output print(make_out_word('<<>>', 'WooHoo')) # correct output print(make_out_word('[[]]', 'word')) # correct output
true
3c456176c6968092afb32d106ba629d9243d8487
dilayercelik/CSE160-Data-Programming-UW
/Loops, If, & Functions Check-in/sum_odds.py
740
4.25
4
# -*- coding: utf-8 -*- """ Created on Thu May 14 23:11:57 2020 @author: Dilay Ercelik """ # Return the sum of the odd ints in the given list. # Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. # Examples: ## sum_odds([5, 2, 6, 3, 4]) → 8 ## sum_odds([3, 6, 11, 2, 5]) → 19 ## sum_odds([]) → 0 # Answer: def sum_odds(nums): sum_odd = 0 for num in nums: if num % 2 == 1: sum_odd += num return sum_odd # Tests: print(sum_odds([5, 2, 6, 3, 4])) # correct output print(sum_odds([3, 6, 11, 2, 5])) # correct output print(sum_odds([])) # correct ouput
true
9b1a98d704ca48daabc4380d415f88e60371ecb6
dilayercelik/CSE160-Data-Programming-UW
/Lists Check-in/front_back.py
532
4.25
4
# Practice # Given a string, return a new string where the first and last chars have been exchanged. # Examples: ## front_back('code') → 'eodc' ## front_back('a') → 'a' ## front_back('ab') → 'ba' # Answer def front_back(str): if len(str) > 1: new_string = str[-1] + str[1:-1] + str[0] else: new_string = str return new_string # Tests print(front_back('code')) # correct output print(front_back('a')) # correct output print(front_back('ab')) # correct output
true
eef4aa43fb7507de91bd76870d2bb0bdfeb77a18
Kaminagiyou123/python_practice
/Games/randomnumber.py
802
4.28125
4
import random def guess(x): random_number=random.randint(1,x); guess=0; while guess!=random_number: guess=int(input(f"guess the number between 1 and {x}: ")); if guess<random_number: print("sorry, the guess is too low") elif guess>random_number: print("sorry the guess is too high") print(f"yay congrats, you got the number {random_number}") def computer_guess(x): low=1; high=x; feedback="" while feedback!="c": if low!=high: guess=random.randint(low,high) else: guess=low; feedback =input(f"Is {guess} to high (H),too low (L), or correct(C)").lower(); if feedback=="h": high=guess-1; elif feedback=="l": low=guess+1; print(f"yay, computer got the number {guess}, correctly") computer_guess(10)
true
ccbcc6245e68930e7d81f6b4f326347f9ed622e8
Kaminagiyou123/python_practice
/Second/Database/app copy.py
1,074
4.1875
4
from utils import database USER_CHOICE=""" Enter: -'a' to add a book -'l' list all books -'r' to mark a book as complete -'d' to delete a book -'q' to quit Your choice:""" def add_book(): name_input=input("Enter the name of the book: ") author_input=input("Enter the author of the book: ") database.add_book(name_input,author_input) def list_books(): books=database.get_all_books() for book in books: print(book) def mark_read(): name_input=input("Enter the name of the book you read: ") books=database.get_all_books() for book in books: if book['name']==name_input: database.markread(name_input) def delete_book(): name_input=input("Enter the name of the book you want to delete: ") database.delete_book(name_input) def menu(): user_input=input(USER_CHOICE) database.create_book_table() while user_input!='q': if user_input=='a': add_book() elif user_input=='l': list_books() elif user_input=='r': mark_read() elif user_input=='d': delete_book() user_input=input(USER_CHOICE) menu()
true
ad7fa474866597dba60464b706c262d4f69af017
ananthramas/pythonBasics
/Day12/fillColor.py
529
4.46875
4
# draw color-filled square in turtle import turtle # creating turtle pen t = turtle.Turtle() # taking input for the side of the square s = int(input("Enter the length of the side of the square: ")) # taking the input for the color col = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolor t.fillcolor(col) # start the filling color t.begin_fill() # drawing the square of side s for _ in range(4): t.forward(s) t.right(90) # ending the filling of the color t.end_fill()
true