blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
101f7b9e37b22819c534e66c6319e363a4cfa99f
Ahmodiyy/Learn-python
/pythonpractice.py
1,142
4.21875
4
# list comprehension number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10] oddNumber_list = [odd for odd in number_list if odd % 2 == 1] print(oddNumber_list) number_list = [1, 2, 3, 5, 6, 7, 8, 9, 10] oddNumber_list = [odd if odd % 2 == 1 else None for odd in number_list] print(oddNumber_list) # generator as use to get Iterator object 'stream of data' def generate_to_any_number(x=10): i = 0 while i < x: yield i i += 1 print("generate to any number: ", generate_to_any_number()) for g in generate_to_any_number(): print("generator object: ", g) # handling error try: tenth = int(input("enter num")) except ValueError: print("enter an integer") # reading from a file txt_file = None try: txt_file = open('C:/New folder/txtfile.txt', 'r') numbers_in_txtfile = txt_file.read() print("numbers in txtfile: ", numbers_in_txtfile) except: print("unable to open file") finally: txt_file.close() # using python with as to autoclose object with open('C:/New folder/txtfile.txt', 'r') as txt_file2: numbers_in_txtfile2 = txt_file2.read() print("numbers_in_txtfile2: ", numbers_in_txtfile2)
true
2c3370cfb32e84cc709f9fbeaa99e961aa0a8ce0
Asresha42/Bootcamp_day25
/day25.py
2,902
4.28125
4
# Write a program to Python find the values which is not divisible 3 but is should be a multiple of 7. Make sure to use only higher order function. def division(m): return True if m % 3!= 0 and m%7==0 else False print(division(23)) print(division(35)) # Write a program in Python to multiple the element of list by itself using a traditional function and pass the function to map to complete the operation. def b(c): return c * c a=[89,90,5,7,333,45,6,11,22,456] print(list(map(b,a))) # Write a program to Python find out the character in a string which is uppercase using list comprehension. a="AsrESha KaR" b=[c for c in a if c.isupper()] print(b) # Write a program to construct a dictionary from the two lists containing the names of students and their corresponding subjects. The dictionary should maps the students with their respective subjects. Let’s see how to do this using for loops and dictionary comprehension. HINT-Use Zip function also # ● Student = [&#39;Smit&#39;, &#39;Jaya&#39;, &#39;Rayyan&#39;] # ● capital = [&#39;CSE&#39;, &#39;Networking&#39;, &#39;Operating System&#39;] students = ["Smit", "Jaya", "Rayyan"] capital = ["CSE","Networking", "Operating System"] print ("Students : " + str(students)) print ("Capital : " + str(capital)) a = dict(zip(students, capital)) print ("Information : " + str(a)) # Learn More about Yield, next and Generators # Write a program in Python using generators to reverse the string. Input String = “Consultadd Training” def a(b): for i in range (len(b) - 1, -1, -1): yield b[i] for i in a('Consultadd Training'): print(i ,end="") # Write any example on decorators. def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @make_italic @make_underline def hello(): return "hello world" print(hello()) # Write a program to handle an error if the user entered the number more than four digits it should return “Please length is too short/long !!! Please provide only four digits while True: a = input("Enter the numbers: ") if len(a)==4: print(a) break else: print("Please length is too short/long !!! Please provide only four digits") # Create a login page backend to ask user to enter the UserEmail and password. Make sure to ask Re-Type Password and if the password is incorrect give chance to enter it again but it should not be more than 3 times. i = 0 while (i<3): a = str(input("Enter Email Id: ")) b = str(input("Enter password: ")) if a=="asha5@gmail.com" and b =="asha": print("Welcome!") break else: print("Retry wrong values") i+=1
true
d0f1e4c5434d246faf1d73097a00a8b87af298b4
anjmehta8/learning_python
/Lecture 1.py
1,113
4.375
4
print(4+3+5) #this is a comment """ hello this is a multiline comment """ #values #data types #date type of x is value. #Eg. 4 is integer. The 4 is value, integer is data type """ #integer 4 7 9 15 100 35 0 -3 #float 3.0 4.6 33.9 17.80 43.2 """ print(6/3) print(6//3) print(7/2) print(7//2) #// rounds downward #/ exact number print(9/2) print(9//2) print(5**3) #** is exponent print(9 % 3) print(11 % 3) print(10 % 3) print(14 % 3) #modulo % is the remainder, how much would be left over #comparison operators, boolean operators T or F #True #False print(4 < 7) print(4 > 7) print(True) print(4 == 7) #if two things are identical print(4 != 7) #not equal print(4 >= 7) #greater than or equal to #and print(4 < 7 and 6 < 7) print(4 < 7 and 9 < 7) print(11 < 7 and 9 < 7) print(11 < 7 and 6 < 7) print(True and False) print(True and True) print(False and False) #or, inclusive print(4 < 7 or 6 < 7) print(4 < 7 or 9 < 7) print(11 < 7 or 9 < 7) print(11 < 7 or 6 < 7) print(True or False) print(True or True) print(False or False) #not print(not(4 < 7)) print(not(9 < 7))
true
278942c8419ff38e9fe29adfb040ab2607afa0f7
geekmj/fml
/python-programming/panda/accessing_elements_pandas_dataframes.py
2,626
4.21875
4
import pandas as pd items2 = [{'bikes': 20, 'pants': 30, 'watches': 35}, {'watches': 10, 'glasses': 50, 'bikes':15,'pants': 5 } ] store_items = pd.DataFrame(items2, index = ['Store 1', 'Store 2']) print(store_items) ## We can access rows, columns, or individual elements of the DataFrame # by using the row and column labels. print() print('How many bikes are in each store:\n', store_items[['bikes']]) print() print('How many bikes and pants are in each store:\n', store_items[['bikes','pants']]) ## Check [[]], while [] worked for one index but not for 2 print() print('How items are in in Store 1:\n', store_items.loc[['Store 1']]) print() ## Notice for accessing row u have to use loc print('How many bikes are in Store 2:\n', store_items['bikes']['Store 2']) ## Notice Column first than row ## For modification we can use dataframe[column][row] ## Adding a column named shirts, provide info shirts in stock at each store store_items['shirts'] = [15,2] print(store_items) ## It is possible to add a column having values which are outcome # of arithmatic operation between other column # New Suits column with values addition of number of shirts and pants store_items['suits'] = store_items['shirts'] + store_items['pants'] print(store_items) ## To add rows to our DataFrame we first have to create a new Dataframe # and than append # New dictionary new_items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4}] # New dataframe new_store = pd.DataFrame(new_items, index = ['Store 3']) print(new_store) # Use append and add it to existing dataframe store_items = store_items.append(new_store) print(store_items) # Notice Alphabetical order in which they appended # we add a new column using data from particular rows in the watches column store_items['new watches'] = store_items['watches'][1:] print(store_items) # Insert a new column with label shoes right before the # column with numerical index 4 store_items.insert(4, 'shoes', [8,5,0]) print(store_items) ## .pop() delete column and .drop() to delete row store_items1 = store_items.pop('new watches') print(store_items1) # Remove the store 2 and store 1 rows store_items2 = store_items.drop(['Store 2', 'Store 1'], axis = 0) print(store_items2) # Change row and column label store_items = store_items.rename(columns = {'bikes': 'hats'}) print(store_items) store_items = store_items.rename(index = {'Store 3': 'Last Store'}) print(store_items) # We change the row index to be the data in the pants column store_items = store_items.set_index('pants') # we display the modified DataFrame print(store_items)
true
900ff84b08de1fb33a0262702f2e79dd11125470
geekmj/fml
/python-programming/panda/accessing_deleting_elements_series.py
2,231
4.75
5
import pandas as pd # Creating a Panda Series that stores a grocerry list groceries = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['eggs', 'apples', 'milk', 'bread']) print(groceries) # We access elements in Groceries using index labels: # We use a single index label print('How many eggs do we need to buy:', groceries['eggs']) print() # we can access multiple index labels print('Do we need milk and bread:\n', groceries[['milk', 'bread']]) print() # we use loc to access multiple index labels print('How many eggs and apples do we need to buy:\n', groceries.loc[['eggs', 'apples']]) print() # We access elements in Groceries using numerical indices: # we use multiple numerical indices print('How many eggs and apples do we need to buy:\n', groceries[[0, 1]]) print() # We use a negative numerical index print('Do we need bread:\n', groceries[[-1]]) print() # We use a single numerical index print('How many eggs do we need to buy:', groceries[0]) print() # we use iloc to access multiple numerical indices print('Do we need milk and bread:\n', groceries.iloc[[2, 3]]) # We display the original grocery list print('Original Grocery List:\n', groceries) ## Changing values # We change the number of eggs to 2 groceries['eggs'] = 2 # We display the changed grocery list print() print('Modified Grocery List:\n', groceries) ## Deleting items # We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list. The drop function removes elements out of place print() print('We remove apples (out of place):\n', groceries.drop('apples')) # When we remove elements out of place the original Series remains intact. To see this # we display our grocery list again print() print('Grocery List after removing apples out of place:\n', groceries) # We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list in place by setting the inplace keyword to True groceries.drop('apples', inplace = True) # When we remove elements in place the original Series its modified. To see this # we display our grocery list again print() print('Grocery List after removing apples in place:\n', groceries)
true
dc0168556ef464beab6eb6371d24d7a726a08df0
ads2100/pythonProject
/72.mysql3.py
1,748
4.15625
4
# 71 . Python MySql p2 """ # The ORDER BY statement to sort the result in ascending or descending order. # The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword # Delete: delete records from an existing table by using the "DELETE FROM" statement # Important!: Notice the statement: mydb.commit() It is required to make the changes otherwise no changes are made to the table # Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record(s) that should be deleted. If you omit the WHERE clause, all records will be deleted! # delete an existing table by using the "DROP TABLE" statement. # If the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error. """ import mysql.connector con = mysql.connector.connect( host = "localhost", user = "root", password= "omarroot000", database= "pythondb" ) mycursor = con.cursor() q = "SELECT * FROM categories ORDER BY name DESC" mycursor.execute(q) result = mycursor.fetchall() for x in result: print(x) q = "DELETE FROM categories WHERE name = 'Javascript'" mycursor.execute(q) con.commit() print(mycursor.rowcount,"record(s) deleted") mycursor.execute("SELECT * FROM categories ORDER BY name DESC") result = mycursor.fetchall() for x in result: print(x) #mycursor.execute("CREATE TABLE categories_tt(name VARCHAR(255), description VARCHAR(255))") mycursor.execute("SHOW TABLES") print("Tables:") for tbl in mycursor: print(tbl) mycursor.execute("DROP TABLE categories_tt") mycursor.execute("SHOW TABLES") print("Tables:") for tbl in mycursor: print(tbl)
true
e3476d68e724f57e66131177f595e38d0ec492fe
ads2100/pythonProject
/15.list.py
658
4.34375
4
# 15. List In python 3 """ # List Methods len() the length of items append() add item to the list insert() add item in specific position remove() remove specified item pop() remove specified index, remove last item if index is not specified clear() remove all items """ print("Lesson 15: List Method") list = ["apple", "banana", "cherry"] list.append("orange") list.append("blueberry") print(list) list.insert(0, "kiwi") print(list) list.remove("banana") print(list) list.pop() print(list) list.pop(3) print(len(list)) print(list) mylist = list.copy(); list.pop(2) print(mylist) print(list) list2 = [1,2] list.clear() print(list)
true
61a30c2c64aa88706a32b898c7fca786775c8ae1
ads2100/pythonProject
/59.regularexpression3.py
994
4.4375
4
# 59. Regular Expressions In Python p3 """ # The sub() function replaces the matches with the text of your choice: # You can control the number of replacements by specifying the count parameter. sub('','',string,no) # Match Object: A Match Object is as object containing information about the search and the result. The Match object has properties and methods used to retrieve information about the search, and the result. Ex: <re.Match object; span=(2, 4), match='is'> span() returns a tuple containing the start-, and end positions of the match. string returns the string passed into the function group() returns the part of the string where there was a match """ import re as myRegEx str = "This Is His Issue" match = myRegEx.sub('\s', '_', str, 2) if (match): print('\nmatch') print(myRegEx.search('is',str)) print(myRegEx.search(r"\bH+",str).span()) print(myRegEx.search(r"\bH",str).string) print(myRegEx.search(r"\bH\w+",str).group())
true
4c36b5214ebd5c63b66233c33a2c3bc59701e770
ads2100/pythonProject
/16.tuple.py
655
4.1875
4
# 16. Tuple in Python """ # A tuple is a collection which is ordered and unchangeable. # In Python tuples are written with round brackets (). # if the tuple has just one item... ("item",) # acces item in tuple with referring [index] # You cannot change its values. Tuples are unchangeable. # You cannot add items to it. # You cannot remove items in a tuple, but you can delete the tuple completely using del(). # You can loop through the tuple items by using a for loop. """ mixtuple = (1, "yellow", 0.1, "green") print(mixtuple[1:3]) for item in mixtuple: print(item) del mixtuple print(mixtuple) # An error because it's no longer exist
true
4054eb15aa4e1c1a406a7766e5874288d321232b
tianyunzqs/LeetCodePractise
/leetcode_61_80/69_mySqrt.py
956
4.15625
4
# -*- coding: utf-8 -*- # @Time : 2019/7/3 9:44 # @Author : tianyunzqs # @Description : """ 69. Sqrt(x) Easy Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. """ def mySqrt(x: int) -> int: def fun(x, d_min, d_max): if d_max == d_min or (d_max - d_min == 1 and d_min * d_min <= x < d_max * d_max): return d_min mid = (d_min + d_max) // 2 if x < mid * mid: res = fun(x, d_min, mid) else: res = fun(x, mid, d_max) return res return fun(x, 1, x) print(mySqrt(2000000000000))
true
7eed19d8675227c947b74aa3143c0745126f08b8
tianyunzqs/LeetCodePractise
/leetcode_61_80/74_searchMatrix.py
2,010
4.375
4
# -*- coding: utf-8 -*- # @Time : 2019/7/9 10:43 # @Author : tianyunzqs # @Description : """ 74. Search a 2D Matrix Medium Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true Example 2: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false """ def searchMatrix(matrix, target: int) -> bool: """ 首先确定目标值可能所在的行,判断条件是:大于等于改行第一个元素,并且小于等于改行最后一个元素 确定行后,在该行定义从前往后和从后往前的两个指针,直至两个指针相遇,如果找到返回True,否则返回False :param matrix: :param target: :return: """ if not matrix or not matrix[0]: return False m, n = len(matrix), len(matrix[0]) candidate_row = -1 for i in range(m): if matrix[i][0] <= target <= matrix[i][-1]: candidate_row = i break if candidate_row == -1: return False left, right = 0, n-1 while left <= right: if matrix[candidate_row][left] == target or matrix[candidate_row][right] == target: return True elif matrix[candidate_row][left] < target: left += 1 elif matrix[candidate_row][right] > target: right -= 1 return False if __name__ == '__main__': matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 matrix = [ [1], [3] ] target = 3 print(searchMatrix(matrix, target))
false
f87328e58228e7fd3e3d16ffd999638ff38cf8f9
AlanRufuss007/Iceberg
/python day1.py
319
4.125
4
num1 = 10 num2 = 20 sum = num1+num2 print("sum of {0} and {1} is {2}".format(num1,num2,sum)) num1 = input("Enter the number:") num2 = input("/n Enetr the number:") sum = float(num1)+float(num2) print("The sum of {0} and {1} is {2}".format(num1,num2,sum)) a = 10 b = 20 maximum = max(a,b) print(maximum)
true
f7c446009fd894559fb63c4a6b928ad6fc4a61e1
eddy-v/flotsam-and-jetsam
/checkaba.py
1,114
4.21875
4
# eddy@eddyvasile.us # how to check validity of bank routing number (aba) # multiply the first 8 digits with the sequence 3, 7, 1, 3, 7, 1, 3, 7 and add the results # the largest multiple of 10 of the sum calculated above must be equal to the 9th digit (checkDigit) import math def validateABA(aba): checkDigit=int(aba[8]) digitSum= \ int(aba[0])*3+ \ int(aba[1])*7+ \ int(aba[2])+ \ int(aba[3])*3+ \ int(aba[4])*7+ \ int(aba[5])+ \ int(aba[6])*3+ \ int(aba[7])*7 if digitSum==0: digitSum=10 #For a more elegant soution use lists or arrays #Find the highest multiple of 10 of the digitSum temp = (math.floor(digitSum/10)*10)+10; validDigit=temp-digitSum; if validDigit==checkDigit: return True else: return False aba=input("Enter the 9 didigit bank routing nuber (e.g. 121000248): ") if aba.isalpha() or len(aba) != 9: print ('Sorry... 9 digit numeric input required\n') else: if (validateABA(aba)): print(aba,' is a valid bank routing number\n') else: print(aba,' is NOT a valid routing number\n')
true
acf9b029ab99b1b978b2e6a41fc2c7feb9cb4f36
gdiman/flask
/sql/sqljoin.py
710
4.15625
4
import sqlite3 with sqlite3.connect("new.db") as connection: c = connection.cursor() try: c.execute("""CREATE TABLE regions (city TEXT, region TEXT)""") except: print("Exists!") cities = [ ('San Franciso', 'Far West'), ('New York City', 'Northeast'), ('Chicago', 'Northcentral'), ('Phoenix', 'Southwest'), ('Boston', 'Central'), () ] # c.executemany("INSERT INTO regions VALUES(?,?)", cities) #c.execute("SELECT * FROM regions ORDER BY region ASC") c.execute("""SELECT population.population, population.city, regions.region FROM population, regions WHERE population.city = regions.city""") rows = c.fetchall() for r in rows: print(r[0], r[1]) connection.commit() connection.close()
false
084af05776f7ae422b74a67e08f68046b7acbd8c
AhirraoShubham/ML-with-Python
/variables.py
1,771
4.65625
5
########################################################################## # Variabels in Python # # * Variables are used to store information to be referenced and # manipulated in computer program. They also provide a way of labeling # data with a decriptive name, so our progams can be understood more # clearly by the reader and ourselves. # * It is helpful to think of variables as containers that hold information # * Their sole purpose is to label and store data in memory. This data can # can then be used throughout our program # * As Python is Dynamically typed language there is no need to use # data types explicitly while creating the variable. # * Depends on the value that we initialise interpreter decides its data # type and allocates memory accordingly. # ############################################################################ # Consider below application which demonstrate different ways in which we # can create variabels. print("--- (-: Learn Python with Mr.Ahirrao :-) ---") print("Demonstration of variable in Python") no = 11 # Considered as Integer name = "Mr.Ahirrao" # Considered as String fValue = 3.14 # Considered as Float cValue = 10+5j # Considered as Complex number eValue = 7E4 # Considered as Scintific number where E indicates power of 10 bigValue = 123456789 print(no) print("String is "+name) print(fValue) print(cValue) print(eValue) print(bigValue) #We can use type function to get data type of variable print("--- Get DataType of any variable using type funcation ---") print(type(no)) print(type(name)) print(type(fValue)) print(type(cValue)) print(type(eValue)) print(type(bigValue)) #Save and run file for output
true
cf6db1cfb7ba5ebff8bf62f9d55eb93071f03e5f
noserider/school_files
/speed2.py
539
4.125
4
#speed program speed = int(input("Enter speed: ")) #if is always the first statement if speed >= 100: print ("You are driving dangerously and will be banned") elif speed >= 90: print ("way too fast: £250 fine + 6 Points") elif speed >= 80: print ("too fast: £125 + 3 Points") elif speed >= 70: print ("Please adhere to the speed limits") elif speed >= 60: print ("Perfect") elif speed <= 30: print ("You are driving too slow") #else is always the last statement else: print ("No action needed")
true
8dcdef576c7fb51962fc4c2537742c92f51976f5
noserider/school_files
/sleep.py
580
4.125
4
#int = interger #we have two variable defined hourspernight & hoursperweek hourspernight = input("How many hours per night do you sleep? ") hoursperweek = int(hourspernight) * 7 print ("You sleep",hoursperweek,"hours per week") #round gives a whole number answer or a specific number of decimal points hourspermonth = float(hoursperweek) * 4.35 hourspermonth = round(hourspermonth,2) print ("You sleep",hourspermonth,"hours per month") hoursperyear = float(hourspermonth) * 12 hoursperyear = round(hoursperyear,2) print ("You sleep",hoursperyear,"hours per year")
true
a3b6246985aa7ea86a440da73a96cefdd4eb6dc3
noserider/school_files
/sleep1.py
291
4.1875
4
hourspernight = input("How many hours per night do you sleep? ") hoursperweek = int(hourspernight) * 7 print ("You sleep",hoursperweek,"hours per week") hourspermonth = float(hoursperweek) * 4.35 hourspermonth = round(hourspermonth) print ("You sleep",hourspermonth,"hours per month")
true
99d347780e81ca24c4537231f538cec5cbef1175
Arcus71/GC50-files
/UserInput.py
224
4.15625
4
#Set up two numbers a = int(input("Enter your first number: ")) b = int(input("Enter your second number: ")) #Output manipulations print("Sum: " + str(a + b)) print("Product: " + str(a * b)) print("Quotient: " + str(a / b))
false
1fb48b796d55cd2988bfb74060178f327b6b549e
helectron/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
282
4.28125
4
#!/usr/bin/python3 '''module 2-append_write Function: append_write(filename="", text="") ''' def append_write(filename="", text=""): '''Function to append a text in a file''' with open(filename, mode="a", encoding="utf-8") as myFile: return myFile.write(text)
true
e85febfe1079f48fac3e990073f76067e4902b6f
alexangupe/clasesCiclo1
/P45/Clase8/requerimientoFor.py
1,852
4.1875
4
#Requerimiento: escribir una función que valide que un correo electrónico #ingresado, solamente tenga una arroba, mostrar en pantalla la posición de las #arrobas que estén sobrando #Objetivo -> Número válido de arrobas den un correo (única arroba) # #Algoritmo (Pseudocódigo) # 1) Ingresa el correo electrónico # 2) Inicializamos contador de arrobas # 3) Recorremos todos los caracteres que constituyen el correo # 3a) Si encontramos una arroba incrementamos el contador de arrobas # 4) Revisar el número de arrobas y reportar si el correo es válido en este contexto. #Traducción -> Python email = input('Ingresar correo electrónico: ') contadorArrobas = 0 # if email[0] == '@': # contadorArrobas += 1 # if email[1] == '@': # contadorArrobas += 1 # if email[2] == '@': # contadorArrobas += 1 # . # . # . #Forma utilizando subíndice # for i in range(len(email)): # if email[i] == '@': # contadorArrobas += 1 # if contadorArrobas > 1: # print("Hay una arroba sobrante en la posición,",i) # #Forma cargando en una variable cada elemento # contadorPosicion = 0 # for caracter in email: # if caracter == '@': # contadorArrobas += 1 # if contadorArrobas > 1: # print("Hay una arroba sobrante en la posición,",contadorPosicion) # contadorPosicion += 1 #Forma combinando las anteriores for i,caracter in enumerate(email): if caracter == '@': contadorArrobas += 1 if contadorArrobas > 1: print("Hay una arroba sobrante en la posición,",i) if contadorArrobas == 1: print("El correo tiene el número correcto de arrobas") elif contadorArrobas == 0: print("El correo no tiene diferenciado el dominio: 0 arrobas encontradas") elif contadorArrobas > 0: print(f"El correo tiene {contadorArrobas-1} de sobra")
false
89f6aaf3951880cbacbf717942940359860c5cc7
bdsh-14/Leetcode
/max_sum_subarray.py
615
4.21875
4
''' Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’ Input: [2, 1, 5, 1, 3, 2], k=3 Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3] educative.io ''' def max_sum(k, nums): windowStart = 0 windowSum = 0 max_sum = 0 for windowEnd in range(len(nums)): windowSum += nums[windowEnd] if windowEnd >= k-1: max_sum = max(max_sum, windowSum) windowSum -= nums[windowStart] windowStart += 1 return max_sum a = max_sum(3, [2, 1, 5, 1, 3, 2]) print(a)
true
24cbb5b9b020dfa0c9547a74b4ec2f77a26a027d
bdsh-14/Leetcode
/Queue_Intro.gyp
1,170
4.15625
4
#Linear queue class Queue: def __init__(self): self.queueList = [] def is_empty(self): return len(self.queueList) == 0 def front(self): if self.is_empty(): return None return self.queueList[0] def back(self): if self.is_empty(): return None return self.queueList[-1] def size(self): return len(self.queueList) def enqueue(self, val): self.queueList.append(val) def dequeue(self): front = self.front() self.queueList.remove(front) return front queue = Queue() print("queue.enqueue(2);") queue.enqueue(2) print("queue.enqueue(4);") queue.enqueue(4) print("queue.enqueue(6);") queue.enqueue(6) print("queue.enqueue(8);") queue.enqueue(8) print("queue.enqueue(10);") queue.enqueue(10) print("Dequeue(): " + str(queue.dequeue())) print("Dequeue(): " + str(queue.dequeue())) print("front(): " + str(queue.front())) print("back(): " + str(queue.back())) queue.enqueue(12) queue.enqueue(14) while queue.is_empty() is False: print("Dequeue(): " + str(queue.dequeue())) print("is_empty(): " + str(queue.is_empty()))
false
4d31e99dd4c78ab8f25bd0de0662b39a1fe7e739
vazquezs123/EULER
/euler19.py
1,613
4.15625
4
#!/usr/bin/env python class Month(object): def __init__(self, month, days): """Return a month object with current month, and total days in month """ self.month = month jan = Month('January', 31) feb = Month('February', 28) mar = Month('March', 31) apr = Month('April', 30) may = Month('May', 31) jun = Month('June', 30) jul = Month('July', 31) aug = Month('August', 31) sep = Month('September', 30) otb = Month('October', 31) nov = Month('November', 30) dec = Month('December', 31) monthList = [] monthList.append(jan) monthList.append(feb) monthList.append(mar) monthList.append(apr) monthList.append(may) monthList.append(jun) monthList.append(jul) monthList.append(aug) monthList.append(sep) monthList.append(otb) monthList.append(nov) monthList.append(dec) # initialize year year = 1901 # initialize day of week list dow = {0:'sunday',1:'monday',2:'tuesday',3:'wednesday',4:'thursday',5:'friday',6:'saturday'} # initialize current dow key dowKey = 2 # initialize to 2 because jan 1, 1901 was a tuesday # first sunday counter sundayCounter = 0 while (year <= 2000): for month in monthList: # check if leap year for range of year daysInYear = 0 if ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)): daysInYear = 366 else: daysInYear = 365 for day in range(1, month.days): if dowKey == 0 and day == 1: sundayCounter = sundayCounter + 1 print "%s, %s, %d, %y" % (dow[dowkey % 6] if dowKey == 6: dowKey = 0 else: dowKey = dowKey + 1 year = year + 1 print "The month is %s and it has %d days" % (jan.month, sundayCounter)
false
a09123591f18b44d4c10b1f134a7c74c7600d15d
M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes
/stages_of_life.py
375
4.28125
4
age = 42 if age < 2: print (str(age) + " years? You're a baby!") elif age <= 3: print (str(age) + " years? You're a toddler!") elif age <= 12: print (str(age) + " years? You're a kid!") elif age <= 19: print (str(age) + " years? You're a teenager!") elif age <=64: print (str(age) + " years? You're an adult!") else: print (str(age) + " years? You're an elder!")
false
0fa2259f7b692512ccfd9fc074ffd8640762853a
racer97/ds-class-intro
/python_basics/class02/exercise_6.py
2,246
4.25
4
''' Edit this file to complete Exercise 6 ''' def calculation(a, b): ''' Write a function calculation() such that it can accept two variables and calculate the addition and subtraction of it. It must return both addition and subtraction in a single return call Expected output: res = calculation(40, 10) print(res) >>> (50, 30) Arguments: a: first number b: second number Returns: sum: sum of two numbers diff: difference of two numbers ''' # code up your solution here summation = a + b diff = a - b return summation, diff def triangle_lambda(): ''' Return a lambda object that takes in a base and height of triangle and computes the area. Arguments: None Returns: lambda_triangle_area: the lambda ''' return lambda base, height: .5 * base * height def sort_words(hyphen_str): ''' Write a Python program that accepts a hyphen-separated sequence of words as input, and prints the words in a hyphen-separated sequence after sorting them alphabetically. Expected output: sort_words('green-red-yellow-black-white') >>> 'black-green-red-white-yellow' Arguments: hyphen_str: input string separated by hyphen Returns: sorted_str: string in a hyphen-separated sequence after sorting them alphabetically ''' # code up your solution here words = hyphen_str.split('-') words.sort() hyphen = '-' sorted_hyphen_str = hyphen.join(words) return sorted_hyphen_str def perfect_number(n): ''' Write a Python function to check whether a number is perfect or not. A perfect number is a positive integer that is equal to the sum of its proper positive divisors. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Example: 6 is a perfect number as 1+2+3=6. Also by the second definition, (1+2+3+6)/2=6. Next perfect number is 28=1+2+4+7+14. Next two perfect numbers are 496 and 8128. Argument: number: number to check Returns: perfect: boolean, True if number is perfect ''' # code up your answer here if n < 1: return 'Invalid Number' if n == 1: return True list2 = [1] for i in range(2, n // 2 + 1): if n % i == 0: list2.append(i) return n == sum(list2) if __name__ == '__main__': pass
true
30132cd72458b94cd244412d9dcdc108a5674c6f
yatikaarora/turtle_coding
/drawing.py
282
4.28125
4
#to draw an octagon and a nested loop within. import turtle turtle= turtle.Turtle() sides = 8 for steps in range(sides): turtle.forward(100) turtle.right(360/sides) for moresteps in range(sides): turtle.forward(50) turtle.right(360/sides)
true
f0962e44eee61bfcb7524c68c346c7fb620269ec
EllipticBike38/PyAccademyMazzini21
/es_ffi_01.py
1,128
4.34375
4
# Write a function insert_dash(num) / insertDash(num) / InsertDash(int num) that will insert dashes ('-') between each two odd numbers # in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number. # Note that the number will always be non-negative (>= 0). def insertDash(num): sNum = str(num) ans = '' for c in range(len(sNum)-1): ans += sNum[c] if int(sNum[c]) % 2 == 1 and int(sNum[c+1]) % 2 == 1: ans += '-' if int(sNum[c]) % 2 == 0 and int(sNum[c+1]) % 2 == 0: ans += '+' ans += sNum[-1] return ans def insertDash2(num): sNum = str(num) ans = '' for c in range(len(sNum)-1): ans += sNum[c] cond1, cond2 = int(sNum[c]) % 2, int(sNum[c+1]) % 2 if cond1 and cond2: ans += '-' if not(cond1 or cond2): ans += '+' ans += sNum[-1] return ans while 1: try: a = int(input('inserire un intero lungo\n')) break except: print('Vorrei un intero') print(insertDash(a))
true
ba6e0574e900be6eed7368ef339d1c1407ea1450
noahmarble/Ch.05_Looping
/5.0_Take_Home_Test.py
2,949
4.28125
4
''' HONOR CODE: I solemnly promise that while taking this test I will only use PyCharm or the Internet, but I will definitely not ask another person except the instructor. Signed: ______________________ 1. Make the following program work. ''' print("This program takes three numbers and returns the sum.") total = 0 for i in range(3): x = int(input("Enter a number: ")) total += x print("The total is:", total) ''' 2. Write a Python program that will use a FOR loop to print the even numbers from 2 to 100, inclusive. ''' for i in range(2,101,2): print(i) ''' 3. Write a program that will use a WHILE loop to count from 10 down to, and including, 0. Then print the words Blast off! Remember, use a WHILE loop, don't use a FOR loop. ''' i = 10 while i > -1: print (i) i-=1 print("Blast Off!") ''' 4. Write a program that prints a random integer from 1 to 10 (inclusive). ''' import random number = random.randrange(1,11) print(number) ''' 5. Write a Python program that will: * Ask the user for seven numbers * Print the total sum of the numbers * Print the count of the positive entries, the number entries equal to zero, and the number of negative entries. Use an if, elif, else chain, not just three if statements. ''' ''' number1 = int(input("give me a number:")) number2 = int(input("give me a number:")) number3 = int(input("give me a number:")) number4 = int(input("give me a number:")) number5 = int(input("give me a number:")) number6 = int(input("give me a number:")) number7 = int(input("give me a number:")) sumofnumbers = number1+number2+number3+number4+number5+number6+number7 print("sum of numbers", sumofnumbers) positive = 0 zero = 0 negative = 0 if number1 >= 1: positive += 1 elif number1 == 0: zero += 1 else: negative += 1 if number2 >= 1: positive += 1 elif number2 == 0: zero += 1 else: negative += 1 if number3 >= 1: positive += 1 elif number3 == 0: zero += 1 else: negative += 1 if number4 >= 1: positive += 1 elif number4 == 0: zero += 1 else: negative += 1 if number5 >= 1: positive += 1 elif number5 == 0: zero += 1 else: negative += 1 if number6 >= 1: positive += 1 elif number6 == 0: zero += 1 else: negative += 1 if number7 >= 1: positive += 1 elif number7 == 0: zero += 1 else: negative += 1 print("number of positive:", positive) print("number of zeros:", zero) print("number f negatives:", negative) ''' positive = 0 zero = 0 negative = 0 sumofnumbers = 0 for i in range (7): number1 = int(input("give me a number:")) if number1 >= 1: positive += 1 elif number1 == 0: zero += 1 else: negative += 1 i+=1 sumofnumbers += number1 print("sum of numbers", sumofnumbers) print("number of positive:", positive) print("number of zeros:", zero) print("number of negatives:", negative)
true
c83665d8eb9bcff974737e4705bb285b8b3384cf
FFFgrid/some-programs
/单向链表/队列的实现.py
1,528
4.125
4
class _node: __slots__ = '_element','_next'#用__slots__可以提升内存应用效率 def __init__(self,element,next): self._element = element #该node处的值 self._next = next #下一个node的引用 class LinkedQueue: """First In First Out""" def __init__(self): """create an empty queue""" self._head = None self._tail = None self._size = 0 def __len__(self): """Return the number of thr elements in the stack""" return self._size def is_empty(self): """Return True if the stack is empty""" return self._size == 0 def first(self): """Return(don't remove the element at the front of the queue )""" if self.is_empty(): print('Queue is empty') else: return self._head._element def dequeue(self): """Remove and return the first element of the queue""" if self.is_empty(): print('Queue is empty') ans = self._head._element self._head = self._head._next self._size -= 1 if self.is_empty(): self._tail = None return ans def enqueue(self,e): """Add an element to the back of the queue""" newest = self._Node(e,None) #this node will be the tail node if self.is_empty(): self._head = newest else: self._tail._next = newest self._tail = newest #Update reference to tail node self._size += 1
true
3081b981b3c1cc909ea8a84005bb3a47150af8db
Kelsi-Wolter/practice_and_play
/interview_cake/superbalanced.py
2,487
4.1875
4
# write a function to see if a tree is superbalanced(if the depths of any 2 leaf nodes # is <= 1) class BinaryTreeNode(object): '''sample tree class from interview cake''' def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right def is_superbalanced(self): '''Check if there are any leafs with difference > 1''' # find two leafs with difference > 1 # traverse tree to find leafs # do BFS to find depths of leafs (queue) - NOPE # do DFS to find leafs quickest, then use short-circuit to quit program # once a difference of greater than 1 is found nodes_to_check = [root] depth = 1 min_leaf_depth = 0 max_leaf_depth = 0 while nodes_to_check: current = nodes_to_check.pop() current_node = current[0] if current_node.left or current_node.right != None: nodes_to_check.append((current.left, depth), (current.right, depth)) depth += 1 else: node_depth = current[1] if min == 0: set min else: if node_depth < min: if min - node_depth > 1 or max - node_depth > 1: return False else: min = depth else depth > max: if max - min > 1: return False else: max = depth # Pseudocode guide # check for children, # if children --> go to those children and continue, depth = 2 # if children (self.left & self.right) == None --> # depth = current depth # and see if it is greater than or less than min/max # update as appropriate # continue until all nodes have been checked # edge cases: # tree of one node # super balanced tree # super unbalanced tree
true
d7955a29d3177efa8b6f558a9a26bd3a7c5f2c61
mulualem04/ISD-practical-4
/ISD practical4Q8.py
282
4.15625
4
# ask the user to input their name and # asign it with variable name name=input("your name is: ") # ask the user to input their age and # asign it with variable age age=int(input("your age is: ")) age+=1 # age= age + 1 print("Hello",name,"next year you will be",age,"years old")
true
9c3a98dc0117de376277591b5ac77807d2b2cf86
vmgabriel/async-python
/src/async_func.py
1,031
4.125
4
"""Async function""" # Libraries from time import sleep async def hello_world(): """Print hello world""" sleep(3) return 'Hello World' class ACalculator: """Class Async Calculator""" async def sum(self, a, b): """function sum a + b""" sleep(2) return a + b async def rest(self, a, b): """function rest a - b""" sleep(2) return a - b async def mult(self, a, b): """function mult a * b""" sleep(2) return a * b async def div(self, a, b): """function div a / b""" sleep(2) if b == 0: return 0 return a / b async def operation(self, val1, val2, op): """function operation""" sleep(2) if op == '+': return await self.sum(val1, val2) if op == '-': return await self.rest(val1, val2) if op == '*': return await self.mult(val1, val2) if op == '/': return await self.div(val1, val2)
false
25405511319bff04521132f09d027eb1bedc6e7a
MahidharMannuru5/DSA-with-python
/dictionaryfunctions.py
1,826
4.5625
5
1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values. 2. items() :- This method is used to return the list with all dictionary keys with values. # Python code to demonstrate working of # str() and items() # Initializing dictionary dic = { 'Name' : 'Nandini', 'Age' : 19 } # using str() to display dic as string print ("The constituents of dictionary as string are : ") print (str(dic)) # using str() to display dic as list print ("The constituents of dictionary as list are : ") print (dic.items()) 3. len() :- It returns the count of key entities of the dictionary elements. 4. type() :- This function returns the data type of the argument # Python code to demonstrate working of # len() and type() # Initializing dictionary dic = { 'Name' : 'Nandini', 'Age' : 19, 'ID' : 2541997 } # Initializing list li = [ 1, 3, 5, 6 ] # using len() to display dic size print ("The size of dic is : ",end="") print (len(dic)) # using type() to display data type print ("The data type of dic is : ",end="") print (type(dic)) # using type() to display data type print ("The data type of li is : ",end="") print (type(li)) 5. copy() :- This function creates the shallow copy of the dictionary into other dictionary. 6. clear() :- This function is used to clear the dictionary contents. # Python code to demonstrate working of # clear() and copy() # Initializing dictionary dic1 = { 'Name' : 'Nandini', 'Age' : 19 } # Initializing dictionary dic3 = {} # using copy() to make shallow copy of dictionary dic3 = dic1.copy() # printing new dictionary print ("The new copied dictionary is : ") print (dic3.items()) # clearing the dictionary dic1.clear() # printing cleared dictionary print ("The contents of deleted dictionary is : ",end="") print (dic1.items())
true
0bfff01de4d4b739f08c6d5499734d9039df55fc
octavian-stoch/Practice-Repository
/Daily Problems/July 21 Google Question [Easy] [Matrix].py
1,618
4.15625
4
#Author: Octavian Stoch #Date: July 21, 2019 #You are given an M by N matrix consisting of booleans that #represents a board. Each True boolean represents a wall. Each False boolean #represents a tile you can walk on. #Given this matrix, a start coordinate, and an end coordinate, #return the minimum number of steps required to reach the end coordinate from the start. #If there is no possible path, then return null. You can move up, left, down, and right. #You cannot move through walls. You cannot wrap around the edges of the board. import random def numSteps(): testMatrix = [['F','F','F','F','F'] , ['F','F','F','F','F'] , ['F','F','F','F','F'] , ['F','F','F','F','F']] def makeMatrix(n, m): #randomly Generate a matrix with values n and m between 1 and 10 #n = column #m = row columnMatrix = [] matrix = [] print (n, m) for makecolumns in range(n): #create columns columnMatrix.append('F') #print(columnMatrix) for makerows in range(m): #create the rows by copying the list and making a bunch of mini lists field = [] #make new lists each time for j in range(n): if random.randrange(1,100) >= 50: field.append('T') else: field.append('F') matrix.append(field) #clear it every time matrix.append(columnMatrix.copy()) print ('\n'.join([' '.join(row) for row in matrix])) #random number between 1 and 100 to change each value in matrix to 'T', if >=50 then 'T' else none if __name__ == "__main__": makeMatrix(random.randrange(1,10), random.randrange(1,10)) #very inneficient because of two for loops O(2n) :(
true
8ed67ae3d95f7ab983bd9b4d2374ac60bf1d44cb
tonycao/CodeSnippets
/python/1064python/test.py
1,882
4.125
4
import string swapstr = "Hello World!" result = "" for c in swapstr: if c.islower(): result += c.upper() elif c.isupper(): result += c.lower() else: result += c print(result) string1 = input("Enter a string: ") string2 = input("Enter a string: ") string1_changed = string1[1:-1] string2_changed = string2[1:-1] string3 = string1_changed + string2_changed print(string3) new_string3 = "" for char in string3: if char.isalpha(): new_string3 = new_string3 + char*3 print(new_string3) # 6) #function of encode: def ROT13(line): """encode the line""" #shift_amount = 13 count = 0 encoded_str = '' for char in line: #count is the index of char, we need find the relationship between char # index number and the shift_amount index,'(count-1)%shift_amount' is # used to get the index of shift_amount count += 1 k = 13 if char.isalpha(): if char.isupper(): char_cal=ord(char)-ord('A') char_upper= chr(int((char_cal+k)%26)+ord('A')) encoded_str = encoded_str + char_upper elif char.islower(): char_cal2=ord(char)-ord('a') char_lower=chr(int((char_cal2+k)%26)+ord('a')) encoded_str = encoded_str + char_lower else: encoded_str = encoded_str + char return encoded_str string = input("Enter message: ") string = string.strip() result = ROT13(string) print(result) str = ROT13(result) print(str) # 7) string1 = input("Enter a long string: ") length = len(string1) ntweet = int((length - 1) / 132) + 1; for i in range(ntweet): print("({0:2d}/{1:2d}) ".format(i+1, ntweet), end="") if (i+1)*132 < length: print(string1[i*132 : (i+1) * 132]) else: print(string1[i*132 : :])
true
d7f42953edff49b748c99be05a79759fa6b994fc
zk18051/ORS-PA-18-Homework02
/task2.py
361
4.125
4
print('Convert Kilometers To Miles') def main(): user_value = input('Enter kilometers:') try: float(user_value) print(float(user_value),'km') except: print(user_value, 'is not a number. Try again.') return main() user_miles = float(user_value) * 0.62137 print(user_value, 'km is', user_miles, 'miles') main()
true
7a15ba5ec8fbfc22d569193c326f5b50aef40f63
manali1312/pythonsnippets
/HR_Func_leapyr.py
336
4.1875
4
def leapYear(): year = int(input("Enter an year:")) if year%4==0 or year%400==0: if year%100==0 and year%400!=0: print("Not a leap year") else: print("It is a leap year") else: print("This is not a leap year") if __name__ == '__main__': leapYear()
false
b49a8155088c794799e763a3d43d12bd5fba57d6
alokjani/project-euler
/e4.py
845
4.3125
4
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. def reverse(num): return int(str(num)[::-1]) def isPalindrome(num): if num == reverse(num): return True return False smallest_3_digit_num = 100 largest_3_digit_num = 999 largest_palindrome = 0 for i in range(smallest_3_digit_num,largest_3_digit_num): for j in range(smallest_3_digit_num, largest_3_digit_num): num = i * j if isPalindrome(num): if num > largest_palindrome: largest_palindrome = num print "%d x %d = %d" % (i,j,largest_palindrome) print "largest palindrome that is a product of two 3 digit numbers is %d" % (largest_palindrome)
true
b0b332d4796c8e4ba777d2c725bd2321f5123b06
Neha-Nayak/Python_basics
/Basics/iteration_sum.py
208
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 9 23:11:45 2021 @author: Neha Nayak """ import fun_sum_of_natural_numbers num=int(input("enter the number=")) print(fun_sum_of_natural_numbers.iteration_sum(num))
false
ee3f43d9120efc1037d5de4aefe93bcd4ea9fcad
DomfeLacre/zyBooksPython_CS200
/module3/AutoServiceInvoice/AutoServiceInvoice1_with_dict.py
2,232
4.25
4
# Output a menu of automotive services and the corresponding cost of each service. print('Davy\'s auto shop services') # Creat dict() to store services : prices servicePrices = { 'Oil change' : 35, 'Tire rotation' : 19, 'Car wash' : 7, 'Car wax' : 12 } print('Oil change -- $35') print('Tire rotation -- $19') print('Car wash -- $7') print('Car wax -- $12') # Prompt the user for two services from the menu. serviceOne = str(input('\nSelect first service: \n')) serviceTwo = str(input('\nSelect second service: \n')) # Check to see if input is a dash (-). If so append 'No service' : 0 to the servicesPrices[] dict() if serviceOne == '-': servicePrices['No service'] = 0 # Set the value of serviceOne to str 'No service' to achieve required assignment output serviceOne = 'No service' else: serviceOne = serviceOne # Check to see if input is a dash (-). If so append 'No service' : 0 to the servicesPrices[] dict() if serviceTwo == '-': servicePrices['No service'] = 0 # Set the value of serviceTwo to str 'No service' to achieve required assignment output serviceTwo = 'No service' else: serviceTwo = serviceTwo # Output an invoice for the services selected. Output the cost for each service and the total cost. print('\n') print('Davy\'s auto shop invoice\n') # Condition to check to see if a dash(-) was entered for serviceOne input if serviceOne == 'No service': print('Service 1: %s' % serviceOne) elif serviceOne in servicePrices: print('Service 1: %s, $%d' % (serviceOne, servicePrices[serviceOne])) else: servicePrices[serviceOne] = 0 print('Service 1: We do not provide the service that you have requested.') # Condition to check to see if a dash(-) was entered for serviceTwo input if serviceTwo == 'No service': print('Service 2: %s' % serviceTwo) elif serviceTwo in servicePrices: print('Service 2: %s, $%d' % (serviceTwo, servicePrices[serviceTwo])) else: servicePrices[serviceTwo] = 0 print('Service 2: We do not provide the service that you have requested.') # Add total using the values from the servicePrices dict() serviceTotal = servicePrices[serviceOne] + servicePrices[serviceTwo] print('\nTotal: $%d' % serviceTotal)
true
0a17bfb11cdda597d527c25d658ee78bf727ad90
DomfeLacre/zyBooksPython_CS200
/module7/MasterPractice_List_Dicts.py
670
4.125
4
##### LISTS ##### # Accessing an Index of a List based on user input of a number: Enter 1 -5 ageList = [117, 115, 99, 88, 122] # Ways to to get INDEX value of a LIST: print(ageList.index(99)) # --> 2 # Use ENUMERATE to get INDEX and VALUE of LIST: for index, value in enumerate(ageList): print(index) print('My index is %d and my index value is %d' % (index, value)) # REMEMBER Lists are 0 Index so if user input wants the value of 1 in the list that is EQUAL to 0: userInput = 2 print('The user wants the number %d value in the list so we need to access the list accordingly: ' % userInput) print('%d is equal to %d' % (userInput, ageList[userInput - 1]))
true
a530473ca06eaf44b8cf4d400510366ddc31be78
JoraKaryan/Repository_600
/Home-01/ex-7.py
447
4.1875
4
#ex-7 bar = "What! is! this book about !this book! is about python coding" def foo(bar:str): for i in range(len(bar)): if 0 <= ord(bar[i]) <= 31 or 33<= ord(bar[i])<=64 or 91 <= ord(bar[i]) <= 96 or 123 <= ord(bar[i]) <= 127: bar= bar.replace(bar[i], "") return bar bar = (foo(bar)) l = bar.split(" ") c = [] for i in range(len(l)): c.append(l.count(l[i])) print(dict(zip(l, c)))
false
3b3c1110fd920f34e35dbc55beb38d9b3ecb16cc
calvinjlzhai/Mini_quiz
/Mini_quiz.py
2,737
4.28125
4
#Setting score count score = 0 #Introducation for user taking the quiz print("Welcome to the quiz! Canadian Edition!\n") #First question with selected answers provided answer1 = input("Q1. What is the capital of Canada?" "\na. Toronto\nb. Ottawa\nc. Montreal\nd.Vancouver\nAnswer: ") # Account for the different input the user enters when request if answer1 == "b" or answer1 == "B" or answer1 == "Ottawa" or answer1 == "ottawa": score += 1 print("You are correct!\n") #Print the output for correct input, this concept repeats for next question else: print("Incorrect, the answer is Ottawa.\n") #Print the output for incorrect input, this concept repeats for next question print("Current Score: "+ str(score) + "\n") #The score is counted after this question and continue until end of page for final score answer2 = input("Q2. Which Canadian province has the highest population?" "\na. Manitoba\nb. British Columbia\nc. Quebec\nd. Ontario\nAnswer: ") if answer2 == "d" or answer2 == "D" or answer2 == "Ontario" or answer2 == "ontario": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Ontario!\n") print("Current Score: "+str(score) + "\n") answer3 = input("Q3. What is the national animal of Canada?" "\na. Moose\nb. Grizzly Bear\nc. Beaver\nd. Beluga Whale\nAnswer: ") if answer3 == "c" or answer3 == "C" or answer3 == "Beaver" or answer3 == "beaver": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Beaver!\n") print(score) answer4 = input("Q4. What is the capital city of Ontario?" "\na. York\nb. Toronto\nc. Hamilton\nd. Peterborough\nAnswer: ") if answer4 == "b" or answer4 == "B" or answer4 == "Toronto" or answer4 == "toronto": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Toronto!\n") print("Current Score: "+ str(score) + "\n") answer5 = input("Q5. What province did not join Canada until 1949?" "\na. Quebec\nb. British Columbia\nc. Newfoundland and Labrador\nd. Saskatchewan\nAnswer: ") if answer5 == "c" or answer5 == "C" or answer5 == "Newfoundland and Labrador" or answer5 == "newfoundland and labrador": score += 1 print("You are correct\n") else: print("Incorrect, the answer is Newfoundland and Labrador!\n") print("Current Score: "+ str(score) + "\n") if score >=5: print("Excellent! " + str(score) + " /5") #Output when user score 4 and above elif score >=3: print("Good job, almost there.." + str(score) + "/5") #Output when user score or equal to 3 else: print("Need to study more! " + str(score) + "/5") #Output when user score 3 and below
true
256990003e5d17856435c73e2faac0e495a2001f
DavidQiuUCSD/CSE-107
/Discussions/Week1/OTP.py
2,104
4.375
4
import random #importing functions from Lib/random """ Author: David Qiu The purpose of this program is to implement Shannon's One-Time Pad (OTP) and to illustrate the correctness of the encryption scheme. OTP is an example of a private-key encryption as the encryption key (K_e) is equal to the decryption key (K_d) and both are kept secret from any adversary. The scheme itself can be described as a tuple of three algorithms: Key Generation, Encryption, and Decryption. The key generation algorithm is dependent on a security parameter, which describes how long (bitwise) the key is. Both encryption and decryption algorithm involve XOR'ing the message/ciphertext with the key. """ PARAMETER = 100 def keyGen(p): """ :param p: security paramter :output k: a number randomly chosen in the keyspace {0,1}^k, assigned to be K_e and K_d """ k = random.randint(0, 2**p-1) # ** is the operator for exponetiation return k def Enc(m, k): """ :param m: the message to be encrypted, whose bitlength must also be equal to the security parameter :param k: encryption key, K_e, generated by the key generation algorithm :output c: ciphertext corresponding to encrypting the message """ c = m ^ k # ^ is the operator for bitwise XOR return c def Dec(c, k): """ :param c: the ciphertext to be decrypted, whose bitlength must also be equal to the security parameter :param k: decryption key, K_d, generated by the key generation algorithm :output m: message corresponding to decrypting the ciphertext """ m = c ^ k return m """ now to show that the above functions are correct. We will encrypt a random message and verify that decrypting the corresponding ciphertext will reveal the same message """ key = keyGen(PARAMETER) message = random.randint(0, 2**PARAMETER-1) #print(message) ciphertext = Enc(message, key) response = Dec(ciphertext, key) #print(response) if response == message: print("Success") else: print("Something went wrong")
true
15f91012d9614d46fe03d9b4ff7b83dd53ad31b5
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question81.py
321
4.21875
4
""" By using list comprehension, please write a program to print the list after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. """ my_lst = [12,24,35,70,88,120,155] # using filter print(list(filter(lambda i: i % 35, my_lst))) # using comprehensive print([i for i in my_lst if i % 35])
true
9cc284d8bb87873882c68440c1ee19f0d4bcf094
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question4.py
336
4.1875
4
""" Input: Write a program which accepts a sequence of comma-separated numbers from console Output: generate a list and a tuple which contains every number.Suppose the following input is supplied to the program """ seq = input('Please in out a sequence of comma-separated numbers\n') print(seq.split(",")) print(tuple(seq.split(",")))
true
3503e1859b0f61b18254c8eb58e5501773c4a84f
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question39.py
241
4.1875
4
""" Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). """ my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) even_tup = tuple(i for i in my_tup if i % 2 == 0) print(even_tup)
false
154f1639865eb98d55ea566ccb0894b949ad14d3
vihahuynh/CompletePythonDeveloper2021
/break-the-ice-with-python/question28.py
291
4.15625
4
""" Define a function that can receive two integer numbers in string form and compute their sum and then print it in console. """ def sum_2_num(): num1 = input('Input the first number: \n') num2 = input('Input the second number: \n') print(int(num1) + int(num2)) sum_2_num()
true
0800b959b8ff2a1687b1c883135a06d5cec4776c
Pritheeev/Practice-ML
/matrix.py
1,665
4.1875
4
#getting dimension of matrix print "enter n for nxn matrix" n = input() matrix1 = [] matrix2 = [] #taking elements of first matrix print "Enter elements of first matrix" for i in range(0,n): #taking elements of first column print "Enter elements of ",i,"column, seperated by space" #raw_input().split() will split the string #'1 2 34'.split() will give ['1', '2', '34'] #map will convert its elements into integers [1, 2, 34] matrix1.append(map(int,raw_input().split())) print "Matrix 1 is",matrix1 #taking elements of second matrix print "Enter elements of second matrix" for i in range(0,n): #Similar to input taken for 1 matrix print "Enter elements of ",i,"column, seperated by space" matrix2.append(map(int,raw_input().split())) print "Matrix 2 is",matrix2 #adding add_matrix = [] for i in range(0,n): a = [] for j in range(0,n): #making a addition matrix's column to append #making a 1D matrix with elements as sum of elements of #respective columns of both matrices a.append(matrix1[i][j]+matrix2[i][j]) add_matrix.append(a) print "Addition of matrix is",add_matrix #multiplication multi_matrix = [] for i in range(0,n): a = [] for j in range(0,n): summ = 0 for k in range(0,n): summ = summ+(matrix1[i][k]*matrix2[k][j]) a.append(summ) multi_matrix.append(a) print "matrix1 x matrix 2 =",multi_matrix #transpose of matrix1 tr_matrix=[] for i in range(0,n): a = [] for j in range(0,n): #matrix1[j][i] will give row of matrix 1 #we are making it column of new matrix a.append(matrix1[j][i]) tr_matrix.append(a) print "Transpose of matrix 1 is",tr_matrix
true
a586bcfe643f3d205136714172bf386a7b8c0e1f
wmaxlloyd/CodingQuestions
/Strings/validAnagram.py
1,380
4.125
4
# Given two strings s and t, write a function to determine if t is an anagram of s. # For example, # s = "anagram", t = "nagaram", return true. # s = "rat", t = "car", return false. # Note: # You may assume the string contains only lowercase alphabets. # Follow up: # What if the inputs contain unicode characters? How would you adapt your solution to such case? # s = "anagram" t = "nagrama" print "sorting" print True if sorted(s) == sorted(t) else False print "Using a hash map" sHash = {} tHash = {} anagram = True if len(s) == len(t) else False if anagram: for i in xrange(len(s)): if s[i] not in sHash: sHash[s[i]] = 1 else: sHash[s[i]] += 1 if t[i] not in tHash: tHash[t[i]] = 1 else: tHash[t[i]] += 1 for key in sHash: try: if sHash[key] != tHash[key]: anagram = False break except: anagram = False break print anagram print "For all Unicode" anagram = True if len(s) == len(t) else False sHash = {} tHash = {} print sHash, tHash if anagram: for i in xrange(len(s)): sUniKey = ord(s[i]) tUniKey = ord(t[i]) if sUniKey in sHash: sHash[sUniKey] += 1 else: sHash[sUniKey] = 1 if tUniKey in tHash: tHash[tUniKey] += 1 else: tHash[tUniKey] = 1 print sHash, tHash for key in sHash: try: if sHash[key] != tHash[key]: anagram = False break except: anagram = False break print anagram
true
54f9eee09ecc211fc0cc378746ceb92c6ca76c8b
wdlsvnit/SMP-2017-Python
/smp2017-Python-maulik/extra/lesson8/madLibs.py
909
4.40625
4
#! python3 #To read from text files and let user add their own text anywhere the word- #ADJECTIVE, NOUN, ADVERB or VERB import re,sys try: fileAddress=input("Enter path of file :") file = open(fileAddress) except FileNotFoundError: print("Please enter an existing path.") sys.exit(1) fileContent = file.read() file.close() print(fileContent) findRegex = re.compile(r'''ADJECTIVE|NOUN|ADVERB|VERB''') fo=findRegex.search(fileContent) while(fo != None): print("Enter " + fo.group().lower() + ":") replacement=input() replaceRegex=re.compile(fo.group()) fileContent=replaceRegex.sub(replacement,fileContent,count=1) fo=findRegex.search(fileContent) newFileAddress=input("Enter path of new file:") print("") file=open(newFileAddress,"w") file.write(fileContent) file.close() print("Following text written to new file at " + newFileAddress) print(fileContent)
true
fe59db7b1a08053585d40019fa344a8afe2564aa
j-a-c-k-goes/replace_character
/replace_this_character.py
2,085
4.21875
4
""" For a list containing strings, check which characters exist, then replace that character with a random character. """ # ................................................................ Imports from random import * # ................................................................ Main Function def make_words(words=["tiger", "airplane", "cocaine"]): return words def replace_character(): string = make_words() string = choice(string) alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] new_words = [] letters_in_word = [] letters_not_in_word = [] for a in alphabet: if a not in string: # print("'{}'\t NOT IN\t'{}'".format(a, string)) letters_not_in_word.append(a) elif a in string: # print("'{}'\tEXISTS IN\t'{}'".format(a, string)) letters_in_word.append(a) print() print("these letters are in '{}'\n{}".format(string, ", ".join(letters_in_word))) print() print("these letters are not in '{}'\n{}".format(string, ", ".join(letters_not_in_word))) count = 0 for i in range(len(alphabet)): count += 1 rand_alpha = choice(alphabet) replace_char = alphabet[i] if rand_alpha in string: print() print('character {} exists in {}'.format(rand_alpha, string)) print('replacing "{}" in {} with "{}"'.format(rand_alpha, string, replace_char)) print('printing new word..') print() new_string = string.replace(rand_alpha,replace_char) new_words.append(new_string) print(new_string) new_words = ", ".join(new_words) return new_words # ................................................................ On Run, Export/Import if __name__ == "__main__": make_words() replace_character() # ................................................................ Updates # ................................................................ Bugs
false
b18cb0ad7ea82d7658bfb957eec60bb047c55971
darkknight161/crash_course_projects
/pizza_toppings_while.py
513
4.21875
4
prompt = "Welcome to Zingo Pizza! Let's start with Toppings!" prompt += "\nType quit at any time when you're done with your pizza masterpiece!" prompt += "\nWhat's your name? " name = input(prompt) print(f'Hello {name}!') toppings = [] topping = "" while topping != 'quit': topping = input('Name a topping to add: ') if topping == 'quit': break else: toppings.append(topping) print(f"Got it, {name}! Here's a run down of what you've ordered:") for value in toppings: print(value)
true
640c1b68233d7fe7ee1cdc0a44b30dd0afce9c1b
umangag07/Python_Array
/array manipulation/changing shape.py
1,019
4.625
5
""" Changing shapes 1)reshape() -:gives a new shape without changing its data. 2)flat() -:return the element given in the flat index 3)flatten() -:return the copied array in 1-d. 4)ravel() -:returns a contiguous flatten array. """ import numpy as np #1 array_variable.reshape(newshape) a=np.arange(8) b=a.reshape(2,2,2) print("The original array-:",a) print("Chnaged array-:",b) #2 array_variable.flat(int) a=np.arange(8) b=a.flat[3] print("The original array-:",a) print("Element of the flat index is",b) #3 array_variable.flatten() a=np.arange(8).reshape(2,2,2) b=a.flatten() print("The original array-:",a) print("Flatten array in 1-d -:",b) #4 """ array_variable.ravel(order) order can be-'F' fortran style 'K' flatten as elemnets occure in the memory""" a=np.array([[7,8,9,2,3],[1,5,0,4,6]]) b=a.ravel() c=a.ravel(order='F') print("The original array-:",a) print("Array after ravel -:",b) print("Array returned in fortran style-:",c)
true
31050593b4252bf94fb491e37e0a0628017d2b69
90-shalini/python-edification
/collections/tuples.py
785
4.59375
5
# Tuples: group of items num = (1,2,3,4) # IMUTABLE: you can't update them like a list print(3 in num) # num[1] = 'changed' # will throw error # Faster than list, for the data which we know we will not change use TUPLE # tuple can be a key on dictionary # creating/accessing -> () or tuple xyz = tuple(('a', 'b')) print("tuple created using tuple: ", xyz) #dictionary.items() returns a tuple of key:value in dictionary months = ('Jan', 'Feb', 'March', 'April', 'June', 'July', 'Aug') #ITERATING over tuples, using loops for month in months: print(month) #Tuple Methods: counting = (1,2,3,4,5,3,4,5,6,4,5,3,6) #count print('Count of element passed in function: ', counting.count(5)) #index print("Index of element:", counting.index(3)) # Nested tuples # can do slicing like lists
true
91039029eb70633744498be6f68fe1435f08ba96
annafeferman/colloquium_2
/45.py
950
4.3125
4
"""Перетин даху має форму півкола з радіусом R м. Сформувати таблицю, яка містить довжини опор, які встановлюються через кожні R / 5 м. Anna Feferman""" import math # імпортуємо math radius = int(input('Введіть радіус: ')) # користувач вводить радіус interval = radius / 5 # зазначаємо інтервал встановлення опор # встановлюємо початкові значенння x = 0 i = 0 while x < 2 * radius - interval: # користуємося формулою розрахунку x = x + interval i += 1 h = math.sqrt(x * (2 * radius - x)) # використовуємо math print(f'Висота {i} опори: {h.__round__(2)}') # виводимо опори, одночасно округлюючи їх значення
false
3aa3292bad982d13aa181250c738804b14af68ca
ssenthil-nathan/DSA
/linkedlistdelwithkey.py
1,628
4.21875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def Delete(self, key): temp = self.head #traverse till the last Node while(temp is not None): #if head itself holds the key if (temp.data == key): #make the head node as the next node self.head = temp.next #free the memory temp = None else: while(temp is not None): if (temp.data == key): break #store the value of previous node in prev variable. prev = temp temp = temp.next #if it is not return if (temp == None): return #make the next of the previous variable as the next of key node. prev.next = temp.next temp = None def printList(self): temp = self.head while(temp is not None): print(temp.data) temp = temp.next if __name__ == '__main__': llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second second.next = third third.next = None llist.push(8) llist.Delete(8) llist.printList()
true
61739837cf983d73229378376144c6465d798813
sevresbabylone/python-practice
/quicksort.py
744
4.34375
4
"""Quicksort""" def quicksort(array, left, right): """A method to perform quicksort on an array""" if left < right: pivot = partition(array, left, right) quicksort(array, left, pivot-1) quicksort(array, pivot+1, right) def partition(array, left, right): """Returns new pivot after partitioning array elements according to current pivot""" for index in range(left, right): if array[index] <= array[right]: array[left],array[index] = array[index],array[left] left += 1 array[left],array[right] = array[right],array[left] return left UNSORTED_ARRAY = [9, 7, 5, 11, 12, 2, 14, 3, 10, 6] quicksort(UNSORTED_ARRAY, 0, len(UNSORTED_ARRAY) - 1) print(UNSORTED_ARRAY)
true
f853cecddcac4e12ec8d8d2f60e01e80ad840f98
mclavan/Work-Maya-Folder
/2014-x64/prefs/1402/if_01_notes.py
1,239
4.5625
5
''' Lesson - if statements ''' ''' Basic if statement if condition: print 'The condition is True.' ''' if True: print 'The condition is True.' if False: print 'The condition is True' ''' What is the condition? 2 == 2 2 == 3 ''' ''' Operators == Equals != Not Equals > Greater Than >= Greater Than or equal to < Less Than <= Less Than or equal to ''' if 2 == 2: print '2 is equal to 2.' if 2 != 3: print '2 is not equal to 3.' ''' Using multiple conditions and or not ''' if 2 == 2 and 2 != 3: print 'Both conditions are True.' if 2 == 2 and 2 == 3: print 'Both conditions are True.' if 2 == 2 or 2 == 3: print 'Both conditions are True.' ''' What if I want to react to False? else statement ''' if 2 == 3: print 'The condition is True.' else: print 'The condition is False.' ''' What if I want to have multiple paths? elif statement. ''' ''' about command pm.about() # os=True returns operating system # windows=True returns true if currently on windows. # macOs=True returns true if currently on osx. ''' if pm.about(windows=True): print 'You are using a computer with windows.' elif pm.about(macOs=True): print 'You are using a computer with osx.' else: print 'You are using a different os.'
true
c297bfde92c1cfdd5e1784ff548374a9f17e6aa5
Courage-GL/FileCode
/Python/month01/day08/demo03.py
557
4.21875
4
""" 局部变量:小范围(一个函数)内使用的变量 全局变量:大范围(多个函数)内使用的变量 """ b = 20 def func01(): # 局部作用域不能修改全局变量 # 如果必须修改,就使用global关键字声明全局变量 global b b = 30 func01() print(b) # ? c = [30] def func02(): # 修改全局变量c还是修改列表第一个元素?? # 答:读取全局变量中数据,修改列表第一个元素 # 此时不用声明全局变量 c[0] = 300 func02() print(c) # [300]
false
3580a2af2a21f9f5d08bbb3115b7c3f7daf70f44
Courage-GL/FileCode
/Python/month01/day13/student_info_system.py
1,531
4.40625
4
""" 学生信息管理系统 """ class StudentModel: """ 学生信息模型 """ def __init__(self, name="", score=0, age=0, sid=0): self.name = name self.score = score self.age = age # 全球唯一标识符:系统为数据赋予的编号 self.sid = sid class StudentView: """ 学生信息视图:负责处理界面逻辑 """ def __init__(self): self.__controller = StudentController() def main(self): while True: self.__display_menu() self.__select_menu() def __display_menu(self): print("1 添加学生信息") print("2 显示学生信息") print("3 删除学生信息") print("4 修改学生信息") def __select_menu(self): item = input("请输入您的选项:") if item == "1": self.__input_student() def __input_student(self): stu = StudentModel() stu.name = input("请输入姓名:") stu.age = int(input("请输入年龄:")) stu.score = int(input("请输入成绩:")) self.__controller.add_student(stu) class StudentController: def __init__(self): self.__all_students = [] self.start_sid = 1001 def add_student(self, new_stu): # 生成学生编号 new_stu.sid = self.start_sid self.start_sid += 1 # 存储学生信息 self.__all_students.append(new_stu) # 入口 view = StudentView() view.main()
false
259a2f1710323a6aa1a905996af1563143528424
Courage-GL/FileCode
/Python/month01/day09/exercise02.py
491
4.1875
4
# 练习:定义数值累乘的函数 # list01 = [4,54,5,65,6] # result = 1 # for item in list01: # result *= item # print(result) def multiplicative(*args): # 合 result = 1 for item in args: result *= item return result print(multiplicative(43, 4, 5, 6, 7, 8)) print(multiplicative(43, 4)) print(multiplicative(43, 4)) # 如果调用函数时,只有列表. # 那么需要通过序列实参拆分后传递 list01 = [4, 5, 5, 6, 8] multiplicative(*list01) # 拆
false
b6d39d5c2f062fcf2dbafbf739f0c03f1c7ce3f4
Courage-GL/FileCode
/Python/month01/day10/exercise02.py
983
4.40625
4
""" 练习:对象计数器 统计构造函数执行的次数 使用类变量实现 画出内存图 class Wife: pass w01 = Wife("双儿") w02 = Wife("阿珂") w03 = Wife("苏荃") w04 = Wife("丽丽") w05 = Wife("芳芳") print(w05.count) # 5 Wife.print_count()# 总共娶了5个老婆 """ class Wife: count = 0 @classmethod def print_count(cls): print(f"总共娶了{cls.count}个老婆") def __init__(self, name=""): # 实例变量:表达实物的多样性(每个人的名字不同) self.name = name Wife.count += 1 w01 = Wife("双儿") # 类变量:0 --> 1 w02 = Wife("阿珂") # 类变量:1 --> 2 w03 = Wife("苏荃") # 类变量:2 --> 3 w04 = Wife("丽丽") # 类变量:3 --> 4 w05 = Wife("芳芳") # 类变量:3 --> 5 print(w05.count) # 5 Wife.print_count() # 总共娶了5个老婆
false
f0bb994dcb9fdc3bc96177da99f96a928a9e6ebf
Courage-GL/FileCode
/Python/month01/day04/demo03.py
547
4.375
4
""" for + range函数 预定次数的循环 使用 for 根据条件的循环 使用 while 练习:exercise04 """ # 写法1: # for 变量 in range(开始,结束,间隔): # 注意:不包含结束值 for number in range(1, 5, 1): # 1 2 3 4 print(number) # 写法2: # for 变量 in range(开始,结束): # 注意:间隔默认为1 for number in range(1, 5): # 1 2 3 4 print(number) # 写法3: # for 变量 in range(结束): # 注意:开始默认为1 for number in range(5): # 0 1 2 3 4 print(number)
false
c6d89bcaeb162b59041dd05b4acbef04f09c38fe
Courage-GL/FileCode
/Python/month01/day18/demo02.py
587
4.15625
4
""" 排列组合 全排列(笛卡尔积) 语法: 生成器 = itertools.product(多个可迭代对象) 价值: 需要全排列的数据可以未知 """ import itertools list_datas = [ ["香蕉", "苹果", "哈密瓜"], ["牛奶", "可乐", "雪碧", "咖啡"] ] # 两个列表全排列需要两层循环嵌套 # n n list_result = [] for r in list_datas[0]: for c in list_datas[1]: list_result.append((r, c)) print(list_result) list_result = list(itertools.product(*list_datas)) print(list_result)
false
4560ae75b9c66bbb4cf36973f48db46b620e10a8
pedronora/exercism-python
/prime-factors/prime_factors.py
458
4.125
4
def factors(value): factors_list = [] # Divisible by 2: while value % 2 == 0: factors_list.append(2) value = value / 2 # Divisible by other primes numbers: sqrt = int(value**0.5) for i in range(3, sqrt + 1, 2): while value % i == 0: factors_list.append(i) value = value / i # If value is prime if value > 2: factors_list.append(value) return factors_list
true
e991e53d24b80d8d91fabdf7696faefcfa3a61d3
weijiang1994/Learning-note-of-Fluent-Python
/character01/sample1-2.py
872
4.28125
4
""" @Time : 2020/6/11 9:59 @Author : weijiang @Site : @File : sample1-2.py @Software: PyCharm """ from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y # print类实例不在以<class object --- at --->的形式输出,而已字符串进行输出,称作为'字符串表示形式' def __repr__(self): return 'Vector({},{})'.format(self.x, self.y) def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def __add__(self, other): x = self.x + other.x y = self.y + other.y return Vector(x, y) def __mul__(self, scalar): return Vector(self.x*scalar, self.y*scalar) v1 = Vector(1, 2) v2 = Vector(2, 2) print('v1 + v2 = ', v1+v2) print('v2 * 3 = ', v1*3) print('abs(v1) = ', abs(v1+v2))
false
62b0c62e5d1f93a770ffc64b37b522b41c979b4b
HernanFranco96/Python
/Curso de Python/Intro-python/Python/7_controlflujo.py
941
4.3125
4
#if 2 < 5: # print('2 es menor a 5') # a == b # a < b # a > b # a != b # a >= b # a <= b #if 2 == 2: # print('2 es igual a 2') #if(2 > 1): # print('2 es mayor a 1') #if(2 < 1): # print('1 no es mayor a 2') #if(2 != 3): # print('2 es distinto que 3') #f(3 >= 2): # print('3 es mayor o igual a 2') #if(3 <= 7): # print('3 es menor o igual a 7') #if 2 > 5: # print("correcto") #elif 2 < 5: # print("2 es menor que 5") #else: # print("ninguna es correcta") #if 2 > 5: # print("correcto") #else: # print("ninguna es correcta") ################################################################## #if 2 < 5: print('If de una sola linea') #print("Cuando devuelve true") if 5 > 2 else print("Cuando devuelve false") ################################################################### if 2 < 5 and 3 > 2: print("Ambas devuelven True") if 1 < 0 or 1 > 0: print("Una de las dos condiciones devolvio true")
false
f52568ec7ea273dbb1f45b4415ce35f462783ef1
j94wittwer/Assessment
/Informatik/E3/task_4.py
460
4.1875
4
is_prime = False n = int(input("Please enter a number, to check if it's prime: ")) factors = [1] if n <= 1: is_prime = False elif n == 2: is_prime = True elif n % 2 == 0: is_prime = False else: for i in range(2, n): if n % i == 0: factors.append(i) if len(factors) > 2: is_prime = False else: is_prime = True if is_prime: print(str(n) + " is prime") else: print(str(n) + " is not prime")
false
fd7a963ec1bbba262d7f0cb3348995198a805674
isobelyoung/Week4_PythonExercises
/Saturday_Submission/exercise_loops.py
2,201
4.15625
4
# Q1 print("***QUESTION 1***") # Sorry Hayley - I had already written this bit before our class on Tuesday so didn't use the same method you did! all_nums = [] while True: try: if len(all_nums) == 0: num = int(input("Enter a number! ")) all_nums.append(num) else: num = int(input("Enter another number, or press enter: ")) all_nums.append(num) except ValueError: break sum_nums = sum(all_nums) print(f"The total sum of your numbers is {sum_nums}!") # Q2 print("***QUESTION 2***") mailing_list = [ ["Roary", "roary@moth.catchers"], ["Remus", "remus@kapers.dog"], ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], ["Biscuit", "biscuit@whippies.park"], ["Rory", "rory@whippies.park"] ] for i in range(len(mailing_list)): print(mailing_list[i][0] + ": " + mailing_list[i][1]) # Q3 print("***QUESTION 3***") names = [] name_1 = input("Hi there! Type your name: ") names.append(name_1) name_2 = input("Thanks for that! What's your mum's name? ") names.append(name_2) name_3 = input("Last one - what's your dad's name? ") names.append(name_3) for x in names: print(x) # Q4 print("***QUESTION 4***") groceries = [ ["Baby Spinach", 2.78], ["Hot Chocolate", 3.70], ["Crackers", 2.10], ["Bacon", 9.00], ["Carrots", 0.56], ["Oranges", 3.08] ] customer_name = input("Hi there! Thanks for visiting our store. What's your name? ") ind = 0 for x in groceries: n = int(input(f"How many units of {groceries[ind][0]} did you buy? ")) groceries[ind].append(n) ind += 1 receipt_width = 28 print() print("Your receipt is as follows: ") print() header = "Izzy's Food Emporium" print(header.center(receipt_width, '=')) total_cost = [] for i in range(len(groceries)): cost = groceries[i][1] * groceries[i][2] total_cost.append(cost) # space_width = receipt_width - len(groceries[i][0]) - 8 # print("{}".format(groceries[i][0]) + " " * space_width + "${:.2f}".format(cost)) print(f"{groceries[i][0]:<20} ${cost:>5.2f}") print("=" * receipt_width) receipt_sum = sum(total_cost) sum_str = "${:>5.2f}".format(receipt_sum) print(f"{sum_str:>27}") # print(sum_str.rjust(receipt_width, ' '))
true
e6e3fe4c8e42ba41bfdabdc0df75ef1d40584fb8
rigzinangdu/python
/practice/and_or_condition.py
984
4.3125
4
# We have to see [and] [or] conditions in pythons : #[and] remember if both the conditions true than output will be true !!! if it's one of condition wrong than it's cames false ----> !! #[or] remember one of the condition if it's true than its will be came true conditions -----> !! #<-----[and]------> name = "python" pass1 = "abc123456" username = input("Enter the username : ") password = input("Enter your password : ") if username == name and password == pass1: print("Line A") print("Login Successfully") else: print("invalid username and password") #<-----[and]------> #<-----[or]------> name = "python" pass1 = "abc123456" username = input("Enter the username : ") password = input("Enter your password : ") if username == name or password == pass1: print("Line A") print("Login Successfully") else: print("invalid username and password") #<-----[or]------>
true
ee8f4dfc81534a9dcfb4952e2ebd1f10e2c52be5
kaltinril/pythonTeaching
/assignments/rock_paper_scissors/sabreeen rock paper sisscors.py
864
4.25
4
import random turns_left = 3 while turns_left > 0: turns_left = turns_left - 1 player = input("Pick (R)ock, (P)aper, or (S)cissors:") computer = random.randint(1, 3) if computer == 1: computer = "r" elif computer == 2: computer = "p" elif computer == 3: computer = "s" if (player == computer): print("It's a tie!") if player == "r": if computer == "s": print("Player wins! Rock breaks Scissors") else: print("Computer wins!") elif player == "p": if computer == "r": print("Computer wins!Paper covers Rock!") else: print("Player wins!") elif player == "s": if computer == "p": print("Player wins! Scissors cut Paper!") else: print("Computer wins!")
false
ca6f741a9a9300c892550aa72f17e1bcbb8197cf
Marwan-Mashaly/ICS3U-Weekly-Assignment-02-python
/hexagon_perimeter_calculator.py
461
4.3125
4
#!/usr/bin/env python3 # Created by Marwan Mashaly # Created on September 2019 # This program calculates the perimeter of a hexagon # with user input def main(): # this function calculates perimeter of a hexagon # input sidelength = int(input("Enter sidelength of the rectangle (cm): ")) # process perimeter = 6*sidelength # output print("") print("Perimeter is {}cm ".format(perimeter)) if __name__ == "__main__": main()
true
75a3d8a466b9e3ba5e531a327c8e1d65f311e509
SureshKumar1230/mypython
/Lists.py
1,476
4.21875
4
data1=[1,2,3,4] data2=['x','y','z'] print(data1[0]) print(data1[0:2]) print(data2[-3:-1]) print(data1[0:]) print(data2[:2]) #list operator list1=[10,20] list2=[30,40] list3=list1+list2 print(list3) list1=[10,20,30] print(list1+[40]) print(list1*2) list1=[1,2,3,4,5,6,7] print(list1[0:3]) #appending the list list1=[34,'z',12] list1.append("rahul") print(list1) #deleting element from the list list1=[10,'rahul',50.8,'a',20,30] print(list1) del list1[0] print(list1) #find the minimum and maximum element of list list1=[101,981,32,44,112] list2=[21,45,121,100.45,98.2] print("Minimum value in List1:") print(min(list1)) print("Minimum value in List2:") print(min(list2)) print("Maximum value in List1:") print(max(list1)) print("Maximum value in List2:") print(max(list2)) print(len(list1)) data=[832,'abc','a',123.5] print(data.index(123.5)) print(data.index('a')) #pop the element from list data = [786,'abc','a',123.5,786] print("Last element is") print(data.pop()) print("2nd position element:") print(data.pop(1)) print(data) #insert the element into list data = [786,123.5,786] pri=data.insert(1,543) print(pri) #extend the list of data data1=['abc',123,10.5,'a'] data2=['ram',541] data1.extend(data2) print(data1) #remove data from the list data1=['abc',123,10.5,'a'] data1.remove('a') print(data1) #reverse list ist1=[10,20,30,40,50] print(list1.reverse()) #sort list1=[10,50,13] l=list1.sort() print(l)
false
1fca15a02681ee918c1ca292e0ced7ece90f53a5
AlekseiSpasiuk/python
/l2ex1.py
768
4.34375
4
#!python3 # 1. Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. array = [] array.append(None) array.append(123) array.append('hello, world!') array.append((11,22,33)) array.append({1,2,3,4,5,6,7,8,9,0}) array.append({'a':10,'b':20,'c':30}) array.append(list(range(10))) print(array) for element in array: print(element, type(element), sep=' -> ')
false
269fa0433fc048b50a8f24cc449a278c8b0b959c
kyumiouchi/python-basic-to-advanced
/11.73. Commun Errors.py
2,023
4.25
4
""" Common Errors It is important to understand the error code SyntaxError - Syntax error- not part of Python language """ # printf('Geek University') # NameError: name 'printf' is not defined # print('Geek University') # 1) Syntax Error # 1 # def function: # SyntaxError: invalid syntax # print('Geek University') # 2 # None = 1 # SyntaxError: can't assign to keyword # 3 # return # SyntaxError: 'return' outside function # 2) Name Error -> Variable or Function is not defined # a. # print(geek) # NameError: name 'geek' is not defined # b. # geek() # NameError: name 'geek' is not defined # c. # a = 18 # # if a < 10: # msg = 'Is great than 10' # # print(msg) # NameError: name 'msg' is not defined # 3 - Type Error -> function/operation/action # a. # print(len(5)) # TypeError: object of type 'int' has no len() # b. # print('Geek' + []) # TypeError: must be str, not list # 4 - IndexError - element of list wrong and or index data type # list_n = ['Geek'] # a. # print(list_n[2]) # IndexError: list index out of range # b. # print(list_n[0][10]) # IndexError: list index out of range # tuple_n = ('Geek',) # print(tuple_n[0][10]) # IndexError: string index out of range # 5) Value Error -> function/operation build-in argument with wrong type # Smaples # a. # print(int('42')) # print(int('GEek')) # ValueError: invalid literal for int() with base 10: 'GEek' # 6) Key Error-> Happen when try to access a dictionary with a key that not exist # a. # dic = {} # print(dic['geek']) # KeyError: 'geek' # 7) AttributeError -> variable do not have attribute/function # a. # tuple_n = (11, 2, 31, 4) # print(tuple_n.sort()) # AttributeError: 'tuple' object has no attribute 'sort' # 8) IndentationError -> not respect the indentation od 4 spaces # a. # def new_function(): # print("Geek") # IndentationError: expected an indented block # for i in range(10): # i+1 # IndentationError: expected an indented block # OBS: Exception == Error # Important to read the output error
true
5c288cf56bcccd91d9188d0123433678cb5f9876
kyumiouchi/python-basic-to-advanced
/10.67. Min e Max.py
2,874
4.15625
4
""" Min and Max max() -> the biggest number list_sample = [1, 8, 4, 99, 34, 129] print(max(list_sample)) # 129 tuple_sample = (1, 8, 4, 99, 34, 129) print(max(tuple_sample)) # 129 set_sample = {1, 8, 4, 99, 34, 129} print(max(set_sample)) # 129 dict_sample = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129} print(max(dict_sample)) # f dict_sample = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129} print(max(dict_sample.values())) # 129 # Do a program with two value and sho the max value_one = int(input('Write the first value: ')) value_two = int(input('Write the second value: ')) print(max(value_one, value_two)) print(max(4, 67, 54)) # 67 print(max('a', 'ab', 'abc')) # abc print(max('a', 'b', 'c', 'g')) # g print(max(4.4353, 5.3453)) # 5.3453 print(max('Yumi Ouchi')) # u min() -> the minor value list_sample = [1, 8, 4, 99, 34, 129] print(min(list_sample)) # 1 tuple_sample = (1, 8, 4, 99, 34, 129) print(min(tuple_sample)) # 1 set_sample = {1, 8, 4, 99, 34, 129} print(min(set_sample)) # 1 dict_sample = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129} print(min(dict_sample)) # a dict_sample = {'a': 1, 'b': 8, 'c': 4, 'd': 99, 'e': 34, 'f': 129} print(min(dict_sample.values())) # 1 # Do a program with two value and sho the max value_one = int(input('Write the first value: ')) value_two = int(input('Write the second value: ')) print(min(value_one, value_two)) print(min(4, 67, 54)) # 4 print(min('a', 'ab', 'abc')) # a print(min('a', 'b', 'c', 'g')) # a print(min(4.4353, 5.3453)) # 4.4353 print(min('Yumi Ouchi')) # ' ' names = ['Anat', 'Samson', 'Zanpy', 'Robervaldeck', 'Tim'] print(max(names)) # Zanpy print(min(names)) # Anat print(max(names, key=lambda name: len(name))) # Robervaldeck print(min(names, key=lambda name: len(name))) # Tim """ musics = [ {"title": "Thunderstruck", "sing": 3}, {"title": "Dead Bla", "sing": 2}, {"title": "Back Bla", "sing": 4}, {"title": "Too old bla", "sing": 32}, ] print(max(musics, key=lambda music: music['sing'])) # {'title': 'Too old bla', 'sing': 32} print(min(musics, key=lambda music: music['sing'])) # {'title': 'Dead Bla', 'sing': 2} # Challenge! Print just the title of music with max and min singed print(max(musics, key=lambda music: music['sing'])['title']) # Too old bla print(min(musics, key=lambda music: music['sing'])['title']) # Dead Bla # Challenge! Print the same without max(), min() and lambda max = 0 for music in musics: if music['sing'] > max: max = music['sing'] for music in musics: if music['sing'] == max: print("max", music['title']) # max Too old bla min = 99999 for music in musics: if music['sing'] < min: min = music['sing'] for music in musics: if music['sing'] == min: print("min", music['title']) # min Dead Bla
false
631632c5fd1c857d8ec88288d114f5ca499a6a46
elgun87/Dictionary
/main.py
1,211
4.25
4
# Created empty dictionary to add word and then to check if the word in the dictionary # If yes print the meaning of the word ''' dictionary = {} while True: word = input("Enter the word : ") if word in dictionary: #checking if the word in the list print(f'I have this word in my dictionary : {dictionary[word]}') else: add = input("I dont have this word meaning.Please add the meaning : ") dictionary [word] = add ''' ## In this program asking the name of the user then inserting his age. ''' check_list = {} #Created empty dictionary while True: name = input("What is your name : ") if name in check_list: #Checking if the name in the check_list.If yes print the check_list print(f'I found you in the system.Your age is {check_list[name]}') continue number = int(input("what is your age : ")) # asking his age check_list[name] = number ask = input("Enter the name to find your age : ") #asking his name to find how old is he if ask in check_list: print(check_list[name]) else : print('We dont have your in our system ') number = int(input("what is your age : ")) check_list [ask] = number '''
true
704045f6eaaa5c51d088b11ceb7877a7cf69b2d3
hannahmclarke/python
/dice_roll.py
1,199
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue May 21 21:02:54 2019 @author: Hannah """ """ Program will roll a pair of dice (number of sides will be randomly determined) and ask the user to guess the total value, to determine who wins Author: Hannah """ from random import randint from time import sleep def get_sides(): sides = randint(4, 8) return sides def get_user_guess(): guess = int(input("Make your guess: ")) return guess def roll_dice(number_of_sides): number_of_sides = get_sides() first_roll = randint(1, number_of_sides) second_roll= randint(1, number_of_sides) max_val = number_of_sides * 2 print ("Maximum possible value is %d" % (max_val)) guess = get_user_guess() if guess > max_val: print ("Guess is too high") else: print ("Rolling...") sleep(2) print ("First roll is a %d" % (first_roll)) sleep(2) print ("...and the second roll is %d" % (second_roll)) sleep(2) total_roll = first_roll + second_roll print ("Total is... %d" % (total_roll)) print ("Result...") sleep(1) if guess == total_roll: print ("Nice work! Winner!!") else: print ("Aha you lose!") roll_dice(get_sides())
true
a16aeb45a19ab709ab4aca7412b93f2cbcd4fb00
supervisaproject/Escuela-Analitica
/Bloque 1/Sesion 1/Ejemplos/Ejemplos - Operadores/ej13_logico.py
1,237
4.3125
4
#Ejemplo 13 #operadores de identidad #is. #si dos variables son dienticas devuelve True si no devuelve False #identity operators #is. #if two variables are scientific it returns True if it does not return False x = "hola" y = "hola" resultado = x is y print(resultado) #diferencia entre is y == #difference between is and == x = 2 y = 2.0 resultado = x==y print(resultado) resultado = x is y print(resultado) #operador de membresia #in #Comprueba si un valor se encuentra en un listado #membership operator #in #Check if a value is in a list pets=['dog','cat','ferret'] resultado = 'fox' in pets print(resultado) #operadores logicos #si las condiciones de ambos lados son True, entonces la expresión completa es True #logical operators #if the conditions on both sides are True, then the entire expression is True x = 6 y = 2 resultado = (x>7)and(y>-1) print(resultado) #Si las condiciones de uno de los dos lados es True, entonces la expresión completa es True #If the conditions of one of the two sides is True, then the entire expression is True x = 6 y = 2 resultado = (x>7)or(y>-1) print(resultado) #not combierte True a False y viceversa #not change True to False and vice versa resultado=not(True) print(resultado)
false
8a7c58ba13a2295ffbf4866d61eaef210814a58b
supervisaproject/Escuela-Analitica
/Bloque 1/Sesion 2/HomeWorks/HomeWork 2 - Macedonia de frutas/hw2.py
633
4.28125
4
# - *- coding: utf- 8 - *- #ejercicio 4 #sin modificar el listado de frutas crea un codigo que muestre el siguiente mensaje #without modifying the fruit list, create a code that displays the following message #Mis frutas favoritas son: #uva #platano #limon #naranja frutas = ["manzana", "pera", "uva", "cebolla", "platano", "limon", "ajo", "naranja"] print("Mis frutas favoritas son:") for #pon el rango correcto para el metodo for - put the correct range for the for method if #pon la condicion correcta - # put the correct condition print #imprime el valor de la lista que toca - #prints the value of the list it touches
false
18440ad27f90f49a1c08f5df08ffe73d743d6967
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02_extra.py
2,174
4.4375
4
def middle_of_three(a, b, c): """ Returns the middle one of three numbers a,b,c Examples: >>> middle_of_three(5, 3, 4) 4 >>> middle_of_three(1, 1, 2) 1 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW return ... def sum_up_to(n): """ Returns the sum of integers from 1 to n Examples: >>> sum_up_to(1) 1 >>> sum_up_to(5) 15 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW return ... def square_root_heron(x, epsilon=0.01): """ Find square root using Heron's algorithm Parameters: x: integer or float epsilon: desired precision, default value epsilon = 0.01 if not specified Returns: the square root value, rounded to two decimals the number of iterations of the algorithm run Example use: >>> y, c = square_root_heron(20) >>> print(y, c) 4.47 4 """ # DON'T CHANGE ANYTHING ABOVE # UPDATE CODE BELOW guess = x/2 # Make initial guess # Loop until squared value of guess is close to x while abs(guess*guess - x) >= epsilon: guess = (guess + x/guess)/2 # Update guess using Heron's formula return round(guess, 2), ... # replace the dots with the final number of iterations def square_root_bisection(x, epsilon=0.01): """ Find square root using bisection search Parameters: x: integer or float epsilon: desired precision, default value epsilon = 0.01 if not specified Returns: the square root value, rounded to two decimals the number of iterations of the algorithm run Example use: >>> y, c = square_root_bisection(20) >>> print(y, c) 4.47 9 """ # DON'T CHANGE ANYTHING ABOVE # UPDATE CODE BELOW low = 0.0 high = max(1.0, x) # Why are we doing this? What would happen for x=0.5? guess = (low + high)/2 # First guess at midpoint of low and high while abs(guess*guess - x) >= epsilon: if guess*guess < x: low = ... # update low else: high = ... # update high guess = ... # new guess at midpoint of low and high return ..., ...
true
8ee4f7214d13842468a03b05f7fdd25e3947c7fc
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02.py
1,057
4.375
4
def sum_of_squares(x, y): """ Returns the sum of squares of x and y Examples: >>> sum_of_squares(1, 2) 5 >>> sum_of_squares(100, 3) 10009 >>> sum_of_squares(-1, 0) 1 >>> x = sum_of_squares(2, 3) >>> x + 1 14 """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS return x^2+y^2 # REPLACE THIS LINE WITH YOUR CODE def print_grade(mark, grade_high, grade_low): """ Prints out 'distinction', 'pass', or 'fail' depending on mark If mark is at least grade_high, prints 'distinction' Else if mark is at least grade_low, prints 'pass' Else prints 'fail' Examples: >>> grade_high = 70 >>> grade_low = 50 >>> print_grade(20, grade_high, grade_low) fail >>> print_grade(61, 70, 50) pass >>> print_grade(90, 80, 60) distinction """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS if mark >= grade_high: print("distinction") elif mark >= grade_low: print("pass") else: print("fail")
true
0c143e6c44d259294ada8ee2cda95c37f74a15ff
Lanottez/IC_BA_2020
/1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses06/ses06_extra.py
1,525
4.5625
5
def caesar_cipher_encrypt(str_to_encrypt, n): """ Encrypt string using Caesar cipher by n positions This function builds one of the most widely known encryption techniques, _Caesar's cipher_. This works as follows: you should be given a string str_to_encrypt and an encoding integer n, which then be used to replace each initial letter to the encrypted one by simply shifting the letter by n positions. Parameters: str_to_encrypt: string n: shift parameter Returns: n-encrypted string Examples: >>> caesar_cipher_encrypt('a', 1) 'b' >>> caesar_cipher_encrypt('abc', 1) 'bcd' >>> caesar_cipher_encrypt('abc', 4) 'efg' >>> caesar_cipher_encrypt('thisistherealdeal', 6) 'znoyoyznkxkgrjkgr' """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS alphabet = 'abcdefghijklmnopqrstuvwxyz' def caesar_cipher_decrypt(str_to_decrypt, n): """ Decrypt Caesar cipher by n positions Parameters: str_to_decrypt: string n: shift parameter Returns: n-decrypted string Examples: >>> caesar_cipher_decrypt('b', 1) 'a' >>> caesar_cipher_decrypt('bcd', 1) 'abc' >>> caesar_cipher_decrypt('efg', 4) 'abc' >>> caesar_cipher_decrypt('znoyoyznkxkgrjkgr', 6) 'thisistherealdeal' """ # DON'T CHANGE ANYTHING ABOVE # YOUR CODE BELOW THIS alphabet = 'abcdefghijklmnopqrstuvwxyz'
true
409ef5ba6745db47dbff12729c87e41eb9761e21
dpochernin/Homework_2
/Homework_2_6.py
266
4.125
4
list_1 = [] while len(list_1) < 3: list_1.append(int(input("Enter number:"))) i = 0 if list_1[0] == list_1[1] or list_1[1] == list_1[2] or list_1[0] == list_1[2]: i = 2 if list_1[0] == list_1[1] == list_1[2]: i = 3 print("In list is ", i, "mach digits")
false
7d3e24b89e54f42068ce2b8dca77ca5e3fc2abed
santhosh15798/k
/sa.py
233
4.15625
4
ch=input() if(ch=='a'or ch=='e'or ch=='i'or ch=='o' or ch=='u' or ch=='A' or ch=='E'or ch=='I'or ch=='O' or ch=='U'): print ("Vowel") elif((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')): print("Consonant") else: print("invalid")
false
638cd82594d426b03aa471ead40ee21e696ca814
hyuraku/Python_Learning_Diary
/section1/dictionary.py
1,183
4.125
4
#辞書型のデータの基本的な作り方。 d={'x':10,'y':20} print(d) print(type(d)) #> <class 'dict'> print(d['x'],d['y']) #xの値を100にする。 d['x']=100 print(d['x'],d['y']) #> 100 20 #'z':200 を追加する d['z']=200 #'1':50 を追加する d[1]=50 print(d) #> {'x': 100, 'y': 20, 'z': 200, 1: 50} #これも辞書型データの作り方 d2=dict(a=10,b=20) print(d2) #> {'a': 10, 'b': 20} #特定の型に使えるメソッドを調べるためにはhelp関数を使うと良い #help(d2) print(d2.keys()) #> dict_keys(['a', 'b']) print(d2.values()) #> dict_values([10, 20]) d3={'a':100,'c':30} d4=dict(a=30,b=40) print(d2,d3) #> {'a': 10, 'b': 20} {'a': 100, 'c': 30} #d2にd3を追加、d2にあったaの値はd3の値になる。 d2.update(d3) print(d2) #> {'a': 100, 'b': 20, 'c': 30} #aの値の出力するコマンド、基本は左のコマンド print(d2['a'],d2.get('a')) #> 100 100 #d2からaを削除、aの値を出力 d2.pop('a') #> 100 #d2からaが削除されているのを確認する。 print(d2) #> {'b': 20, 'c': 30} #d2にkeyであるcがあるかを判定する。 #あればTrue、なければFalse print('c' in d2) #> True
false
a858fbfb5b2570d28a04edf7ef7d99fae6cd1038
mcwiseman97/Programming-Building-Blocks
/adventure_game.py
1,829
4.1875
4
print("You started a new game! Congratulations!") print() print("You have just had a very important phone call with a potential employer.") print("You have been in search of a new job that would treat you better than you had been at your last place of emplyement.") print("John, the employer, asked you to submit to him your desired salary by 5pm today.") print() salary = int(input("What salary do you with to obtain in this job? ")) print() print("Some time later...") print("Thank you for submiting your desired wages! I see that you are looking for", salary,"dollars. ") print() if salary > 75000: print("We reviewed the slary that you presented and are sorry that we cannot provide that amount for you.") print("However we would like to offer you 6500. Would you be interested in this amount?") high_salary = input("YES or NO: ") if high_salary == "yes": print("Great, We look forward to working with you! We have just sent you an email with a document you need to sign before you come into work on monday.") elif high_salary == "no": print("You said no") elif salary >= 45001: print("Good news! We have accepted your request for,", salary, "!") print("We will send you an email with a document to sign before you start work on monday.") elif salary <= 45000: print("Are you sure you don't want to ask for more than,", salary,"?") low_salary = input("YES or NO: ") if low_salary == "yes": print("Upon reviewing your request, we have determined that we will offer you the job, at out starting salary for this position.") print("You will recieve an email shortly. Please sign the document, which will indicate that you accept the job position.") elif low_salary == "no": salary = int(input("What salary do you with to obtain in this job? ")) else: print("TRY AGAIN")
true
440d7421e3f5a138f13f43f9ce1b79d170ef8eb4
Soooyeon-Kim/Object-Oriented-Programming
/Practice/Encapsulation_PointClass.py
946
4.4375
4
#2차원 평면상의 점(point)을 표현하는 클래스 Point를 정의하라. import math class Point: def __init__(self, x=0.0, y=0.0): self.__x = x self.__y = y @property def x(self): return self.__x @property def y(self): return self.__y def move(self, x, y): self.__x = x self.__y = y def reset(self): self.__x = 0.0 self.__y = 0.0 def distance(self, pt): x2 = math.pow(self.__x - pt.x, 2) y2 = math.pow(self.__y - pt.y, 2) return math.sqrt(x2+y2) def main(): p1 = Point() p2 = Point(1.0, 1.0) d = p1.distance(p2) print(f'distance between p1:({p1.x}, {p1.y}) and p2:({p2.x}, {p2.y}) ‐ {d:.4f}') p1.move(2.0, 3.0) p2.reset() d = p1.distance(p2) print(f'distance between p1:({p1.x}, {p1.y}) and p2:({p2.x}, {p2.y}) ‐ {d:.4f}') main()
false
26eeca2fda332e7113887da66b91edf8ad362a2c
nerminkekic/Guessing-Game
/guess_the_number.py
912
4.4375
4
# Write a programme where the computer randomly generates a number between 0 and 20. # The user needs to guess what the number is. # If the user guesses wrong, tell them their guess is either too high, or too low. import random # Take input from user guess = int(input("Guess a number between 0 and 20! ")) # Number of guesses tracking guess_count = 1 # Generate random number randomNumb = random.randrange(20) # Allow user to guess again if first guess is not correct # Also check for conditions and let user know if they guessed high or low while guess != randomNumb: guess_count += 1 if guess < randomNumb: print("You guessed low!") guess = int(input("Try another guess. ")) elif guess > randomNumb: print("Your guessed high!") guess = int(input("Try another guess. ")) print("You have guessed correct. YOU WIN!") print(f"Total number of guesses: {guess_count}")
true
e0fd54fe84a10dc5d8e15ded5538fd5674b40e6e
kilmer7/workspace_python
/Curso em Video/desafio16.py
345
4.21875
4
import math num = float(input('Digite um número real: ')) num = math.trunc(num) print('O número inteiro do algarismo que você escreveu é {}'.format(num)) ''' Outra forma de resolver sem adicionar bibliotecas. num = float(input('Digite um valor')) print('O valor digitado foi {} e a sua porção inteira é {}'.format(num, int(num))) '''
false
4844eb4416c99f709e8d8d7d4219bee020c7adb6
nbpillai/npillai
/Odd or Even.py
205
4.3125
4
print("We will tell you if this number is odd or even.") number = eval(input("Enter a number! ")) if number%2==0: print("This is an even number!") else: print ("This number is an odd number!")
true
ee4bb01eb029819b15ee23c478edab0aada9608b
ari-jorgensen/asjorgensen
/SimpleSubstitution.py
1,140
4.15625
4
# File: SimpleSubstitution.py # Author: Ariana Jorgensen # This program handles the encryption and decryption # of a file using a simple substitution cipher. # I created this algorithm myself, only borrowing the # randomized alphabet from the Wikipedia example # of substitution ciphers # NOTE: For simplicity, all characters are converted to lowercase # Regular alphabet & randomized substitution # alphabet to be used for encyrption/decryption alpha = 'abcdefghijklmnopqrstuvwxyz' subAlpha = 'vjzbgnfeplitmxdwkqucryahso' def simpleSubEncrypt(line): subLine = '' subWord = '' for word in line: for char in word: try: char = char.lower() ind = alpha.index(char) newChar = subAlpha[ind] subWord += newChar except ValueError: subWord = char subLine += subWord subWord = '' return subLine def simpleSubDecrypt(line): normalLine = '' normalWord = '' for word in line: for char in word: try: char = char.lower() ind = subAlpha.index(char) newChar = alpha[ind] normalWord += newChar except ValueError: normalWord += char normalLine += normalWord normalWord = '' return normalLine
true
f09176c324c14916ee1741dd82077dd667c86353
cbarillas/Python-Biology
/lab01/countAT-bugsSoln.py
903
4.3125
4
#!/usr/bin/env python3 # Name: Carlos Barillas (cbarilla) # Group Members: none class DNAString(str): """ DNAString class returns a string object in upper case letters Keyword arguments: sequence -- DNA sequence user enters """ def __new__(self,sequence): """Returns a copy of sequence in upper case letters""" return str.__new__(self,sequence.upper()) def length(self): """Returns length of sequence""" return len(self) def getAT(self): """Returns the AT content of the sequence""" num_A = self.count("A") num_T = self.count("T") return ((num_A + num_T)/self.length()) """ Builds a new DNAString object based on what the user inputs Prints the AT content of the sequence """ DNA = input("Enter a DNA sequence: ") coolString = DNAString(DNA) print ("AT content = {:0.3f}".format(coolString.getAT()))
true
8db2c042802cacea93d08efe36084db87a410409
hkaushalya/Python
/ThinkPythonTutorials/exer_10_1.py
595
4.125
4
def capitalize_all(t): res = [] for x in t: res.append(x.capitalize()) return res ###################### # This can handle nested list with upto depth of 1. # i.e. a list inside a list. # not beyond that, like , list in a list in a list!!! ###################### def capitalize_nested(t): res = [] for x in t: #if len(x)>1: res += capitalize_all(x) #else: # res += capitalize_all(x) return res mylist = ['a','a','c'] nestedlist=['p','q',mylist,['x','y','z'] print capitalize_all(mylist) print capitalize_nested(nestedlist)
false
92db81dc42cd42006e58a7acb64347ef443b4afc
mattin89/Autobiographical_number_generator
/Autobiographic_Numbers_MDL.py
1,542
4.15625
4
''' By Mario De Lorenzo, md3466@drexel.edu This script will generate any autobiographic number with N digits. The is_autobiographical() function will check if numbers are indeed autobiographic numbers and, if so, it will store them inside a list. The main for loop will check for sum of digits and if the number of 1s is 0, 1 or 2. After inserting the N digits, the script will tell you how long it should take. You can decide which for loop condition to keep based on your purpose. ''' import collections from tqdm import tqdm user = input("N digits: ") b_list = [] def is_autobiographical(num): lst = list(map(int, list(num))) counts = collections.Counter(lst) return all(lst[i] == counts.get(i, 0) for i in range(len(lst))) def check_ones(num): #The numbers of 1s can only be 0,1, or 2 check = str(num) if num > 10: if int(check[1]) >= 3: return True else: return False else: return False #for i in tqdm(range(10**(int(user)-1), 10**(int(user)))): #Only N digits numbers for i in tqdm(range(10**(int(user)))): #All numbers up to N digits sum_of_digits = sum(int(digit) for digit in str(i)) if sum_of_digits == len(str(i)): #Only checks the numbers that the sum of each digits is equal to the length if is_autobiographical(str(i)): b_list.append(i) if check_ones(i) and i > 10: temp = str(i) temp1 = int(temp[0]) i = (temp1+1) * (10 ** (len(temp)-1)) print() print(b_list)
true
801c588912b99c98b0076b70dbbd8d7b2184c23e
garetroy/schoolcode
/CIS210-Beginner-Python/Week 2/counts.py
1,410
4.4375
4
""" Count the number of occurrences of each major code in a file. Authors: Garett Roberts Credits: #FIXME Input is a file in which major codes (e.g., "CIS", "UNDL", "GEOG") appear one to a line. Output is a sequence of lines containing major code and count, one per major. """ import argparse def count_codes(majors_file): """ Adds majors to a list. Counts the amount of times a major is in a list and then prints the major and the count in the list. If it is already a previously gone through major, it skips it and goes to the next. """ majors = [ ] gone_through = [ ] for line in majors_file: majors.append(line.strip()) majors = sorted(majors) count = 0 for major in majors: count = majors.count(major) if major in gone_through: continue gone_through.append(major) print(major, count) def main( ): """ Interaction if run from the command line. Usage: python3 counts.py majors_code_file.txt """ parser = argparse.ArgumentParser(description="Count major codes") parser.add_argument('majors', type=argparse.FileType('r'), help="A text file containing major codes, one major code per line.") args = parser.parse_args() # gets arguments from command line majors_file = args.majors count_codes(majors_file) if __name__ == "__main__": main( )
true
40cd6d4d249a74f144be83a371b8cb1c1d383cb0
MrSerhat/Python
/Fibonacci_Serisi.py
323
4.15625
4
""" Fibonacci Serisi yeni bir sayıyı önceki iki sayının toplamı şeklinde oluşturur. 1,1,2,3,5,8,13,21,34... a,b=b,a+b "a nın değerine b nin değerini atıyoruz" """ a=1 b=1 fibonacci=[a,b] for i in range(20): a,b=b,a+b print("a:", a,"b:",b) fibonacci.append(b) print(fibonacci)
false
2e18fd51ae66bc12003e51accf363523f227a76e
agzsoftsi/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,007
4.46875
4
#!/usr/bin/python3 """Define a method to print a square with #""" class Square: """Class Square is created""" def __init__(self, size=0): """Initializes with a size""" self.size = size @property def size(self): """method to return size value""" return self.__size @size.setter def size(self, value): """method to set a size value""" if type(value) != int: raise TypeError('size must be an integer') if value < 0: raise ValueError('size must be >= 0') """Verify that size is not negative or 0""" self.__size = value def area(self): """Return the area of the square""" return self.__size**2 def my_print(self): """Prints square with # in stdout.""" if self.__size == 0: print() else: for num in range(0, self.__size): print('#' * self.__size) """loop to print the square"""
true