blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
25e013758a88efcc5f984af1650f877a93366c56
andreyafanasev/jobeasy-algorithms-course
/Algorithm_4.py
2,410
4.5
4
""" # 1 Enter a string of words separated by spaces. Find the longest word. """ def long_word(string): counter = 0 list1 = string.split() l = len(list1) while l > 0: if counter < len(list1[l-1]): counter = len(list1[l-1]) l -= 1 else: l -= 1 return counter print(long_word('Find the longest word')) """ # 2 Enter an irregular string (that means it may have space at the beginning of a string, at the end of the string, and words may be separated by several spaces). Make the string regular (delete all spaces at the beginning and end of the string, leave one space separating words). """ def irreg_str(string): l = string.split() return ' '.join(l) print(irreg_str(' Find the longest word ')) """ From Codewars # 1 Define String.prototype.toAlternatingCase (or a similar function/method such as to_alternating_case/toAlternatingCase /ToAlternatingCase in your selected language; see the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example: hEllO wOrld """ def to_alternating_case(string): result = '' for i in string: if i.islower() == True: result += i.upper() else: result += i.lower() return result print(to_alternating_case("1a2b3c4d5e")) """ From Codewars # 2 Is the string uppercase? Task Create a method is_uppercase() to see whether the string is ALL CAPS. For example: is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS. """ def is_uppercase(inp): return inp.isupper() print(is_uppercase('ACSKLDFJSgSKLDFJSKLDFJ')) """ From Codewars # 3 Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string. """ def fake_bin(x): res = '' l = list(x) for i in l: if int(i) < 5: res += '0' else: res += '1' return res print(fake_bin("1234888"))
true
d0e129190aa0ac9af9eefb088a64be319e113844
jroach20/Portfolio
/Python/ReversePolishNotation.py
2,181
4.5625
5
#Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it. #The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should #return 5 + 3 = 8. For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] #should return 5, since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5. #You can assume the given expression is always valid. #In comparison testing of reverse Polish notation with algebraic notation, reverse Polish has #been found to lead to faster calculations, for two reasons. The first reason is that #reverse Polish calculators do not need expressions to be parenthesized, fewer operations #need to be entered to perform typical calculations. Additionally,users of reverse Polish #calculators made fewer mistakes than for other types of calculator.[9] [10] Later research #clarified that the increased speed from reverse Polish notation may be attributed to the smaller number of #keystrokes needed to enter this notation, rather than to a smaller cognitive load on its users. #[11] However, anecdotal evidence suggests that reverse Polish notation is more #difficult for users to learn than algebraic notation.[10] #for each token in the postfix expression: # if token is an operator: # operand_2 ← pop from the stack # operand_1 ← pop from the stack # result ← evaluate token with operand_1 and operand_2 # push result back onto the stack # else if token is an operand: # push token onto the stack #result ← pop from the stack ops = { "+": (lambda a,b: a+b), "-": (lambda a,b: a-b), "*": (lambda a,b: a*b), "/": (lambda a,b: a/b) } def eval(expression): tokens = expression.split() stack = [] for token in tokens: if token in ops: operand2 = stack.pop() operand1 = stack.pop() result = ops[token](operand1,operand2) stack.append(result) else: stack.append(int(token)) #Sprint (stack) return stack print(eval("15 7 1 1 + - / 3 * 2 1 1 + + -"))
true
c1df1a8bea8ae57b88f8333998099d5f2cc8a070
azimsyafiq/Mini_Projects_Python
/order_pizza.py
1,986
4.3125
4
answer_yes = ('y', 'ye', 'yes') answer_no = ('n', 'no') available_toppings = ['pepperoni', 'mushroom', 'onion', 'sausage', 'bacon', 'extra cheese', 'black olives', 'green pepper'] pizza_toppings = [] print(""" ****************************** * Hi! * *Welcome to PapaJohn's Pizza * ****************************** """) print("Would you like to place an order?") customer = input("(Yes/No)\n -> ").lower() if customer in answer_yes: print("We have 10/12/14 inches pizza. What is the pizza size you would like to order?") pizza_size = int(input("Size: ")) if pizza_size == 10 or pizza_size == 12 or pizza_size == 14: print(""" What topping would you like to add to the pizza? We have Pepperoni, Mushrooms, Onions, Sausage, Bacon, Extra cheese, Black olives, Green peppers. (Enter 'Done' once you are finished) """) while True: pizza_topping = input("-> ").lower() if pizza_topping == 'done': break else: pizza_toppings.append(pizza_topping) continue if pizza_topping: print(f"\nOne {pizza_size} inch pizza coming right up!\n") for topping in pizza_toppings: if topping not in available_toppings: print(f"Sorry, {topping.upper()} is NOT available.") else: print(f"Adding {topping} to the pizza.") print("\nHere is your pizza. Thank you and enjoy your meal. Please come again soon.") else: print(f"One extra {pizza_size} inch plain pizza coming right up!\n") print("Here is your pizza. Thank you and enjoy your meal. Please come again soon.") else: print("Invalid value.") quit() elif customer in answer_no: print("Thank you for coming. Please come again.") else: print('Sorry, I did not understand that.')
true
d0bfdbf46106cfc22c0eb73dfa8a487dd115c2be
aliakseiChynayeu/geekbrains-python
/lesson4/task2.py
838
4.3125
4
# 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. # Результат: [12, 44, 4, 10, 78, 123]. import random initial_list = [] for i in range(0, 20): initial_list.append(random.randrange(0, 1000)) print(initial_list) result_list = [value for index, value in enumerate(initial_list) if value > initial_list[index-1]] print(result_list)
false
a202a785763905a648edb984e806826beb29fc0f
aliakseiChynayeu/geekbrains-python
/lesson1/task4.py
670
4.21875
4
# 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. number = int(input("Введите целое положительное число >>> ")) max_number = 0 current_number = number while True: if max_number < current_number % 10: max_number = current_number % 10 if current_number // 10 == 0: break current_number //= 10 print("Максимальная цифра числа {}, равна {}".format(number, max_number))
false
093ce04a315a3a9159e232fcdfa72c0f4d012079
manishpandit/workspace
/algorithms/sort/coins.py
1,081
4.21875
4
# This is an implementation of coin change problem using # bottom up dynamic programming. # Problem statement: given a set of coins of different values # and an amount to make up, find number of different ways to # make up the amount using given set of unlimited supply of # coins from the given set. def coin_change(amount, coins): # if amount is less than 0, return 0. if amount < 0: return 0 # construct the results list to store lower valued results ways = [0 for i in range(0, amount + 1)] # there is one way to make amount 0 ways[0] = 1 # start filling the table from 1 to amount for i in range(1, amount + 1): # for each coin if the amount is greater than # coin's value, compute ways[i] from lower terms for c in coins: if i >= c: ways[i] += ways[i-c] #return final value return ways[amount] def main(): coins = [1, 2, 5] amount = 4 print("different ways to make ", amount, " is ", coin_change(amount, coins)) if __name__ == "__main__": main()
true
6609662325c48219bee54290f7f869888def18ba
rcortezk9/OOP_python
/src/multi_instance_var.py
844
4.25
4
""" Multiple Instance Variables In this exercise we will declare two instance variables: identifier and data. Their values will be specified by the values passed to the initialization method, as before. """ # Create class: DataShell class DataShell: # Initialize class with self, identifier and data arguments def __init__(self, identifier, data): # Set identifier and data as instance variables, assigning value of input arguments self.identifier = identifier self.data = data # Declare variable x with value of 100, and y with list of integers from 1 to 5 x = 100 y = [1, 2, 3, 4, 5] # Instantiate DataShell passing x and y as arguments: my_data_shell my_data_shell = DataShell(x, y) # Print my_data_shell.identifier print(my_data_shell.identifier) # Print my_data_shell.data print(my_data_shell.data)
true
eb5db7c04aa6e27eee0c3bbf84c580fa7ad32ac0
sg349/COPLProject
/Parser/StatementType.py
772
4.125
4
from enum import Enum # Coogan Koerts, Brent Einolf, Sam Gardiner # This is an enum class that is used to determine which type of statement is being used. class StatementType(Enum): ELSE = 1 CONDITIONAL = 2 ASSIGNMENT = 3 WHILE = 4 REPEAT = 5 FOR = 6 PRINT = 7 def string_type(self): if self.value == 1: return "else_statement" if self.value == 2: return "conditional_statement" if self.value == 3: return "assignment_statement" if self.value == 4: return "while_statement" if self.value == 5: return "repeat_statement" if self.value == 6: return "for_statement" if self.value == 7: return "print_statement"
true
89deb675d1fbcc44439937152571e9738ce7481b
aeksei/PY111-template
/Tasks/a0_my_stack.py
1,037
4.3125
4
""" My little Stack """ from typing import Any class Stack: def __init__(self): ... # todo для стека можно использовать python list def push(self, elem: Any) -> None: """ Operation that add element to stack :param elem: element to be pushed :return: Nothing """ print(elem) return None def pop(self) -> Any: """ Pop element from the top of the stack. If not elements - should return None. :return: popped element """ return None def peek(self, ind: int = 0) -> Any: """ Allow you to see at the element in the stack without popping it. :param ind: index of element (count from the top, 0 - top, 1 - first from top, etc.) :return: peeked element or None if no element in this place """ print(ind) return None def clear(self) -> None: """ Clear my stack :return: None """ return None
true
93f7ad339ccc5e6c988944e2787b4689afde3bbc
Acilikola/MachineLearning_Python
/2_6-NonLinearRegression.py
2,985
4.375
4
''' For an example, we're going to try and fit a non-linear model to the datapoints corrensponding to China's GDP from 1960 to 2014. We download a dataset with two columns, the first, a year between 1960 and 2014, the second, China's corresponding annual gross domestic income in US dollars for that year. ("china_gdp.csv") ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("china_gdp.csv") print(df.head()) # plotting the dataset plt.figure(figsize=(8,5)) x_data, y_data = (df["Year"].values, df["Value"].values) plt.plot(x_data, y_data, 'ro') plt.ylabel('GDP') plt.xlabel('Year') plt.show() # choosing a model ''' From an initial look at the plot, we determine that the logistic function could be a good approximation, since it has the property of starting with a slow growth, increasing growth in the middle, and then decreasing again at the end ''' X = np.arange(-5.0, 5.0, 0.1) Y = 1.0 / (1.0 + np.exp(-X)) plt.plot(X,Y) plt.ylabel('Dependent Variable') plt.xlabel('Indepdendent Variable') plt.show() # building the model ##Let's build our regression model and initialize its parameters def sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y ##Lets look at a sample sigmoid line that might fit with the data beta_1 = 0.10 beta_2 = 1990.0 Y_pred = sigmoid(x_data, beta_1 , beta_2) #plot initial prediction against datapoints plt.plot(x_data, Y_pred*15000000000000.) plt.plot(x_data, y_data, 'ro') plt.show() # Lets normalize our data xdata =x_data/max(x_data) ydata =y_data/max(y_data) ''' we can use curve_fit which uses non-linear least squares to fit our sigmoid function, to data. Optimal values for the parameters so that the sum of the squared residuals of sigmoid(xdata, *popt) - ydata is minimized. popt are our optimized parameter ''' from scipy.optimize import curve_fit popt, pcov = curve_fit(sigmoid, xdata, ydata) #print the final parameters print(" beta_1 = %f, beta_2 = %f" % (popt[0], popt[1])) # Now we plot our resulting regresssion model x = np.linspace(1960, 2015, 55) x = x/max(x) plt.figure(figsize=(8,5)) y = sigmoid(x, *popt) plt.plot(xdata, ydata, 'ro', label='data') plt.plot(x,y, linewidth=3.0, label='fit') plt.legend(loc='best') plt.ylabel('GDP') plt.xlabel('Year') plt.show() # Finding the accuracy of our model ##split data into train/test msk = np.random.rand(len(df)) < 0.8 train_x = xdata[msk] test_x = xdata[~msk] train_y = ydata[msk] test_y = ydata[~msk] ##build the model using train set popt, pcov = curve_fit(sigmoid, train_x, train_y) ##predict using test set y_hat = sigmoid(test_x, *popt) ##evaluation print("Mean absolute error: %.2f" % np.mean(np.absolute(y_hat - test_y))) print("Residual sum of squares (MSE): %.2f" % np.mean((y_hat - test_y) ** 2)) from sklearn.metrics import r2_score print("R2-score: %.2f" % r2_score(y_hat , test_y) )
true
880440dca29d2d0c79c25bdf4aac8da0c261f185
joshdavham/Starting-Out-with-Python-Unofficial-Solutions
/Chapter 5/Q4.py
370
4.15625
4
#Question 4 def main(): speed = int(input("What is the speed of the veihicle in mp? ")) time = int(input("How many hours has it traveled? ")) print("Hour\tDistance Traveled", \ "\n----------------------------") for hour in range(1, time+1): distance = hour * speed print(hour, "\t", distance) main()
true
b5a7a1c4371cf3b3853879263ca2dcaf639818e6
joshdavham/Starting-Out-with-Python-Unofficial-Solutions
/Chapter 9/Q3.py
1,028
4.1875
4
#Question 3 def main(): date = input("Enter the date in the form mm/dd/yyyy: ") dateList = date.split("/") monthNum = int(dateList[0]) dayNum = int(dateList[1]) yearNum = int(dateList[2]) dateString = getDate(monthNum,dayNum,yearNum) print("The date is:", dateString) def getDate(monthNum, dayNum, yearNum): if monthNum == 1: month = "January" elif monthNum == 2: month = "February" elif monthNum == 3: month = "March" elif monthNum == 4: month = "April" elif monthNum == 5: month = "May" elif monthNum == 6: month = "June" elif monthNum == 7: month = "July" elif monthNum == 8: month = "August" elif monthNum == 9: month = "September" elif monthNum == 10: month = "October" elif monthNum == 11: month = "November" else: month = "December" return month + " " + str(dayNum) + ", " + str(yearNum) main()
false
c8380b87f0fe64810fe3abe9313de97fc79802bf
TheOnlyHans/intermediatePython
/mod2Final.py
571
4.15625
4
list = ["xbox", "playstation", "pc", "apple"] def list_o_matic(item): if not item: print(list.pop(), "Has been removed") else: if item in list: print(item + " will be removed") list.remove(item) else: print(item, "will be added to the list") list.append(item) return #empty list = false while list: print("List of items: ", list) stringIn = input("enter an item: ").lower() if stringIn == "quit": break else: list_o_matic(stringIn) print("\nGoodbye!")
true
755fdfd50be4fef47253d96dfd308b081216ab60
libertydisco/python
/conditions.py
222
4.125
4
num = int(input("Number: ")) if num > 0: print("Mr. T says your number is positive, foo.") elif num < 0: print("Mr. T says your number is negative, foo.") else: print("Mr. T says your number is 0, foo")
true
f4a5c88751c980ce68256e0087365b38e3660398
ejluciano/Python
/Crash course/list/Place.py
408
4.40625
4
places = ['Japan', 'Germany', 'France', 'Maldives'] print(places) print(sorted(places)) #sorted makes them in alphabetical order print(places) print(sorted(places, reverse=True)) #reversed order print(places) places.reverse() # will reverse the order temporarily print(places) places.reverse() # will reverse the order Original order print(places) places.sort() print(places) places.reverse() print(places)
true
d4ac29fb95d1504b7533d43c92500216451c9e90
PeterBeard/math-experiments
/munchausen.py
1,773
4.28125
4
# Look for Munchausen numbers # A Munchausen number is an integer such that the sum of the digits raised to the power of themselves equals the number # For example, 3435 is a Munchausen number because 3^3 + 4^4 + 3^3 + 5^5 = 3435 # Get the digits of an integer def get_digits(n): s = str(n) digits = [] for digit in s: digits.append(int(digit)) return digits # Determine whether n is a Munchausen number def is_munchausen(n, show_steps=False): digits = get_digits(n) s = 0 for d in digits: # Assume 0^0 = 0; this is common in this area according to Wikipedia if d > 0: s += d**d if show_steps: steps = [] for d in digits: steps.append('%i^%i' % (d, d)) print '%i = %s' % (n, ' + '.join(steps)) # If the sum of d**d equals the number, it's a Munchausen number return s == i print 'A Munchausen number is an integer where the sum of the digits raised to the' print 'power of themselves equals the original number.' print '' print 'For example, 3,435 is a Munchausen number because:' print '3^3 + 4^4 + 3^3 + 5^5 = 3435' print '' print 'This script will find all Munchausen numbers in a particular range.' print '' # Ask the user for the parameters of the search space try: lower_bound = int(raw_input('Where shall I start the search? ')) except: print 'Start point must be an integer.' quit() try: upper_bound = int(raw_input('And where shall I end it? ')) except: print 'End point must be an integer.' quit() # Look for Munchausen numbers print 'Searching for Munchausen numbers between %i and %i.' % (lower_bound, upper_bound) for i in xrange(lower_bound, upper_bound+1): if is_munchausen(i): is_munchausen(i, True)
true
02bafc6b94b6250953250d86d97dd770277a2b07
scaniasvolvos/python-basics
/arr-largest.py
219
4.15625
4
def largest(arr, n): max = arr[0] for i in range(n): if arr[i] > max: max = arr[i] return max arr = [10, 20, 65, 500] n = len(arr) max = largest(arr, n) print("Largest element is", max)
false
c70977390dcf55bca5da61478639079633048ac0
SuperZG/MyPythonLearning
/my_first_project/day2/chapter5/demo7(偶数求和).py
1,062
4.125
4
# 思考下如何完成1~100的求和。 # 1.range+for # count = 0 # num_list = list(range(0, 101,2)) # print(num_list) # for num in num_list: # count += num # print("和为:", count) # 2.for+if # count = 0 # num_list = list(range(0, 101)) # print(num_list) # for num in num_list: # if num % 2 == 0: # count += num # # print("和为:", count) # 3.for+continue # count = 0 # num_list = list(range(0, 101)) # print(num_list) # for num in num_list: # if num % 2 == 1: # continue # count += num # # print("和为:", count) # 4.while+if # sum = 0 # x = 0 # while x <= 100: # if x%2==0: # sum = sum + x # x = x + 1 # print(sum) # 5.while+continue # sum = 0 # x = 0 # while x <= 100: # x = x + 1 # if x % 2 == 1: # continue # sum = sum + x # print(sum) # 6.while+range num_list = list(range(0, 101, 2)) print(num_list) # 求list的长度 # print(len(num_list)) # print(num_list.__len__()) # list[index] sum = 0 x = 0 while x < len(num_list): sum = sum + num_list[x] x = x + 1 print(sum)
false
e546e9187cea2b9510a43f1a691c0557bec05a7a
SuperZG/MyPythonLearning
/my_first_project/day2/chapter6/demo5(可变参数).py
992
4.46875
4
# 参数前面加*,代表为可变长参数,可以接收tuple,可变参数也必须放在必选参数的后面,*号的意思是创建一个名为numbers的空元组来接收实参。 def calcu(*numbers): print(numbers) print(type(numbers)) sum = 0 for number in numbers: sum = sum + number * number print('The sum answer is:', sum) # calcu(1, 2, 3, 4) numlist = [2, 4, 6, 8] # calcu(numlist) calcu(*numlist) ''' (2, 4, 6, 8) <class 'tuple'> The sum answer is: 120 ''' #不加星号的话,也可以直接传递list或者tuple,不过必须将list和tuple传入1个变量传入。。 def calcu(numbers): print(numbers) print(type(numbers)) sum = 0 for number in numbers: sum = sum + number * number print('The sum answer is:', sum) # calcu(1, 2, 3, 4) #calcu() takes 1 positional argument but 4 were given numlist = (2, 4, 6, 8) # calcu(numlist) calcu(numlist) ''' [2, 4, 6, 8] <class 'list'> The sum answer is: 120 '''
false
840f0bfbece59e78c1eeebb806cb09b264352f05
lumc-python/functions-ruizhideng
/second_day_function.py
2,773
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 11:58:07 2019 @author: Administrator """ # -*- coding: utf-8 -*- """ Created on Wed Nov 27 10:40:57 2019 @author: Administrator """ # Assignment Functions # 1. Write a Python function that returns the maximum of two numbers. def max_number_two(x,y): """returns the maximum of two numbers""" return max(x,y) print(max_number_two(2,3)) # 2. returns the maximum of three numbers def max_number_three(x,y,z): """returns the maximum of three numbers""" return max(max_number_two(x,y),z) print(max_number_three(2,3,4)) # 3. positive and negative numbers def judge_ne_po(): """ positive and negative numbers""" input_number = int(input('please input a number:')) if type(input_number) != int : raise TypeError else: if input_number > 0: print('{} is a positive number'.format(input_number)) elif input_number == 0: print('{} is == 0'.format(input_number)) else: print('{} is a negative number'.format(input_number)) judge_ne_po() #Practice Funcitons # 1. Multiplication def multiplication_pos_number(x): """multiply all the positive numbers in a list""" result = 1 for i in x: if i > 0: result = result * i return result x = [-1,11,3,-1,3] print(multiplication_pos_number(x)) # 2. Function updates def transform_pos(x): """transforms all the positive numbers from a list""" for i in x: if i > 0: return True x = [-1,11,3,-1,3] print(transform_pos(x)) # 3. Palindrome def palindrom(x): if x[:] == x[::-1]: return True else: return False print('{} is palindrom'. format(palindrom('90.09'))) # 4. k-mer counting # (1/2) def suffixes(dna_string,k): """Print all the sufixes""" for i in range(0, len(dna_string) + 1): print(dna_string[i:]) """Print all length 3 substrings""" for i in range(0, len(dna_string) - k + 1): print(dna_string[i:i+k]) """Print all unique substrings of length 3.""" unique_words = set() for i in range(0, len(dna_string) - k + 1): unique_words.add(dna_string[i:i+k]) print(unique_words) string_test = "ACGT" * 3 + "TTATT" * 5 suffixes(string_test,k=4) # (2/2) def suffixes(dna_string,k): """Print substrings""" list_keys = [] list_values = [] for i in range(0, len(dna_string) - k + 1): list_keys.append(dna_string[i:i+k]) list_values.append(k) print(dict(zip(list_keys,list_values))) string_test = "ACGT" * 3 + "TTATT" * 5 suffixes(string_test,k=4)
true
9c315a3f1e1678d21b95e781b9a3a7b6a76680c4
Yuito181/UCLA-2019
/calculator.py
926
4.1875
4
#BEGINNING OF CALCULATOR # 1) use if-statements to complete this calculator program with 4 operations # Example run (what it should look like): # 0 - add # 1 - subract # 2 - multiply # 3 - divide # Enter a number to choose an operation: # 1 # Enter your first input: 7 # Enter your second input: 4 # 7 - 4 = 3 # 2) add a fifth operation, power, that does a to the power of b # 3) add a sixth operation, square root, that only asks for 1 input number and outputs its sqrt # 4) seventh operation, factorial(a), one input # 5) eighth operation, fibonacci(a), one input # 6) talk to instructors when finished print(" 0 - add") print(" 1 - subract") print(" 2 - multiply") print(" 3 - divide") print("Enter a number to choose an operation: \n") op = input() a = int(input("Enter your first input: ")) b = int(input("Enter your second input: ")) print("a + b =",a+b) #END OF CALCULATOR
true
41391589904cefc11db02d3f67e41dbea5fd9a52
earganda/sorting-schedule
/sorting-schedule.py
1,403
4.15625
4
menu_choice = input("""Menu: 1. View Sched 2. Add Sched Answer: """) # View Sched if menu_choice == '1': print('') # Add Sched elif menu_choice == '2': sched_q = input('How many subjects will you add? ') # This line should run n times (depending sa input of sched_q) or bahala ka # if you thought of something else subject_time = input('Enter time: ') subject_name = input('Enter subject name: ') print('\nSubject added!\n', subject_name, '—', subject_time) # Sort or Main Menu add_choice = input("""Select: 1 - Sort 2 - Return to Menu Answer: """) # Sorting Methods if add_choice == '1': sorting_choice = input("""Choose a sorting method: A. Bubble Sort B. Selection Sort C. Insertion Sort D. Shell Sort E. Merge Sort Answer: """) if sorting_choice.upper() == 'A': print('Kayo bahala here') elif sorting_choice.upper() == 'B': print('Kayo bahala here') elif sorting_choice.upper() == 'C': print('Kayo bahala here') elif sorting_choice.upper() == 'D': print('Kayo bahala here') elif sorting_choice.upper() == 'E': print('Kayo bahala here') return_menu = input('Return menu?') elif add_choice == '2': print('Dapat magback to menu.')
true
40e3a8a5250b1954be0479135019e9c9e1ce30bf
BlkeSnchz/SE_126
/Sanchez.py/lab_1b.py
2,398
4.15625
4
#Blake Sanchez, SE126, 7/16/2019, Lab 1 B print("Welcome to Blake's Fire Safety Determinator.") room = 0 people = 0 ans = "y" #def main(): #while (ans != "y" or ans != "Y" or ans != "n" or ans != "N"): #check = input("Do you want to check anymore rooms? [y/n]") #if (ans == "y" or ans == "Y"): #elif (ans == "n" or ans == "N"): # print ("Thank you.") #else: # print("You should enter either Y/y or N/n.") #return while (ans == "y" or ans == "Y"): room = int(input("Please enter the Maximum Room Capacity: ")) people = int(input("Please enter the amount of people attending the meeting: ")) amount = room - people if (people <= room): print("Good News! The meeting is Legal and {0} additonal people may attend.".format(amount)) elif (people > room): print("Bad News! The meeting cannot be held as planned due to the fire regulation. {0} people must be excluded in order to meet the fire regulations.".format(amount)) else: print("The letter you have entered resulted in an error. Please try again.") ans = input("Do you want to check again?: [y/n]") while (ans != "y" and ans != "Y" and ans != "n" and ans != "N"): print("Error please enter a valid answer: [Y/y for 'Yes' or N/n for 'No']") ans = input("Do you want to check again?: [y/n]") print("Thank you for using Blake's Fire Safety Determinator!") #while ans == "Y" or ans == "y": #room = int(input("Please enter the Maximum Room Capacity: ")) #people = int(input("Please enter the amount of people attending the meeting: ")) #amount = room - people #if ans == "n" or ans == "N": #print("Thank you for using Blake's Program.") #while (ans == "y" or ans == "Y"): # if (ans == "N" or ans == "n"): # print("Thank you for using Blake's Fire Safety Determinator!") #else: #ans = input("Do you want to check again?: [y/n]") #------------------------------ #room = int(input("Please enter the Maximum Room Capacity: ")) # people = int(input("Please enter the amount of people attending the meeting: ")) # amount = room - people # if(ans == "n" or ans == "N"): # print("Thank you.") #else: # ans = input("Do you want to check again?: [y/n]")
true
0317979091ce097f3b7c0050d519a7ce12d3e433
prasadrao/python3_ost
/Lesson04/re_test.py
925
4.15625
4
import re text = "Guido will be out of the office from 12/15/2012 - 1/3/2013" print("This is given text: " + text) # A regex pattern for a date. datepat = re.compile('(\d+)/(\d+)/(\d+)') #Find and print all dates for m in datepat.finditer(text): print(m.group()) print("Done Printing dates") # Find all dates, but print in a different format monthnames = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', \ 'Sep', 'Oct', 'Nov', 'Dec'] for m in datepat.finditer(text): print ("%s %s, %s" % (monthnames[int(m.group(1))], m.group(2), m.group(3))) print("Done printing dates in different pattern") # Replace all dates with fields in the European format (day/month/year) def fix_date(m): return "%s/%s/%s" % (m.group(2), m.group(1), m.group(3)) newtext = datepat.sub(fix_date, text) print (newtext) #And alternative replacement newtext = datepat.sub(r'\2/\1/\3', text) print (newtext)
true
8e593348ff7612def8b53be8c343b0680986b470
LizaPleshkova/PythonLessonsPart1
/venv/43-lambda-functions.py
520
4.1875
4
# def get_square(num): # return num**2 # # print(get_square(5)) # get_square = lambda num: num**2 # сохраняем в переменную\не предпочтительноо # print(get_square(10)) # print((lambda num: num**2)(10)) l = [1,2,3] # def get_double(lis): # return [i for i in lis] def get_double(lis): return list(map((lambda i: i*2), l)) print(get_double(l)) # # tw = lambda num: num*2 # # output = [tw(i) for i in l] # output = [(lambda i: i*2)(i) for i in l] # # print(output)
false
b124e304f1c9f9a56943eab375054ca8df6e9907
dpsutton/algo
/python/linked_list.py
1,257
4.25
4
class LinkedList(object): """Linked List class that adds objects as nodes. It is doubly linked and uses a nil pointer for ease. """ def __init__(self): super(LinkedList, self).__init__() self.nil = Node("nil") self.nil.next = self.nil.previous = self.nil def add(self, val): "add the new value at the head of the list" node = Node(val) node.next = self.nil.next node.previous = self.nil.next self.nil.next = node def remove(self, node): "remove a node (by reference) from the linked list" node.previous.next = node.next node.next.previous = node.previous def find(self, key): current = self.nil.next while current != self.nil and current.val != key: current = current.next return current def length(self): length = 0 current = self.nil.next while current != self.nil: length = length + 1 current = current.next return length class Node(object): """Doubly linked Node for linked lists """ def __init__(self, val): super(Node, self).__init__() self.val = val self.next = None self.previous = None
true
aebb4fdcce38879923be7d511c2aa5c144adf0c2
kwasnydam/python_exercises
/StrukturyDanychIAlgorytmy/scripts/python_decorators.py
2,239
4.5625
5
''' @author: Damian Kwaśny decorators used to alter the functionality of functions (xD) Where and why use fnction decorators?: 1. logging -> keeping track of how many times a fucntion was called and what arguments it received 2. timing how long a function runs ''' from functools import wraps #above lib is needed to preserve the info about the function we are decorating #like its documentation #Clousures def outer_function(): message = 'Hi' def inner_function(): print(message) return inner_function() #decorators def decorator_function(original_function): ''' Using decorator we can enhance the functionality without changing anything inside the actual fucntion we are decorating ''' @wraps#u use it to preserve the info about the original_function def wrapper_function(*args, **kwargs): print('wrapper run function: {}'.format(original_function.__name__)) return original_function(*args, **kwargs) #multi argument return wrapper_function @decorator_function def display(): '''everytime we use display we actually use wrapper_function thus extenbding functionality of this function it's equal to: display = decorator_function(disply) -> EQUAL ''' print('display()') @decorator_function def display_info(name, age): print('display_info: {} {}'. format(name, age)) decorated_display = decorator_function(display) #it has a wrapper_function ready to be executed decorated_display() # Executes wrapper so in fact executes the original_function, display display() #The same output thanks to @decorator_function display_info('damian', 22) """ #class decorators #this is just another syntax class decorator_class(object): #decorator class instead of decorator function def __init__(self, original_function): self.original_function = original_function def __call__(self, *args, **kwargs): #it raplaces wrapper function print('call method executed this before {}'. format(\ self.original_function.__name__)) return self.original_function(*args, **kwargs) @decorator_class def display_info(name, age): print('display_info: {} {}'. format(name, age)) display_info('damian', 22) """
true
40dec99e2a628dd31815590a0bb7bf457c0aa80f
drkg405t/BMI-Python-
/bmi.py
505
4.3125
4
def BMI(height, weight): bmi = weight/(height ** 2) return bmi # driver code height = float(input("Enter your height in inches: ")) weight = float(input("Enter your weight in lbs: ")) # calling bmi function bmi = BMI(height, weight) # conditions to find out BMI category if (bmi < 18,5): print("You're underweight") elif (bmi >= 18.5 and bmi < 24.9): print("Desirable") elif (bmi >= 24.9 and bmi < 30): print("Overweight") elif (bmi >= 30): print("Suffering from obesity")
true
e9b95bed8eea2e25231f5eb24abe2fe573820533
anup5889/PythonWork
/Node.py
990
4.15625
4
myList=[5, 3, 6, 8, 9, 10] myList.sort() """ [3, 5, 6, 8, 9, 10] """ def binarySearch(myList): start=0 num_to_search=int(input("Enter the number you want to search")) length_of_list= len(myList) end=length_of_list while(start<=end): mid=(start+end)/2 if(myList[mid]==num_to_search): return mid elif num_to_search>myList[mid]: start=mid+1 else: end=mid-1 #binarySearch(myList) """ [2, 6, 13, 21, 36, 47, 63, 81, 97] start will be start element case 1: x==A[mid] case 2: x>A[mid]==> we will increase the start to start==mid+1 case 3: x<A[mid]==> we will decrease the end to end =mid-1 """ def linearSearch(myList): num_to_search=int(input("Enter the number you want to search")) for index, value in enumerate(myList): if num_to_search==value: print "Num to search found at ", index exit() else: print "number not found" linearSearch(myList) """ Linear Search Algorithm takes O(n) time """
true
cddd6db0ae77bd5d07104cfd51b6b0544d05fe9a
tomi1710/holbertonschool-higher_level_programming
/0x0A-python-inheritance/11-square.py
1,022
4.15625
4
#!/usr/bin/python3 """ class Square that inherits from Rectangle (9-rectangle.py) """ class BaseGeometry: """ class BaseGeometry """ def area(self): """ defines area """ raise Exception("area() is not implemented") def integer_validator(self, name, value): """ validates the integer passed """ if (type(value) != int): raise TypeError("{} must be an integer".format(name)) elif (value <= 0): raise ValueError("{} must be greater than 0".format(name)) class Square(BaseGeometry): """ defines a class Square inherited from BaseGeometry """ def __init__(self, size): """ init """ self.__size = size BaseGeometry.integer_validator(self, "size", self.__size) def area(self): """ returns the area of the square """ return (self.__size * self.__size) def __str__(self): """ returns the dimensions of the square """ return ("[Square] {}/{}".format(self.__size, self.__size))
true
7c4d2a1f4b7809b3f0352a9dd87b15fc358078c8
jamiemalcolm/git_homework_day_1
/guessing_game.py
870
4.25
4
# I found out how to generate a random number with a google search and tried it # Failed multiple times trying to run the code with some errors in the elif syntax import random # I read some documentation on import and found i needed that to get the code to generate the number n = random.randint(1, 100) # still dont understnd it all that well number = int(input("guess a number from 1 to 100. ")) while number != n: if number < n: print("too low! try again") number = int(input("guess a number from 1 to 100. ")) elif number > n: print("too high!, try again") number = int(input("guess a number from 1 to 100. ")) if number == n: print("well done!") # took some time but eventually managed to get it to output what i wanted. # # I used stack overflow, pythonforbeginners.com and docs.python.org to # # help me get to my solution.
true
755bac9d272c34cff24b7c24e6b4e863da86ec8f
dkeen10/A01185666_1510_v3
/Lab01/base_converter.py
2,333
4.125
4
# base_conversion = int(input("what base between 2 and 9 do you want to convert to?")) # max_number = base_conversion ** 4 - 1 # print("max number is", max_number) # decimal_number = int( # input("enter a base 10 number between 0 and the max number to convert to the designated base number:")) # # remainder_4 = decimal_number % base_conversion # remainder_3 = (decimal_number // base_conversion) % base_conversion # remainder_2 = (decimal_number // base_conversion // base_conversion) % base_conversion # remainder_1 = (decimal_number // base_conversion // base_conversion // base_conversion) % base_conversion # # print("the converted number is:" + str(remainder_1) + str(remainder_2) + str(remainder_3) + str(remainder_4)) base_conversion = int(input("what base between 2 and 9 do you want to convert to?")) if 2 <= base_conversion <=9: max_number = base_conversion ** 4 - 1 print("max number is", max_number) decimal_number = int(input("enter a base 10 number between 0 the max number to convert to the designated base number:")) if 0 <= decimal_number <= int(max_number): remainder_4 = decimal_number % base_conversion remainder_3 = (decimal_number // base_conversion) % base_conversion remainder_2 = (decimal_number // base_conversion // base_conversion) % base_conversion remainder_1 = (decimal_number // base_conversion // base_conversion // base_conversion) % base_conversion print("the converted number is:" + str(remainder_1) + str(remainder_2) + str(remainder_3) + str(remainder_4)) else: print("invalid input") else: print("invalid input") # number_to_convert = input(float("enter a base 10 number between 0 and 6560 to convert into a 4 digit number:")) # base = input("what base between 2 and 9 do you want it converted to?") # if basenumber_to_convert > 6560: # print("sorry that number is too large") # elif 6560 >= number_to_convert > 4095: # # elif 4095 >= number_to_convert > 2400: # elif 2400 >= number_to_convert > 1295: # elif 1295 >= number_to_convert > 624: # elif 624 >= number_to_convert > 255: # elif 255 >= number_to_convert > 80: # elif 80 >= number_to_convert > 15: # elif 15 >= number_to_convert >= 0: # elif number_to_convert < 0: # print ("sorry that number is too small") # else: # print ("invalid input)
true
c2bca7853aeabd1b39e7a963b25405eeafec3f1c
mosabzx/Lexicon-Test
/task02.py
858
4.25
4
#Funktion som tar in input från användaren (Förnamn, Efternamn, Ålder) och sedan skriver ut dessa i konsolen """fname = input("Please enter your first name: ") aname = input("Please enter your after name: ") age = input("Please enter your age: ") print("Hello " + fname + ", Your family name is: " + aname + " , Your age is: " + age + ".")""" #Nu Som funkion utan välkommen. """def info(): fname = input("Please enter your first name: ") aname = input("Please enter your second name: ") age = input("Please enter your age: ") info()""" #Nu Som funkion med välkommen def info(): fname = input("Please enter your first name: ") aname = input("Please enter your second name: ") age = input("Please enter your age: ") print("Hello " + fname + ", Your family name is: " + aname + " , Your age is: " + age + ".") info()
false
756e00640438f8eb4c3816ce451e9b8adf7b0fa5
fiolla345/aliens2
/aliens2.py
1,725
4.34375
4
#imports a library that allows for creation of pause throughout code import time # Lines 5-16 give the user a description print("This program is to figure out how many aliens") time.sleep(0.4) print("will be on earth after a certain amount of time passes.") time.sleep(0.4) print("----------------------------------------") time.sleep(0.4) print("Every alien from a generation that is") time.sleep(0.4) print("odd will be red and every even generation will be blue.") time.sleep(0.4) print("----------------------------------------") time.sleep(0.8) # Declare the variables firstLanding = int(input("How many aliens first landed on earth?")) weeks = int(input("And how many weeks have they been on earth?")) countingVar = 1 weeks2 = weeks #Tell the user that only the original population exists if weeks == 0: print("There are only",firstLanding,"aliens on Earth") #Tell the user how many aliens there are after (x) weeks if weeks > 0: #added while loop to count the population week by week while countingVar < (weeks + 1): print( firstLanding * (2 ** countingVar),"aliens are on earth after", countingVar ,"weeks") countingVar = countingVar + 1 time.sleep(.5) print("----------------------------------------") time.sleep(.5) print("And now for the colors") time.sleep(.5) print("----------------------------------------") time.sleep(.5) #2nd while loop to destinguish generation and color countingVar2 = 0 while countingVar2 < (weeks2): if (countingVar2 + 1) % 2 == 0: print("The #", countingVar2 + 1, "generation will be blue") else: print("The #", countingVar2 + 1, "generation will be red") countingVar2 = countingVar2 + 1 time.sleep(.5)
true
5d5a8580513cd6640354f6a018e480942413b6f4
CAAPCS/LectureCodes
/w2c3/main.py
1,531
4.125
4
class Book(object): def __init__(self, title, author, text): self.title = title self.text = text self.author = author class Client(object): def __init__(self, name): self.name = name class Library(object): def __init__(self): self.listOfBooks = [] self.listOfClients = [] # contain Client(s) def addBook(self, book): self.listOfBooks.append(book) def addClient(self, client): self.listOfClients.append(client) def printLibraryClients(self): for client in self.listOfClients: print(">>", client.name) def printLibraryBooks(self): for book in self.listOfBooks: print(">>", book.title) def numberOfBooks(self): return len(self.listOfBooks) if __name__ == '__main__': print("Welcome to the library") websterLibrary = Library() client1 = Client("Austin") # line 42 instantiates a book, and it sets its atrributes book1 = Book("Think Python", "Allen Downey", "it says lot of things...") #line below instantiates another different book, and it sets its atrributes book2 = Book("Theory of Communicative Action", "Jurgen Habermas", "speech acts blah blah...") websterLibrary.addBook(book1) websterLibrary.addBook(book2) websterLibrary.addClient(client1) print("this is the list of clients") websterLibrary.printLibraryClients() print("this is the list of books we have:", websterLibrary.numberOfBooks()) websterLibrary.printLibraryBooks()
true
c5699c1284aba664e54bf6b5b741993b0c788274
EddyShang/python_exercise
/if_condition.py
676
4.125
4
#if condition example # print '''Please choose a rounting protocol using number: 1. RIP 2. EIGRP 3. IGRP 4. OSPF 5. ISIS 6. BGP''' protocol_option=raw_input("Please enter your choice(number 1-6): ") if protocol_option.isdigit() and 1<=int(protocol_option)<=6: if protocol_option=='1' or protocol_option=='2' or protocol_option=='3': print "This routing protocol is a distance vector protocol." elif protocol_option=='4' or protocol_option=='5': print "This routing protocol is a link state protocol." else: print "This routing protocol is a path vector protocol" else: print "Invalid choice! The program has been terminated!" raw_input()
true
bef3ce8568dc0d1458d46debd0c351f9ac5b2e3c
Jitesh-Khuttan/Gemini-Solutions-Learning
/PandasTutorial/dataframe_basics.py
1,149
4.28125
4
import pandas as pd #Reading CSV file for creating a dataframe df = pd.read_csv("pandas/2_dataframe_basics/weather_data.csv") # print(df[['temperature','windspeed']]) #Creating a dataFrame from Python Dictionary data = { 'student_id':[1,2,3,4,5], 'name': ['Jitesh','Aman','Raghav','Harman','Madhav'], 'branch': ['cse','ece','mech','cse','bio'] } df_dict = pd.DataFrame(data) # print(df_dict) print(df_dict.shape) #Printing rows from top print(df.head()) #Printing from end print(df.tail(3)) #Slicing on dataframe print(df[1:4]) #Finding Max,Min Value print("Max Temp:", df['temperature'].max()) print("Min Temp:", df['temperature'].min()) print("Mean of Temp:", df['temperature'].mean()) print("Standard Deviation of Temp:", df['temperature'].std()) #Print the statistics of data print(df.describe()) #Conditionally Select Data print(df[df['temperature'] >= 32]) #or df[df.tempeature >= 32] #Print the temperature and day where temp was max print ( df[['day','temperature']][df.temperature == df.temperature.max()]) #Setting the index of the dataframe print(df.set_index('event',inplace = True)) print(df.loc['Snow'])
true
60cc347a593f8e43217147585203e71aab0fb968
LiHua1997/Python-100-learn
/day7/day7_7.py
961
4.15625
4
""" 双色球抽奖 输入注数,输出几个由6个(1,34)和1个(1,16)的数字构成的双色球彩票 Version = 0.1 Author = St """ from random import randrange, randint, sample def select_balls(): red_balls = [x for x in range(1, 34)] selected_balls = [] selected_balls += sample(red_balls, 6) selected_balls.sort() selected_balls.append(randint(1, 16)) return selected_balls # def display_balls(balls): # for index in range((len(balls))): # if index == 6: # print('|', end=' ') # print(balls[index], end=' ') def display_balls(balls): for index, ball in enumerate(balls): if index == len(balls) - 1: print('|', end=' ') print("%02d" % ball, end=' ') def main(): num = int(input('机选几注: ')) for _ in range(num): balls = select_balls() display_balls(balls) print() if __name__ == '__main__': main()
false
677ad767fe551eb184ea78da5351dc499bf34947
ZipCodeCore/PythonFundamentals.Exercises.Solutions
/part2/exponentiator.py
478
4.21875
4
def exponentiate(a: int, b: int) -> int: """ This function takes two integers (a and b) and returns the value of int a raised to the power of b. """ return a ** b square = lambda x: exponentiate(x, 2) cube = lambda x: exponentiate(x, 3) def raise_to_fourth_power(x: int) -> int: """ Given an integer, this function will raise it to the 4th power """ return exponentiate(x, 4) print(square(2)) print(cube(2)) print(raise_to_fourth_power(2))
true
f1756dc0f05e31f33f357281732b05a1d8b55833
kaushiknimalan/Rock-Paper-and-Scissors-Game-Python
/Player.py
1,479
4.15625
4
import random import Check_Process print("""Hi, This is Rock,Paper and scissors game.. You can play this game anytime and anywhere you want.. You are gonna compete with our intelligent computer which most of them has never defeated Let's see if you can win.. """) loops = int(input("How many rounds do you want?? ")) def time_for_player(): players_choice = int(input("What do you wanna choose?? (1 : Rock, 2 : Paper, 3 : Scissors) ")) return players_choice def time_for_computer(): computers_choice = random.randint(1, 3) return computers_choice returned_points = None i = 1 while i <= loops: players = time_for_player() computers = time_for_computer() if computers == players: print("Both values are same") i += 1 continue elif players > 3 or computers > 3: print("Value must be a number or you have written the number more than 3") i += 1 continue else: returned_points = Check_Process.check(computers, players) i += 1 continue if returned_points[0] > returned_points[1]: print(f"Player wins with the total of {returned_points[0]} beating the computer's total of {returned_points[1]}!! ") elif returned_points[1] > returned_points[0]: print(f"Computer wins with the total of {returned_points[1]} beating the Player's total of {returned_points[0]}!! ") else: print("It's a tie!") print("\n Thank you for playing rock paper scissors with us..")
true
08d22d0abb976e2f1aea91e215c604c91cb1962f
MalarSankar/demo
/find_country.py
621
4.25
4
#to create a function for find country name def get_country(val): for key,value in dict.items(): if val==value: print(key) #to create a empty dictionary dict={} n=int(input("enter the number of elements in dictionary:")) for i in range (n): key=input("enter key:") value=input("enter value") dict.update({key:value}) print("the dictionary is",dict) # to call the function desired_continent=input("enter the desired continent") if(desired_continent[0].islower()): get_country(desired_continent) else: str=desired_continent[0].lower()+desired_continent[1:] get_country((str))
true
3738b1f2322e63598fd5008c82954874d7f40331
Ou-tec/Phyton-2020
/Assignment.py
475
4.25
4
x = int(input("Choose the conversion type ")) y = 0 if x == 1: print("You are converting from Fahrenheit to Celsius") x = int(input("How many Fahrenheit would you like to convert? ")) y = (x - 32) * 0.56 print(f"{x} Fahrenheit is {y} Celsius") elif x == 2: print("You are converting from Fahrenheit to Kelvin") x = int(input("How many Fahrenheit would you like to convert? ")) y = (x-32) * 0.56 y += 273.15 print(f"{x} Fahrenheit is {y} Kelvin")
false
4f11a9d9d4cc6ea8209c58d8755678fb1d7d3af4
praiseey/Wejapa-ds-wave3
/usernames_range.py
647
4.28125
4
#Modify Usernames with Range # Write a for loop that uses range() to iterate over the positions in usernames to # modify the list. Like you did in the previous quiz, change each name to be # lowercase and replace spaces with underscores. After running your loop, this list #usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] #should change to this: #usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"] usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] # write your for loop here for username in range(len(usernames)): usernames[username] = usernames[username].lower().replace(' ', '_') print(usernames)
true
40cc7d2a053c52232f45103ccaed326ce1e03b5a
voron521/geekbrains_osnovy_python
/taks_1.py
472
4.3125
4
# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. a = 15 b = "Hello World" print (a, type(a)) print (b, type(b)) c = input("введите имя: ") d = int(input("Введите возраст: ")) print (c) print (d)
false
31162349be43794e3315c31048a7266e8d47bece
shreeya917/-python_assignment_dec15
/max_min.py
324
4.15625
4
#Q2. Given a list of integers, my_list = [4,2,4,0,2,4,5,7,8,9,23,8,5,4,2,2,34,4,45]. # Find the maximum and minimum numbers in the list. my_list = [4,2,4,0,2,4,5,7,8,9,23,8,5,4,2,2,34,4,45] sorted_my_list=sorted(my_list) print("The minimum number is:",my_list[0]) i=len(my_list) print("The maximum number is:",my_list[i-1])
true
54bd8176edad3dae150e4dd1ffd25af43a8b2017
wabc1994/Pyhton_algorithm
/bit/find_missing_number.py
679
4.125
4
""" return the missing number from a sequence of unique integers in range[0:n] in O(n) time and space. The dif """ def find_missing_number(nums): """ :param nums: the number array :return: the missing number """ missing = 0 n = len(nums) for i, element in enumerate(nums): missing ^= element missing ^= (i+1) missing ^= (n+1) return missing def find_missing_number2(nums): nums_sum = sum(nums) n = len(nums) total_sum = (n+1)*n // 2 misssing = total_sum-nums_sum return misssing if __name__ == '__main__': nums =[1,5,3,4] print(find_missing_number(nums)) print(find_missing_number2(nums))
true
ecef91c3ad04267d79fb6849f50a2f37cf75c641
CatanaRaulAndrei/PythonDS_ALG
/BinarySearch.py
1,006
4.1875
4
def binary_search(target, input_list): middleIndex = int((len(input_list) - 1) / 2) + 1 for idx in range(len(input_list)): # 1.target is not in the list if target not in input_list: return False # 2.target is in the middle of the list if target == input_list[middleIndex]: return input_list[middleIndex] # 3.target is in left side of the list if target < input_list[middleIndex]: middleIndex = middleIndex - 1 return target # 4.target is in right side of the list if target >= input_list[middleIndex + 1]: middleIndex = middleIndex + 1 return target print(binary_search(90, [1, 7, 8, 23, 45, 71, 90, 101])) """ 1.if target is not in the list, return False 2.if target is in the middle of the list, return middle element 3.if target is < than the middle element, search in the left side of the list 4.if target is >= than the middle element, search in the right side of the list """
true
d072a558c1634c4fbfb5e5e573f737e3e4d0dcf5
its-lee/python-tutorial
/sections/3.2-more-functions.py
2,537
4.90625
5
"""Every function in Python receives a predefined number of arguments, if declared normally, like this: """ # %% def some_function(first, second, third): pass # %% """It is possible to declare functions which receive a variable number of arguments, using the syntax below. - *args must be placed after all positional arguments, and 'catches' all otherwise unspecified positional arguments. - It then places their values in a tuple named args. - 'args' is the conventional name for such an argument. """ # %% def foo(first, second, third, *args): print(f"First: {first}") print(f"Second: {second}") print(f"Third: {third}") print(f"And all the rest... {args}") foo(1, 2, 3, 4, 5) # %% """It is also possible to send functions arguments by keyword, so that the order of the argument does not matter, using the syntax below. - **kwargs must be placed after all keyword arguments, and 'catches' all otherwise unspecified keyword arguments. - It then places their values in a dict named kwargs. - 'kwargs' is the conventional name for such an argument. """ # %% def bar(first, second, third, **kwargs): if kwargs.get("action") == "sum": print(f"The sum is: {first + second + third}") if kwargs.get("number") == "first": print(first) bar(1, 2, 3, action="sum", number="first") # %% """Using *args and **kwargs """ # %% def receive(apple, orange, *args, ham=1, eggs=True, **kwargs): print("Today I received:") print(f"apple={apple}") print(f"orange={orange}") print(f"args={args}") print(f"ham={ham}") print(f"eggs={eggs}") print(f"kwargs={kwargs}") # The minimum number of argument required for a valid function call. receive(1, 2) # Using enough arguments to require *args and **kwargs to catch the excess receive(1, 2, 3, 4, 5, ham=2, eggs=False, cheese="hell yes", lamb="hell no") # %% """Functions (as with most definitions in Python) are first-class citizens, which is a big simplification in a lot of situations.. """ # %% def old_function(num): return 10 * num # Create an alias for new_function, for folks with ageism.. new_function = old_function print(new_function(50) == old_function(50)) # Try and import a function, falling back it if it does not exist: try: from os import some_non_existing_function except ImportError: def some_non_existing_function(): print( "Using the fallback, rather than something which doesn't exist in the os module" ) some_non_existing_function() # %%
true
4408e887367407f24118bc697717d302b7b85593
its-lee/python-tutorial
/sections/4.3-sets.py
961
4.40625
4
"""sets are like dicts mashed up with lists: - Every item appears only once uniquely. - They are unordered - They are unindexed """ # %% # Even though we construct the set with the value '1' specified multiple times, the constructed # object only contains it once. some_set = {1, 2, 4, 5, 1, 1, 1, 1} print(some_set) # %% """Because they're intrinsically hashed, as with dicts - they're super-fast for find-operations (much faster than a list) but generally slower for insertion. """ # %% from timeit import timeit def iter_test(iterable): candidate = 10000 if candidate in iterable: print(f"Found {candidate}") for collection in ["set", "list"]: number = 100000 print(f"When using a {collection}, {number} iterations..") print( timeit( "iter_test(iterable)", setup=f"from {__name__} import iter_test; iterable = {collection}(range(10000))", number=number, ) ) # %%
true
5cd71c86e108934fa53bd7ecb3652db7ce51f573
HieuChuoi/nguyenminhhieu-fundamental-c4e25
/session3/fix_password.py
519
4.375
4
loop = True while loop: pwd = input("Enter your password: ") loop = False #assume password is valid if len(pwd) < 8: print("Password length must be greater than 8") loop = True if not pwd.isalnum(): print("Password must not contain special characters") loop = True if pwd.isdigit(): print("Password must contain letters") loop = True if pwd.isalpha(): print("Password must contain digits") loop = True print("Password OK")
true
54fbe18381b9cb40a4b468f0cf77c724d3598cbf
BestPracticeSchool/BPS-BaseProgramming_2_2019
/Lec_3_08.10/proga7.py
212
4.125
4
# RANGE BASED FOR print("############WHILE LOOP##############") i = 0 while i <= 10: print(i) i += 3 print("#######FOR LOOP###########") for j in range(13): if j % 2 == 0: print(j )
false
46bc39cab755386a0d3c7512cb60111c7f8d7aa2
juffaz/module3
/task_4.py
471
4.125
4
print('Задача 4. Площадь треугольника') # Напишите программу, # которая запрашивает у пользователя длины двух катетов # в прямоугольном треугольнике и выводит его площадь. # Формула: # S = ab/2 a = int(input("Первый катет: ")) b = int(input("Второй катет: ")) s = (a * b / 2) print("Площадь : ", s)
false
1ed4ca1eb6683e44916ef1bd66dc62179183eff2
jeremyerickson31/assorted
/collatz_conjecture/run_collatz.py
2,541
4.3125
4
# small script to perform the Collatz Conjecture and graph the output # done two ways # with a while loop and recursive function # mathematics researchers have run 15 quintillion numbers and yet to find an exception # no proof yet exists for the conjecture import json from matplotlib import pyplot def collatz_recursive(sequence): """ perform the Collatz Conjecture algorithm using a recursive function :param sequence: input number to start with :return: series generated by Collatx algorithm as string of numbers """ seq_in_str = str(sequence) seq_in_list = seq_in_str.split(",") curr_num = int(seq_in_list[-1]) if curr_num % 2 == 0: next_num = int(curr_num / 2) else: next_num = int((curr_num * 3) + 1) seq_in_str += "," + str(next_num) if next_num == 1: return seq_in_str else: return collatz_recursive(seq_in_str) def collatz_whileloop(start_num): """ perform the Collatz Conjecture algorithm using a while loop :param start_num: input number to start with :return: series generated by Collatx algorithm """ collatz_series = list() curr_num = start_num collatz_series.append(curr_num) while curr_num != 1: if curr_num % 2 == 0: next_num = int(curr_num / 2) else: next_num = int((curr_num * 3) + 1) collatz_series.append(next_num) curr_num = next_num return collatz_series if __name__ == "__main__": arg = "plot" save_file = "collatz_series.json" if arg == "run": # ################## # make a list of numbers to run and store the results # ################## start_num_list = list(range(2, 100)) results = dict() for num in start_num_list: # series = collatz_whileloop(num) series = collatz_recursive(num) print(series) results[str(num)] = series # save to json f = open(save_file, "w") json.dump(results, f, indent=4) f.close() if arg == "plot": f = open(save_file) series = json.load(f) f.close() data_series = list(range(97, 98)) pyplot.subplot(1, 1, 1) for data_index in data_series: data = series[str(data_index)].split(",") data = [int(x) for x in data] pyplot.plot(data) pyplot.grid() pyplot.xlabel("Iteration") pyplot.ylabel("Value After Iteration") pyplot.show()
true
80c4a66d6dc750c050a4c1143bd4219e0039f964
rajlaxmi06/sorting_algo
/insertionsort.py
557
4.3125
4
def insertionsort(list,n): for i in range (1,n): key=list[i] j=i-1 while (j>=0 and key < list[j]): list[j+1]=list[j] j-=1 list[j+1]=key def printarr(list,n): for i in range(0,n): print("%d" %list[i]) n=int(input("Enter the total numbers of elements")) list=[0]*n for i in range(n): m=int(input("Enter the elements")) list[i]=m print("The order of elements before sorting:") printarr(list,n) insertionsort(list,n) print("The order of elements after sorting:") printarr(list,n)
true
eeac369f89d9f06d0bf386ae1fe616faa2c1b3f5
Sait-C/CS106-CSBridge
/Section11/Challenges&Solutions/Day7AM/sorted_numbers.py
507
4.125
4
""" File: sorted_numbers.py ------------------- This program prompts the user for 10 numbers, and then prints out those numbers in sorted order. """ def main(): inputs = get_input() #sort inputs.sort() show_elements(inputs) def show_elements(list): for element in list: print(element) def get_input(): input_list = [] for i in range(10): number = int(input("> ")) input_list.append(number) return input_list if __name__ == '__main__': main()
true
e8738afb7f907947d530d18388fc8787fddb8590
Sait-C/CS106-CSBridge
/Section16/Challenges&Solutions/Day9PM/phone_book.py
1,373
4.5625
5
""" File: phone_book.py ----------------- This program allows the user to store and lookup phone numbers in a phone book. They can "add", "lookup" or "quit". """ COMMAND_NOT_FOUND_MESSAGE = "This command is not found try again!" def main(): phone_book = {} print(f"Welcome to Phone Book! This program stores phone numbers of contacts. " f"You can add a new number, get a number, " f"or quit ('add', 'lookup', 'quit').") operation = get_input() while operation != 'quit': result = check_operation(operation, phone_book) if result: print(result) operation = get_input() def get_input(): print("Enter your command at the prompt.") return input("('add', 'lookup', 'quit') > ") def check_operation(operation, data): if operation == 'lookup': return search_from_data(data) elif operation == 'add': return add_to_data(data) elif operation == 'quit': return quit() else: return COMMAND_NOT_FOUND_MESSAGE def search_from_data(data): name = input("name? ") if name in data: return data[name] else: return f"{name} not found." def add_to_data(data): name = input("name? ") number = input("number? > ") data[name] = number return None def quit(): return 'quit' if __name__ == '__main__': main()
true
c9f7808aa8d579c8b81c46a4459edd5806c3e42b
Sait-C/CS106-CSBridge
/Section5/Challenges&Solutions/Day3PM/khansole_academy.py
1,070
4.34375
4
""" File: khansole_academy.py ------------------- This program generates random addition problems for the user to solve, and gives them feedback on whether their answer is right or wrong. It keeps giving them practice problems until they answer correctly 3 times in a row. """ # This is needed to generate random numbers import random def generateTwoRandomNumbers(min, max): a = random.randint(min, max) b = random.randint(min, max) return a, b def main(): correctCount = 0 while True: a, b = generateTwoRandomNumbers(10, 99) correctResponse = a + b print("What is " + str(a) + " + " + str(b) + " ?") userResponse = int(input("Your answer: ")) if userResponse == correctResponse: correctCount += 1 print("Correct! You've gotten " + str(correctCount) + " correct in a row.") if correctCount == 3: print("Congratulations! You mastered addition.") break else: correctCount = 0 print("Incorrect. The expected answer is " + str(correctResponse)) if __name__ == "__main__": main()
true
e6edb55104ff66345db19360ade6809492f1ff11
sydneybeal/100DaysPython
/Module2/Day23/module2_day23_lambdas.py
1,702
4.28125
4
""" Author: <REPLACE> Project: 100DaysPython File: module1_day23_lambdas.py Creation Date: <REPLACE> Description: <REPLACE> """ from typing import List def odds(x: int) -> List: """ Use a lambda function to provide a list of odd values between 0 and a maximum received from the user. :param x: Integer :return: List of odd integers from zero to the provided maximum. """ return list(filter(lambda x: x % 2, range(x))) # An example of the task using a loop odd = [] n = int(input("Provide a positive number greater than zero: ")) for i in range(n): if i % 2 != 0: odd.append(i) print("For Loop: {}".format(odd)) print("Lambda Function: {}".format(odds(n))) print("Lambda Expression: {}".format(list(filter(lambda n: n % 2, range(n))))) # Addition example of function vs lambda def adder(x: int, y: int) -> int: """ Adds two integers together :param x: integer :param y: integer :return: The sum of the two integer inputs. """ return x + y x = 1100 y = 17 add = lambda x, y: x + y print("Function: {}\nLambda: {}".format(adder(x, y), add(x, y))) print("=" * 100) # Casing example of function vs lambda def prop_case(s: str) -> str: """ Take a string input and convert it to the proper casing structure using the `.capitalize()` method. :param s: String in the received casing structure :return: The string converted into the proper casing structure """ return s.capitalize() s = str(input("Provide a string to convert to the proper casing structure.")) pcase = lambda s: s.capitalize() print("Function: {}\nLambda: {}".format(prop_case(s), pcase(s)))
true
0075c8415fb75932e271267f24d19d6c7e0ee882
pandaizumi/Python-Exercises
/Python Crash Course/Chapter 03/more_guests.py
1,139
4.21875
4
# Exercise 3.6 guests = ['jamie', 'hewitt', 'skye'] print(f"Hello {guests[0].title()}, you've been invited to dinner.") print(f"Hello {guests[1].title()}, you've been invited to dinner.") print(f"Hello {guests[2].title()}, you've been invited to dinner.") print() print(f"Oh no, it looks like {guests[0].title()} can't make it.") guests[0] = 'terris' print() print(f"Hello {guests[0].title()}, you've been invited to dinner.") print(f"Hello {guests[1].title()}, you've been invited to dinner.") print(f"Hello {guests[2].title()}, you've been invited to dinner.") print() print("Hey, everyone it looks like I've found a bigger dinner table.") guests.insert(0, 'kay') guests.insert(2, 'alexi') guests.append('shan') print() print(f"Hello {guests[0].title()}, you've been invited to dinner.") print(f"Hello {guests[1].title()}, you've been invited to dinner.") print(f"Hello {guests[2].title()}, you've been invited to dinner.") print(f"Hello {guests[3].title()}, you've been invited to dinner.") print(f"Hello {guests[4].title()}, you've been invited to dinner.") print(f"Hello {guests[5].title()}, you've been invited to dinner.")
true
028f291f3bbdb7a02cc95a0468e261b925e0f1b7
RDozier22/psychic-networking
/Systems GitHub/calc2.py
2,058
4.3125
4
#!/usr/bin/python3 ''' Pseudo Code: Step 1: Build basic calculator script Step 1a: Build predefined functions Step 2a: Define main function Step 2: Print statement that tells user that it is a calculator Step 3: Establish variables as integers that ask user to provide x and y input Step 4: Estabish variable that asks user to select Add, Sub, Mul, or Div Step 5: Establish input validation for number length Step 6: Establish if statement for first choice Step 7: Establish print statements for if statement Step 8: Establish elif statements for following three choices Step 8a: Establish statement so you cannot divide by 0 Step 9: Establish print statements following three elif choices Step 10: Establish else statement if user does not input correct functions ''' def addition(x,y): return x + y def subtraction(x,y): return x - y def multiplication(x,y): return x * y def division(x,y): return x / y def main(): print ('Basic Calculator 2') choice=input("add, sub, mul, or div' ('add' or 'sub' or 'mul' or 'div')?") x = input('Input number: ') y = input('Input number: ') if len(x) > 10: exit ('You must chose a number less than 10') elif len(y) > 10: exit ('You must chose a number less than 10') else: x = int(x) y = int(y) if choice == 'add': answer=addition(x,y) print ('You chose Addition') print (f'Your answer is: {answer}') elif choice == 'sub': answer=subtraction(x,y) print ('You chose Subtraction') print (f'Your answer is: {answer}') elif choice == 'mul': answer=multiplication(x,y) print ('You chose Multiplication') print (f'Your answer is: {answer}') elif (choice == 'div') and ('x == 0') or ('y == 0'): exit ('You cannot DIVIDE by 0') elif choice == 'div': answer=division(x,y) print ('You chose Division') print (f'Your answer is: {answer}') else: print ('You did not chose a correct calculator function') main()
true
46718a41299afc2bc022cd727cb9c99221f20691
0xMYsteRy/Big_Data
/DataStructure/BinaryTree/BinaryTreeSample.py
553
4.125
4
# Python Program to introduce Binary Tree # A class that represents an individual node a binary tree. class Node: def __init__(self, key): self.left = None self.right = None self.value = key # Create Root root = Node(1) ''' Following is the tree after above statment 1 / \ None None ''' root.left = Node(2) root.right = Node(3) ''' 2 and 3 become left and right children of (1) 1 / \ 2 3 / \ / \ None None None None ''' root.left.left = Node(4)
true
bc8a27b018260cf2367efd0c496d4e84f7092151
infoyashpanchal/Cesar-Chipher-Simulator
/cc_decrypt.py
588
4.28125
4
def decrypt(): print("Welcome to Caesar Cipher Decryption.\n") encrypted_message = input("Enter the message you would like to decrypt: ").strip() print() key = int(input("Enter key to decrypt: ")) decrypted_message = "" for letter in encrypted_message: if (letter.isalpha()): if (letter.isupper()): decrypted_message += chr((ord(letter) -key -65)%26 +65) elif (letter.islower()): decrypted_message += chr((ord(letter) -key -97)%26 +97) else: decrypted_message += letter print(decrypted_message) decrypt()
true
675e159e57018cee10c21a52ec9db523e8698197
espiercy/py_junkyard
/python_udemy_course/62 sorting dictionary.py
489
4.21875
4
#create dictionary fruits= {'mango':576,'grapes':200,'oranges':300,'banana':20,'strawberry':1000} #get minimum value print(min(fruits.values())) #if we want key along with val, use zip function print(min(zip(fruits.values(),fruits.keys()))) print(min(zip(fruits.keys(),fruits.values()))) print(max(zip(fruits.values(),fruits.keys()))) #sort print(sorted(zip(fruits.values(),fruits.keys()))) #can also sort by key, just put it first print(sorted(zip(fruits.keys(),fruits.values())))
true
8fca1567125b384f1bc2da3ef3e924dcdeae185f
espiercy/py_junkyard
/Python_Programming_For_The_Absolute_Begginer_Scripts/HeroInventory.py
796
4.375
4
#Hero's Inventory #Demonstrates tuple creation #Evan Piercy #3.20.15 #I think this text makes a mistake introducing tuples this way. #Tuples turn out to be an extraordinarily important data structure #They really deserve their own chapter. #When I started my way through this book several years ago, I didn't #Really know/understand what a 'tuple' was. #creat empty tuple inventory = () #treat tuple as condition if not inventory: print("You are empty handed!") input("Press enter key to continue.") #create a tuple with some items inventory = ("sword" , "armor" , "shield" , "healing potion") #print tuple print("\nThe tuple inventory is: ") print(inventory) #print each element print("\nYour items: ") for item in inventory: print(item) input("\n\nPress the enter key to exit.")
true
338cac53e8bdb1cf48e078ad2eba50c84c38df9f
espiercy/py_junkyard
/python_udemy_course/14 tuple.py
345
4.125
4
#here's a tuple: test_tuple=(2,3,56,"text in a tuple") print(test_tuple) print(test_tuple[0]) #can't change tuple values #test[1]="poop" #empty tuple empty=() second_test=test_tuple*3 print(second_test) new=('new tuple','hi earth') joined_tuple=test_tuple+new print(joined_tuple) print(joined_tuple[1:4]) t1=joined_tuple[1:5] print(t1)
true
aa38dce44c1f8bdf355af27106c0e9844900c4c3
roynozoa/Python-Fast-Course
/[3] Intermediate Python/intermediate_python_1.py
1,222
4.46875
4
# Intermediate Programming in python # This source code is my practical learning programming in python # Muhammad Adisatriyo Pratama - October 2020 # (1) Import statement and working with dates (use and format date) # import datetime module in python from datetime import datetime from datetime import date import math # import library in python # another example from math import pi # (only import certain module) string = 'Hello World' print(string.upper()) # example of a built in function in python print(math.pi, math.cos(1)) # usage of the math library in python def area_of_circle(r): return r*r*pi # using 'pi' instead of math.pi print(f'Area of a circle with 10 radius = {area_of_circle(10)}') print('================') # Dates print(datetime.now()) # print current date and time print(date.today()) # print current date print(datetime.now().time()) # print current time print('================') # Formatting dates # %d = date of month, %m = month(num), %b = month name (short), # %B = month name, %Y = year, %M = minutes, %S = seconds now = datetime.now().strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YYYY HH:MM:SS now2 = datetime.now().strftime("%d-%b-%Y %H:%M:%S") # dd-bbb-YYYY HH:MM:SS print(now) print(now2)
true
39cf58bb0ad03154e0a7fa0328aa6982edd0a690
dsouzaly/gpaCalculator
/gradeCalc.py
1,865
4.15625
4
import math; "What grade do I currently have" def gpa2(grade): if grade >= 85: gpa = "4.0" elif grade >= 80: gpa = "3.7" elif grade >= 77: gpa = '3.3' elif grade >= 73: gpa = '3.0' elif grade >= 70: gpa = '2.7' elif grade >= 67: gpa = '2.3' elif grade >= 63: gpa = '2.0' elif grade >= 60: gpa = '1.7' elif grade >= 57: gpa = '1.3' elif grade >= 57: gpa = '1.0' elif grade >= 50: gpa = '.7' else: gpa = 'Step your damn game up' return gpa def tell_me(): current_grade = 0 total_weight = 0 more = 'y' gpa = 0 while more != 'n': mark = float(input("Input your mark: ")) out_of = float(input("Input total marks: ")) grade = mark/out_of weight = float(input("Input the weight (percent): ")) more = input("more (y/n): ") current_grade += grade*weight total_weight += weight current_grade = round(current_grade,2) total_weight = round(total_weight,2) gpa = gpa2(round(100*current_grade/total_weight)) print("Your current gpa: " + gpa) print("Your current percent: " + str(round(100*current_grade/total_weight,2))) print("You have earned " + str(current_grade) + "/" + str(total_weight) + " of the marks awarded.") best_grade = 100 - total_weight + current_grade gpa = gpa2(best_grade) print("your best possible percent: " + str(best_grade)) print("your best possible gpa: " + gpa) more = 'y' while more != 'n': mark = float(input("What do you want in the course (percent): ")) avg = round(100*(mark - current_grade)/(100-total_weight),2) print("You need to get a " + str(avg) + "% from now on") more = input("more (y/n)") tell_me()
false
18a5447738ce3f983ca835775a2b816fce758e57
ErenBtrk/PythonRecursionExercises
/Exercise1.py
275
4.15625
4
''' 1. Write a Python program to calculate the sum of a list of numbers. ''' def function(list,start,end): if(start == end): return 0 else: return list[start] + function(list,start+1,end) list1 = [1,2,3,4,5,5] print(function(list1,0,len(list1)))
true
2358d1b34533e09ff50d7682a9b5ffee7f3f698c
DurantSim/Data-structure
/sorting algorithm/Quick Sort.py
1,241
4.1875
4
""" Quick sort Best case: O(n log n) , for simple partition with simple swap Worst case: O(n^2) , when list is sorted and choose the largest value as pivot, in partition process it will move everything in front for each loop """ def quick_sort(list): left = 0 right = len(list)-1 splitpoint = partition(left,right,list) partition(left,splitpoint-1,list) partition(splitpoint+1,right,list) return list def partition(left,right,list): pivot_val = list[len(list)-1] while True: while list[left] < pivot_val: #move pointer to right and will stop if value is greater than pivot left +=1 while list[right] >= pivot_val: #move pointer to left and will stop if value is smaller than pivot right -=1 if left > right: #if left pointer is greater than right pointer, values which smaller than pivot should be at front of right pointer break else: list[left] , list[right] = list[right],list[left] #swap latest left pointer position value with latest right pointer position value list[left],list[len(list)-1]= list[len(list)-1],list[left] return left #return splitpoint where pivot is in correct position
true
2b2f72c87bc1d580f37970f9ff3e49880523c946
zacharywilliams05/portfoliowork
/python/high_low_game.py
646
4.3125
4
#!/usr/bin/env python3 #creating a high and low numbers game import random #generate a random number between 1 and 10 number = random.randint(1, 10) print(number) #user guesses a number between 1 and 10 guess = int(input("Guess a number between 1 and 10: ")) while guess != number: #if the number is too high we tell them and ask to guess again if guess > number: guess = int(input("Too high! Try again: ")) #if the number is too low we tell them and ask to guess again elif guess < number: guess = int(input("Too low Try again: ")) #if the user guesses the number we congratulate them print("Well done! You got it!")
true
f63c854271d790c8c29a52476e9be10f2afe6a02
alexander-colaneri/python
/studies/curso_em_video/ex026-primeira-e-ultima-ocorrencia-de-uma-string.py
1,386
4.375
4
# Primeira e última ocorrência de uma string # Enunciado: Faça um programa que leia uma frase e mostre: # 1 - Quantas vezes aparece a letra "A" # 2 - Em que posição ela aparece a primeira vez. # 3 - Em que posição ela aparece a última vez. print() frase = str(input('Digite a frase: ')).strip().upper().replace('', "").replace('Ç', 'C').replace('Â', 'A').replace('Ã', 'A').replace('Á', 'A').replace('À', 'A').replace('É','E').replace('Ê', 'E').replace('Í', 'I').replace('Õ', 'O'). replace('Ô', 'O').replace('Ó', 'O').replace('Ú', 'U') # O "replace" foi adicionado como um extra, para localizar vogais com acentos e cedilha. Foi preciso adicionar # replace('', ""), não sei ainda o raciocínio mas funcionou. letra = str(input('Digite a letra a ser encontrada: ')).strip().upper() print() # A escolha da letra não era parte do exercício, mas resolvi colocar após ver um comentário. print(f'A letra "{letra}" apareceu {frase.count(letra)} vez(es).') print(f'A letra "{letra}" apareceu pela primeira vez na posição {frase.find(letra) + 1}.') # Foi colocado um "+1" acima para indicar a posição da letra na língua portuguesa, não na linguagem Python. print(f'A letra "{letra}" apareceu pela última vez na posição {frase.rfind(letra) + 1}.') # A funcionalidade rfind procura da direita (right) para a esquerda, mantendo a contagem da esquerda para direita.
false
7d570802f9768317d2eeff2e061e2f21f6d65fe3
alexander-colaneri/python
/studies/curso_em_video/ex035-analisando-triangulo-V1.py
737
4.3125
4
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar # um triângulo. print() print('*-' * 7, 'Analisador de Triângulos', '*-' * 7) # Regra matemática. Para um triângulo "fechar", a soma de dois lados não pode ser menor que um dos lados. # Ou seja, por exemplo, lado1 < lado2 + lado3 l1 = float(input('Digite o comprimento do primeiro lado: ')) l2 = float(input('Digite o comprimento do segundo lado: ')) l3 = float(input('Digite o comprimento do terceiro lado: ')) print() if l1 < l2 + l3 and l2 < l1 + l3 and l3 < l1 + l2: print(f'Os lados {l1}, {l2} e {l3} podem formar um triângulo!') else: print(f'Os lados {l1}, {l2} e {l3} NÃO podem formar um triângulo!')
false
fa5d7f768b84497e4a70cf99121d0f07989b4247
alexander-colaneri/python
/studies/curso_em_video/ex072-inicio-mundo-3-numero-por-extenso.py
678
4.375
4
# Crie um programa que tenha uma tupla totalmente preenchida com uma # contagem por extenso, de zero até vinte. Seu programa deverá ler um número # pelo teclado (entre 0 e 20) e mostrá-lo por extenso. extenso = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte') print() numero = int(input('Digite um número entre 0 e 20: ')) while numero > 20: numero = int(input('Opção inválida, digite um número entre 0 e 20: ')) print(f'*** Por extenso, o número {numero} é "{extenso[numero]}". ***')
false
81772114767e30e203ba212d1b32cd9e61d95f9f
jlucasldm/coursera
/cienciaDaComputacaoPython/lista5/imprime_retangulo_cheio.py.py
643
4.34375
4
# Escreva um programa que recebe como entradas (utilize a # função input) dois números inteiros correspondentes à # largura e à altura de um retângulo, respectivamente. O # programa deve imprimir uma cadeia de caracteres que # represente o retângulo informado com caracteres '#' na # saída # digite a largura: 10 # digite a altura: 3 # ########## # ########## # ########## # digite a largura: 2 # digite a altura: 2 # ## # ## larg = int(input('digite a largura: ')) alt = int(input('digite a altura: ')) i = 0 j = 0 while i != alt: j = 0 while j != larg: print("#", end='') j+=1 print('') i+=1
false
fc2705619b31a52ec5984b13d73f8c7c8b34d669
jlucasldm/coursera
/cienciaDaComputacaoPython/lista3/soma_digitos.py
343
4.125
4
# Escreva um programa que receba um número inteiro na entrada, # calcule e imprima a soma dos dígitos deste número na saída # Exemplo: # Digite um número inteiro: 123 # 6 num = int(input('Digite um número inteiro: ')) soma = 0 while num != 0: if num<0: num*=-1 var = num%10 soma+=var num = num//10 print(soma)
false
ab8bce508ba568fbaed2cc1094d8bfa764b6f132
MATE-Programming/Student-s-Works
/Урок 5/Asror Abduvosiqov/problem1 (2).py
372
4.1875
4
# думаю тут коментарий не надо так как тут все очень просто и легко class Cricle: def __init__(self): self.r = 0 self.p = 3.14 def func(self): self.perimetr = 2 * self.p * self.r self.s = self.p * (self.r ** 2) print(self.s, self.perimetr) a = Cricle() a.r = 8 a.func()
false
4a7a9d382575c71dc30659d9b5e589d42cd3dbcf
pythonbootcamp19/Boot_Camp_19
/ex39.py
1,723
4.375
4
#In dictionary we save in pairs. For e.g. cities = {"Vikas" : "Bombay"}. print(cities["Vikas") #create a mapping of state to abbreviation states = { 'Maharashtra': 'Mah', 'Karnataka': 'Kar', 'Andra Pradesh': 'AP', 'Utter Pradesh': 'UP', 'Kerala': 'Ker', } # create a basic set of states and some cities in them cities = { 'Mah': 'Mumbai', 'Kar': 'Bangalore', 'AP': 'Vishakapatnam', } # add some more cities cities['UP'] = 'Lucknow', cities['Ker'] = 'Coachin', #print out some cities print('-' * 10) print("Utter Pradesh state has: ", cities['UP']) print("Kerala state has: ", cities['Ker']) #print some states print('_' * 10) print("Maharashtra's abbreviation is: ", states['Maharashtra']) print("Utter Pradesh's abbreviation is: ", states['Utter Pradesh']) #do it by using the state then cities dict print('_' * 10) print("Maharashtra has: ", cities[states['Maharashtra']]) print("Andhra Pradesh has: ", cities[states['Andra Pradesh']]) #print every state abbreviation print('_' * 10) for state, abbrev in list(states.items()): print(f"{state} is abbreviated {abbrev}") #print every city in state print('_' * 10) for abbrev, city in list(cities.items()): print(f"{abbrev} has the city {city}") #now do both at the same time print('_'*10) for state, abbrev in list(states.items()): print(f"{state} state is abbreviated {abbrev}") print(f"and has city {cities[abbrev]}") print('_'*10) #safely get a abbreviation by state that might not be there state = states.get('Madhya Pradesh') if not state: print("Sorry, no Madhya Pradesh.") #get a city with a default value city = cities.get('MP', 'Does not Exist') print(f"The city for the state 'MP' is: {city}")
false
aed9f982b85a7c7ae4a5929a105f535a8647a78d
graphtobinary/Basic-mathematics-python-program-example
/kilometers_into_miles.py
296
4.5
4
# Program to convert kilometers into miles # change this value for a different result kilometers = float(input('Enter kilometers: ')) # conversion factor conv_fac = 0.621371 # calculate miles miles = kilometers * conv_fac print('{0} kilometers is equal to {1} miles'.format(kilometers,miles))
true
28d897ef7cfeda7aece209241671634412df1225
mandresblanco/Datacademy
/Week 1/milla.py
1,428
4.375
4
'''Reto 3 - Conversor de millas a kilómetros Imagina que quieres calcular los kilómetros que son cierta cantidad de millas. Para no estar repitiendo este cálculo escribe un programa en que el usuario indique una cantidad de millas y en pantalla se muestre el resultado convertido a kilómetros. Toma en cuenta que en cada milla hay 1.609344 Km Bonus: haz que el usuario pueda escoger entre convertir millas a kilómetros o kilómetros a millas.''' import os def mtokm(): millas = float(input("Ingresa las Millas a convertir: ")) kilometros = millas/1.609344 print(f'{millas} Millas son equivalentes a {round(kilometros, 4)} Km') def kmtom(): kilometros = float(input("Ingresa los Kilometros a convertir: ")) millas = kilometros*1.609344 print(f'{kilometros} Km son equivalentes a {round(millas, 4)} Millas') def run(): print('''\nBienvenido al conversor Milla/Kilometro, puedes elegir una de las 2 opciones:''') salir = False while not salir: print('''\n 1. De Millas a Kilometros.\n 2. De Kilometros a Millas.\n ''') opcion = int(input("Elige una opcion:")) if opcion == 1: mtokm() salir = True elif opcion == 2: kmtom() salir = True else: os.system ("cls") print('Debes escoger una opcion valida!\n' ) if __name__ == '__main__': run()
false
9db3b5a20cc080e40c21856cd95e4e127d4d893f
BashayerNouri/python
/conditions_task.py
1,210
4.25
4
# Foundations 3: Python # Task Two # This is a calculator. the code ask the user for two numbers and the mathematical operation # and then print the result of that operation. first = input("Enter the first number: ") second = input("Enter the second number: ") operation = input("Choose the operation (+, -, /, *): ") if (first.isdigit()) and (second.isdigit()): if operation == "+": result = int(first) + int(second) print("The answer is " + str(result)) elif operation == "-": result = int(first) - int(second) print("The answer is " + str(result)) elif operation == "*": result = int(first) * int(second) print("The answer is " + str(result)) elif operation == "/": result = int(first) / int(second) print("The answer is " + str(result)) else: # If the user added an alphabet in the operation area print("The operation is not valid!, The operation was not any of the choices(+, -, *, /)") else: # Cases: # If the user added an alphabet in: # 1) one of the inputs # 2) two of the inputs # 3) one of the inputs and in the operation # 4) all of them. print("Not valid, check the inputs or the operation")
true
bcb5f50aadbfe74992c9f229b3ece35e5a44eed0
simplymanas/python-learning
/palindrome.py
258
4.28125
4
# verify if a string is palindrome or not # avoid using built in function input_string = input ("Enter the string : ") if input_string[::-1].lower() == input_string.lower(): print ("Oh My God!!! that's a palindrome 👏") else: print ("Try again ")
true
123ace045db3cd03e44cc51df57ed19c1a98d7f3
simplymanas/python-learning
/SetOperation.py
1,103
4.34375
4
# Date: 27th Jun 2020 # Lets learn Set Theory in Python # Few Operations on Sets # Let's take two sets first_set = {11, 21, 31, 41, 51} second_set = {11, 61, 71, 81, 31} print('First Set : ' + str(first_set)) print('Second Set : ' + str(second_set)) # The basic operations are: # 1. Union of Sets print('\nUNION of the two sets are (Both in first and second)') print(set(first_set) | set(second_set)) # inbuilt function print(first_set.union(second_set)) # 2. Intersection of sets print('\nIntersection of the two sets are (common to both)') print(set(first_set) & set(second_set)) # inbuilt function print(first_set.intersection(second_set)) # 3. Difference of two sets print('\nDifference of the two sets are (in first but not in second) ') print(set(first_set) - set(second_set)) # inbuilt function print(first_set.difference(second_set)) # 4. Symmetric difference of two sets print('\nSymmetric Difference of the two sets are (excluding the common element of both) ') print(set(first_set) ^ set(second_set)) # inbuilt function print(first_set.symmetric_difference(second_set)) print()
true
9c916a5385b119983937fb612033620b746887b4
simplymanas/python-learning
/GetDigitsOfAWholeNumber.py
390
4.34375
4
# Whole number to digits # Writing whole numbers in expanded form # 11th August 2020, Janmasthmai Day # Manas Dash whole_number = 16789 # list comprehension digits = [int(a) for a in str(whole_number)] print(digits) # map digits = list(map(int, str(whole_number))) print(digits) # str function digits = list(str(whole_number)) print(digits) # which one is simpler or may be better? print(ord(1))
true
a54edb5812159e4f149ff0df2538509d530b89c6
GrearNose/Algorithm
/Basic/primes_sifting.py
1,659
4.15625
4
from math import ceil def primes_sifting(n): """ Get all the prime numbers smaller that the given n. """ if None == n or n <2: return None primes = [] sift = [True]*(n+1) i = 2 while i**2 <= n: for j in range(i**2,n+1,i): sift[j] = False primes.append(i) i += 1 while not sift[i] and i <= n: i += 1 for j in range(i,n+1): if sift[j]: primes.append(j) return primes def primes_get_more(primes, n_extra): """ Get n_extra more prime numbers given the previous prime number. ==== Args ==== primes: the previous prime numbers starting with 2; n_extra: the amount of extra prime numbers to get. return: None. The extra prime numbers will be appended to 'primes'. """ assert isinstance(primes, list) assert n_extra > 0 if 0 == len(primes): primes = [2] for cnt in range(n_extra): num = 1 + primes[-1] # the first number to try found = False while not found: upper = ceil(num**.5) is_prime = True for p in primes: if 0 == num % p: is_prime = False break if p >= upper: # found a prime number. break if is_prime: primes.append(num) found = True num += 1 def test(): n = 35 primes = primes_sifting(n) print(primes) n_extra = 3 primes_get_more(primes,n_extra) print('get %d more primes:'%n_extra) print(primes) if __name__ == '__main__': test()
true
029c4d0a05ef6d75002b5fb5dd7b133dc1996161
cs-fullstack-2019-fall/weekly4-retake-Kenn-CodeCrew
/q4.py
388
4.3125
4
# Ask the user to enter a number to add to a total. Keep asking the user to enter a number until they enter 0. Afterward, print the total of all numbers entered. userInput = input("Enter a number to add to a total") total = 0 while(userInput != "0"): total = total + int(userInput) userInput = input("Enter aother number to add to the total") print("The total is " + str(total))
true
e66d7cea25028ca5b978ff78b653c32d48cca9e3
goguvova/codecademy-Learn-Python-3
/LISTS(Combine Sort).py
419
4.15625
4
##Write a function named combine_sort that has two parameters named lst1 and lst2. ## ##The function should combine these two lists into one new list and sort the result. Return the new sorted list. #Write your function here def combine_sort(lst1, lst2): combine = lst1 + lst2 combine.sort() return combine #Uncomment the line below when your function is done print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))
true
c6611487e55e08a522aae12876ed885a0ff4d4f2
goguvova/codecademy-Learn-Python-3
/LOOPS(Odd Indices).py
513
4.4375
4
##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. ## ##For example, odd_indices([4, 3, 7, 10, 11, -2]) should return the list [3, 10, -2]. #Write your function here def odd_indices(lst): empty =[] empty = lst[1:len(lst):2] return empty #Uncomment the line below when your function is done print(odd_indices([4, 3, 7, 10, 11, -2]))
true
278a0152ee248334876043d880733987f7175ee4
goguvova/codecademy-Learn-Python-3
/LOOPS(Max Num).py
371
4.25
4
##Create a function named max_num() that takes a list of numbers named nums as a parameter. ## ##The function should return the largest number in nums #Write your function here def max_num(nums): maxx = nums[0] for i in nums: if i >maxx: maxx =i return maxx #Uncomment the line below when your function is done print(max_num([50, -10, 0, 75, 20]))
true
9bd7cf952b131989cd3f07d62ade41906841aabd
saintaubins/random_algos
/interview_questions.py
1,774
4.1875
4
import math #import pdb; pdb.set_trace() #breakpoint() #python -m pdb interview_questions.py #import inspect class Prime_num: def __init__(self, num): self.num = num def find_prime(self): abs_val = abs(num) root_val = math.sqrt(abs_val) root_val = int(root_val) print('root_val:',root_val) if abs_val <= 1: print('number is zero or 1 and cannot be prime') print('$' * abs_val) elif abs_val == 2 or abs_val == 3: print('number is', abs_val , 'and is prime') print('$' * abs_val) elif abs_val % 2 == 0: print('number is not prime, because it is an even number') print('$' * abs_val) elif num >= 3: i = 3 #breakpoint() while i <= 1+root_val: if num % i == 0: print(num,'is not prime') break else: print(num,'is prime') break i += 2 num = 2 p = Prime_num(num) x = list(range(0, 20)) x_e = [i for i in x if i%2 == 0] x_o = [i for i in x if i%2 != 0] print('x_e = ',x_e) print('x_o = ',x_o) print(p.find_prime()) #print(inspect.getsource(count)) ##################### 2-1-21 Apple interview question 6;45pm EST ######################## a = [22,25] b = ['python', 'programming'] """return odd-indexed list from list a -> [25,46]""" for i,v in enumerate(a): if i % 2 != 0: print(v, a[i]) # slicing -> print(a[1:len(a):2]) print(a[1::2]) # then second question merge a:b into key value res = {} for k,v in zip(a,b): res[k] = v print(res) print({k:v for k,v in zip(a,b)}) ## my solution print(dict(zip(a,b)))
false
ca40b682c3465d1fa3a8b3d75472eccb5660b46f
Ridhima12345/lab7
/Python_Task1/program_sum.py
263
4.125
4
#function for calculating sum def sum(a,b): c = a + b print(c) print(float(c)) #function for calculating product def mul(a,b): c = a * b print(c) #input a = int(input("Enter a")) b = int(input("Enter b")) #function call sum(a,b) mul(a,b)
true
4336ad7cbfbab8eea4abcc558e797a5ac1b61b29
chingdrop/Python-practice
/Reverse_List.py
2,236
4.25
4
import random #Create a new class to handle all methods called from main(). class List: #Creates the constructor which creates a list on startup. def __init__(self): self.initList = [] #This method fills the empty list with 20 random digits between 1 and 100. def createList(self): #Assigns the constructor list to a new variable. newList = self.initList #Uses iteration to create 20 random numbers. for x in range(20): #Random numbers from 1 to 100 are assigned to the element variable. newRandom = random.randint(1,100) #The random number is appended to the list. newList.append(newRandom) #The method returns the list filled with the new entries. return newList #This method reverses the list by using slicing. def reverseList(self, listVal): #Returns a copy of the first list but reversed by using slicing. return listVal[::-1] #This method calculates the big O efficiency for the program. def bigOCalc(self, listVal): #Since a copy is created the formula O(n) is used. #This is linear with the number of entries to the list. n = len(listVal) #The slicing effort is a different integer than the length of the list. #Since the entire list is sliced, the length of the list is used. k = n #Returns the bigO efficiency. return n + k def main(): #The class is loaded under the randomList variable. randomList = List() #To create the inital list, the createList method is called. beforeList = randomList.createList() #To reverse the initial list, the reverseList method is given the initial list as a parameter. afterList = randomList.reverseList(beforeList) #To calculate the bigO, the bigOCalc method is given the reversed list as a parameter. bigOList = randomList.bigOCalc(afterList) #These statements turn data objects into strings, and prints the output from the program. print(str(beforeList)) print(str(afterList)) print(str(bigOList)) main()
true
a28dfa30fd1c50adc76545ffc3fba86baeb7d5f0
rehammarof/network_programming_hw1
/Question1/Q1B.py
407
4.4375
4
print("This Program calculate (a+b) or (a-b) or (a*b) or (a/b)") a = int(input("Enter a: ")) b = int(input("Enter b: ")) operation = input("Enter the operation: ") if operation=="+": res=a+b elif operation=="-": res=a-b elif operation=="*": res=a*b elif operation=="/": res=a/b else: res='error' if res!='error': print("{0}{1}{2}={3}".format(a,operation,b,res)) else: print(res)
false
582aa93abe5fc116769e1468c82235b4b21f2f0c
nartu/test-tasks
/4_algo/factorial.py
380
4.125
4
def factorial(n): f = 1 if n==0 or n==1: return f for i in range(2,n+1): f = f * i # print(f) return f def factorial_r(n): f = 1 if n==0: print(f"Step: {n}, result: {f}") return f f = n * factorial_r(n-1) print(f"Step: {n}, result: {f}") return f if __name__ == '__main__': print(factorial_r(3))
false
47677d63b378eb5e17c67d59670c14ede2a762a7
bmazey/python_solutions
/challenges/interview/src/palindrome.py
292
4.1875
4
class Palindrome(object): """this is our palindrome class""" @staticmethod def is_palindrome(s): reverse = '' for i in range(len(s)): reverse += s[len(s) - 1 - i] if s == reverse: return True else: return False
false
f122e937806ca314bbdae367d10d009b7c14b2c6
virajnemane/Python
/Lec-2/for.py
939
4.28125
4
# When we need to repeat any task for number of time, we use for loop #for i in range(5): # print(i) student_names=['nilesh','mayura','arnav'] student_marks=[56,78,93] student_marksheet={'nilesh':39,'mayura':52,'arnav':74} for i in student_names: print("Student name : ", i) #for (a,b) in zip(student_names,student_marks): # print(a , " : " , b) #Sort even odd number even_num = [ ] odd_num = [ ] for num in range(0,100): if num%2 == 0: even_num.append(num) else: odd_num.append(num) print(even_num) print(odd_num) # continue....break in for loop for h in range(10): if h==3: continue #skips the next statements and shifts pointer to the top of the loop print(h,h**2) if h==7: break #break the loop abruptly and changes the pointer to the end of the loop else: print("I am out of for loop") #executes when for loop has ended without executing break
true
f69ad4d21baca3643b5bf9e3ebd8799b7567d3cf
alby177/Training
/pyStuff/Calcolatrice.py
2,209
4.25
4
while True: print(''' Benvenuto, qui trovi una semplice calcolatrice! Creata da: Alberto Di seguito un elnco delle varie funzioni disponibili - Per effettuare un\'addizione seleziona 1; - Per una sottrazione seleziona 2; - Per effettuare una moltiplicazione seleziona 3; - Per effettuare una divisione seleziona 4; - Per effettuare un calolo esponenziale seleziona 5; - Per uscire dal programma digitare ESC; ''') scelta = input('Inserisci il numero corrispondente all\'azione desiderata ----> ') if scelta == '1': print('\nHai scelto addizione\n') a = float(input('Inserisci il primo numero -> ')) b = float(input('Inserisci il secondo numero -> ')) print('Il risultato della somma è: ' + str(a + b)) elif scelta == '2': print('\nHai scelto sottrazione\n') a = float(input('Inserisci il primo numero -> ')) b = float(input('Inserisci il secondo numero -> ')) print('Il risultato della sottrazione è: ' + str(a - b)) elif scelta == '3': print('\nHai scelto moltiplicazione\n') a = float(input('Inserisci il primo numero -> ')) b = float(input('Inserisci il secondo numero -> ')) print('Il risultato della moltiplicazione è: ' + str(a * b)) elif scelta == '4': print('\nHai scelto divisione\n') a = float(input('Inserisci il dividendo -> ')) b = float(input('Inserisci il divisore -> ')) print('Il risultato della divisione è: ' + str(a / b)) elif scelta == '5': print('\nHai scelto sottrazione\n') a = float(input('Inserisci la base -> ')) b = float(input('Inserisci l\'esponente -> ')) print(' Il risultato della potenza è: ' + str(a ** b)) elif scelta == 'ESC': print('Sto chiudendo l\'applicazione....') break else: print('Bad input command') loop = input('Desideri proseguire? S per continuare, N per uscire -> ') print('\n********************************************************') if loop == "S" or loop == "s": continue elif loop == "N" or loop == "n": break else: print('Invalid command') continue
false
2dbc2157c09c6cf30c54aa58f5d86da85cb44e77
alby177/Training
/pyStuff/Liste3.py
1,157
4.21875
4
inventario = ['torcia', 'spada', 'pane elfico', 'arco'] print(inventario) inventario.append('frecce') # permette di inserire un elemento alla fine della lista print(inventario) def riempiInventario(): inventario = [] while True: oggetto = input("Cosa vuoi aggiungere all'inventario?\n") if oggetto == 'terminato' or oggetto == 'Terminato': break else: inventario.append(oggetto) print('La lista prodotta è: ', inventario) inventario.remove('spada') # permette di togliere l'elemento indicato come agomento della funzione print(inventario) inventario.sort() # ordina in ordine alfabetico la lista print(inventario) numeri = [4, 5, 1, 12, -1, 3] numeri.sort() # mette in ordine i numeri in ordine crescente print(numeri) # aggiungendo "Reverse" come parametro della funzione sort() ordina la lista in ordine inverso print(inventario.index('frecce')) # permette di capire qual'è l'indice dell'elemento fornito come parametro inventario.insert(2, 'canna da pesca') #inserisce alla posizione passata come parametro l'elemento passato come parametro print(inventario)
false
5fe5507d5cb0208baeecd0b3d4c11d5605fe1e93
ThisIsJorgeLima/Intro-Python-I
/src/05_lists.py
1,351
4.5
4
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). """ append() is a method in python which adds a single item to the existing list. In this case a Four """ # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.append(4) print(x, '\n') # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] print('+---------------------+') # YOUR CODE HERE x = x + y print(x, '\n') # Change x so that it is [1, 2, 3, 4, 9, 10] """ remove() is an inbuilt function in Python that removes a given object from the list. e.g., x.remove(8) removes the number eight. """ print('+---------------------+') # YOUR CODE HERE x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] """ the insert() is a method wich inserts an item at a given position. e.g., x.insert(8, 99) inserts the number 99 in position five. """ print('+---------------------+') # YOUR CODE HERE x.insert(5, 99) print(x, '\n') # Print the length of list x """ The len() method is used to find the length of the list in Python. """ print('+---------------------+') # YOUR CODE HERE print('Length of x:', len(x), '\n') # Print all the values in x multiplied by 1000 print('+---------------------+') # YOUR CODE HERE print([i*1000 for i in x], '\n')
true
4434a19beacb958cc771d0eef27b0a524dea289c
taitujing123/my_leetcode
/145_addTwoNumbers.py
2,061
4.40625
4
""" 给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。   你可以假设除了数字 0 之外,这两个数字都不会以零开头。 进阶: 如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。 示例: 输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 输出: 7 -> 8 -> 0 -> 7 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-two-numbers-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 is None: return l2 if l2 is None: return l1 num1 = [] num2 = [] while l1 is not None: num1.append(l1.val) l1 = l1.next while l2 is not None: num2.append(l2.val) l2 = l2.next res = [] curry = 0 while len(num1) > 0 and len(num2) > 0: temp = num1.pop() + num2.pop() + curry res.append(temp % 10) curry = temp // 10 while len(num1) > 0: temp = num1.pop() + curry res.append(temp % 10) curry = temp // 10 while len(num2) > 0: temp = num2.pop() + curry res.append(temp % 10) curry = temp // 10 if curry > 0: res.append(curry) dummy = curr = ListNode(-1) while len(res) > 0: curr.next = ListNode(res.pop()) curr = curr.next return dummy.next
false
b9fd1eac68f1037b0b880ad137d1cc40ec3789c3
jwalakc/sdet
/Python Scripts/activity10.py
287
4.15625
4
list = input("Enter numbers separated by coma: ").split(",") print("tuple of given numbers: ", tuple(list)) list1 = [] for number in list: if int(number) % 5 == 0: list1.append(number) tuple = tuple(list1) print("tuple of numbers that are divisible by 5: ", tuple)
true