blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
65b74aac44554152dc0fec93df6345180e9c6d86
Wellington-Farina-Ferraz/Projetos-de-estudo-Python
/media_aritimetica_x.py
629
4.1875
4
print("Digite zero para finalizar o Programa .") soma = 0 #variaveu par guarda a somas cont = 0 # variavel par contar quanta vez passou no laco result = 0 # variavel para guarda o resultado valor = 1 # variavel para guarda o valor digitado pelo usuario while valor != 0: cont = cont + 1 valor = int(input("digite o valor: ")) soma = soma + valor # soma os valors digitado // Digitado 0 ele sai do laco cont = cont - 1 # retira 1 para deixar a divisao exata result = soma / cont # calcula o resultado print("sua conta é: ", soma, " / ", cont) print("A media aritimetica é: ", result) #imprime o resultado
false
62e8be275c05c86054b0c1b572fe8a7c4383c539
katohawke/python
/func_doc.py
322
4.21875
4
#!/usr/bin/env python3 def printMax(x, y): '''Выводит максимальное из двух чисел. Оба значения должны быть целыми числами.''' x = int(x) y = int(y) if x > y: print(x, 'is more') else: print(y, 'is more') printMax(3, 5) print(printMax.__doc__)
false
f4c4ebeb7c1e579eb647bd388c7489a227c10ae2
AK88-RM/Udacity-CS101
/unit3_optional/3o.2.symmetric_square.py
1,278
4.15625
4
def symmetric(mylist): if mylist == []: # check from empty set return True rows = len(mylist) # check length of rows versus columns columns = len(mylist[0]) if columns != rows: return False i = 0 j = 0 for row in mylist: print 'row', row column = [] for element in row: # compose column list1 = mylist[i] cell = list1[j] column.append(cell) i = i+1 print 'column', column i = 0 j = j + 1 if row != column: # check row entry = column entry return False return True #print symmetric([[1, 2, 3], # [2, 3, 4], # [3, 4, 1]]) #>>> True print symmetric([]) print symmetric([["cat", "dog", "fish"], ["dog", "dog", "fish"], ["fish", "fish", "cat"]]) #>>> True #print symmetric([["cat", "dog", "fish"], # ["dog", "dog", "dog"], # ["fish","fish","cat"]]) #>>> False #print symmetric([[1, 2], # [2, 1]]) #>>> True #print symmetric([[1, 2, 3, 4], # [2, 3, 4, 5], # [3, 4, 5, 6]]) #>>> False #print symmetric([[1,2,3], # [2,3,1]]) #>>> False
true
ead05c6c612f3a5387bb63db9d7c87f080e9ebe4
AK88-RM/Udacity-CS101
/unit2_optional2/2o2.5.leap_year_baby.py
1,424
4.21875
4
def is_leap_baby(day,month,year): return ((year % 400 == 0) or (year%100 != 0)) and (year % 4 == 0) and (day == 29) and (month == 2) # if year % 400 == 0: # if (day == 29) and (month == 2): # return True # else: return False # if year % 100 == 0: # return False # if year % 4 == 0: # if (day == 29) and (month == 2): # return True # else: return False # else: # return False # The function 'output' prints one of two statements based on whether # the is_leap_baby function returned True or False. def output(status,name): if status: print "%s is one of an extremely rare species. He is a leap year baby!"%name else: print "There's nothing special about %s's birthday. He is not a leap year baby!"%name #Test Cases #output(is_leap_baby(29,2,1996),'Calvin') #>>>Calvin is one of an extremely rare species. He is a leap year baby! #output(is_leap_baby(19,6,1978),'Garfield') #>>>There's nothing special about Garfield's birthday. He is not a leap year baby! #output(is_leap_baby(29,2,2000),'Hobbes') #>>>Hobbes is one of an extremely rare species. He is a leap year baby! #output(is_leap_baby(29,2,1900),'Charlie Brown') #>>>There's nothing special about Charlie Brown's birthday. He is not a leap year baby! #output(is_leap_baby(28,2,1976),'Odie') #>>>There's nothing special about Odie's birthday. He is not a leap year baby!
true
341d8a58d70c439bad3e9e35e1ab59f3d413d862
AbhinavJain13/oct_2016_python
/JoshuaAhn/JoshuaAhn/algorithms/scoresandgrades.py
671
4.125
4
def grade(num): print "Scores and Grades" for x in range(num): score = input("Enter score: ") if score > 100 or score < 0: print "Please enter score between 0 and 100" else: if score <= 59: grade = "F" elif score >= 60 and score <= 69: grade = "D" elif score >= 70 and score <= 79: grade = "C" elif score >= 80 and score <= 89: grade = "B" elif score >= 90: grade = "A" print "Score:", str(score) + "; Your grade is",grade print "End of program. Bye!"
true
0bbbf518aaae6fcdd2497b95a2de6d3cbf0f6763
AbhinavJain13/oct_2016_python
/erik/1-python/ex1.py
289
4.375
4
''' 1-prints all the odd numbers from 1 to 1000. Use the for loop and don't use array to do this exercise. 2-prints all the multiples of 5 from 5 to 1,000,000. ''' #1 for x in range(1,1000,2): print "loop - ",x #2 for x in range(5,1000,5): if x%5==0: print "loop - ",x
true
61df44c437f0121fb992e480ec22215efa6c7a55
rakib06/data-science-python
/python/List_Tuples_Sets.py
1,806
4.125
4
""" courses_2=['Bangla','English'] courses.insert(0,courses_2 )#oi index a puro list ta add hbe print(courses[0]) courses.remove(courses_2) courses.extend(courses_2) #2 ta marge hbe print('Extend : ') print(courses) courses.append('Chemistry') #ENd a ekta element add kora courses.insert(0,'Art') #prothome ekta element add hbe print('Before pop') print(courses) popped=courses.pop() #FIFO print('After Pop') print(courses) print('pop element') print(popped) courses.reverse() print('After reverse') print(courses) courses.sort() print('After sorting :') print(courses) print('descending order :') courses.sort(reverse=True) print(min(courses)) print(courses.index('Math')) print('list comparison') for item in courses: print(item) """ courses=['History','Math','Physics','CompSci'] """ #loop with index for index, course in enumerate(courses,start=1): print(index,course) """ """ course_str=' -- '.join(courses) #split new_list=course_str.split(' - ') print(course_str) print(new_list) """ """ ####immutable/mutable list_1=['History','Math','Physics','CompSci'] list_2=list_1 print(list_1) print(list_2) ## list_1[0]='Art' print(list_1) print(list_2) ##Immutable tuple_1=('History','Math','Physics','CompSci') tuple_2=tuple_1 print(tuple_1) print(tuple_2) """ #but not support #tuple_1[0]='Art' ######SETS cs_courses={'History','Math','Physics','CompSci'} art_courses={'History','Math','Bangla','Art'} print(cs_courses) print('Math' in cs_courses) print(cs_courses.intersection(art_courses)) print(cs_courses.difference(art_courses)) print(art_courses.difference(cs_courses)) print(art_courses.union(cs_courses)) #Empty list empty_list=[] empty_list=list() #Empty touple empty_touple=() empty_touple=tuple() #Empty Set empty_set={} # this isn't right ! it's a dictionary empty_set=set()
false
56a2a3dcb6d2a22cfff9ff78b01105a4132d8ff5
crazzle/fp_python
/01_getting_started/task1/solution1.py
1,248
4.21875
4
import unittest """ Task 1: Convert the string into a string of ASCII codes Detail: Convert the string into a string of ASCII codes concatenated by '+' Example: NCA = "78+67+65" Characters can be converted to ASCII by ord() """ class Testsuite(unittest.TestCase): the_string = "Never Code Alone" result = "78+101+118+101+114+32+67+111+100+101+32+65+108+111+110+101" def test(self): self.assertEqual(self.result, convert(self.the_string)) self.assertEqual(self.result, convert_recursive(self.the_string)) self.assertEqual(self.result, convert_comprehension(self.the_string)) self.assertEqual(self.result, convert_map(self.the_string)) def convert(zeile): zahlen = "" for i in range(0, len(zeile)): zahl = str(ord(zeile[i])) zahlen += zahl if i < len(zeile)-1: zahlen += "+" return zahlen def convert_recursive(zeile): if len(zeile) > 1: return str(ord(zeile[0])) + "+" + convert_recursive(zeile[1:]) else: return str(ord(zeile[0])) def convert_comprehension(zeile): return "+".join([str(ord(buchstabe)) for buchstabe in zeile]) def convert_map(zeile): return "+".join(map(lambda b: str(ord(b)), zeile))
true
2bc9682f793be2247314fb83180a98d91097902a
amebrahimi/django_tutorial
/warmup/strings.py
667
4.21875
4
name = 'Brad' age = 32 # Concatenate print('Hello I am ' + name + ' and I am ' + str(age)) # Arguments by position print('{1}, {2}, {0}'.format('a', 'b', 'c')) # Arguments by name print('My name is {name} and I am {age}'.format(name=name, age=age)) # F-Strings (only in 3.6+) print(f'My name is {name} and I am {age}') # String Methods s = 'Hello there world' # Capitalize first letter print(s.capitalize()) # Get length len(s) # Replace s.replace('world', 'everyone') # Count s.count('h') # Starts with s.startswith('hello') # Ends with s.endswith('d') # Is all alphanumeric s.isalnum() # Is all alphabetic s.isalpha() # Is all mumeric s.isnumeric()
false
31ac315070c9493f21543ad133b963966f372933
ProperBeowulf/cp1404practicals
/prac_05/word_occurrences.py
449
4.125
4
word_dictionary = {} user_string = input("please enter a string") words_list = user_string.split() for word in words_list: if word in word_dictionary: word_dictionary[word] += 1 else: word_dictionary[word] = 1 words_list = list(word_dictionary.keys()) words_list.sort() longest_word = max(len(word) for word in words_list) for word in words_list: print("{:{}}: {}".format(word, longest_word, word_dictionary[word]))
true
0e62e640fbf13620fc5c614457d3d3bfc058588d
ViAugusto/Logica-de-programacao-python
/rm92244_EX02.py
1,116
4.1875
4
print("Programação não é para os mais velhos! Jovens também podem usar.") print("Aqui você informará suas transações que fez hoje, depois será feito uma média e exibirá os valores.") quantidade = int(input("Quantas transações você fez hoje?: ")) transacoes = 0 contador = 1 if(quantidade <= 0): print("Ops, você colocou um número igual ou inferior a 0.") print("Programa finalizado!") elif(quantidade >= 85): print("Duvido que você tenha feito tantas transações assim!") print("Programa finalizado!") else: while(contador <= quantidade): armazenarTransacoes = float(input("Quantos reais você gastou nessa transação?: ")) if(armazenarTransacoes <= 0): print("Você está fazendo transações, não um depósito na sua conta! Digite o valor correto.") else: transacoes = transacoes + armazenarTransacoes contador = contador + 1 media = transacoes / quantidade print("Você gastou R${}".format(transacoes) + " hoje!") print("E também, em média, gastou R${}".format(media) + " por cada transação.")
false
72a09034410d67403701eff571f321f27e309f64
jaythaceo/Python-Beginner
/src/strings/palindrome.py
1,010
4.34375
4
""" Check to see if it's a palindrome If it isn't it will convert to palindrome palindrome.py Name: Jason Brooks Email: jaythaceo@gmail.com Twitter: @jaythaceo """ def is_palindrome(string_value): char_array = list(string_value) size = len(char_array) half_size = int(size / 2) for i in range(0, half_size): if char_array[i] != char_array[size - i - 1]: return False return True def convert_to_palindrome(v): def action(string_value, chars): chars_to_append = list(string_value) [0:chars] chars_to_append.reverse() new_value = string_value + "".join(chars_to_append) if not is_palindrome(new_value): new_value = action(string_value, chars + 1) return new_value return action(v, 0) user_input = raw_input("string to terminate program (exit to terminate program): ") while user_input != "exit": print(str(convert_to_palindrome(user_input))) user_input = raw_input("string to check (exit to terminate): ")
true
de97068df6a27153b0389841500d36eb4a421d18
jfsharron/sharron-sphere
/sharron-sphere/gcd.py
1,491
4.34375
4
""" =============================================================================== Program: gcd.py Software Engineer: Jonas Sharron Date: 05-February-2020 Purpose: This script will calculate the gcd of two (user supplied) integers. =============================================================================== """ # print banner and instructions print("This program will calculate the gcd of two integers, please enter two") print("integers, the smaller one first and the gcd will be calculated") print("======================================================================") # gather user input small = input("Please enter the smaller of the two numbers: ") large = input("Please enter the larger of the two numbers: ") smallgcd = int(small) largegcd = int(large) # test to ensure user input is positive if smallgcd > 0 and largegcd > 0: # test to ensure user data is entered in the correct order if smallgcd > largegcd: print("ERROR: the first number entered is larger than the second") # Euclid's algorithm to calculate gcd else: while smallgcd > 0: # step 1 div = (largegcd%smallgcd) # step 2 largegcd = smallgcd smallgcd = div print("The gcd of " + small + " and " + large + " is " + str(largegcd)) else: print("ERROR: the numbers entered must be positive") # ============================================================================
true
198902fadef319e7b71b7d3b88acd16cdd572eb7
Nimish5/REST-API-With-Flask-and-Python-
/Section_5/Code3/tables.py
822
4.40625
4
# Section5: Storing Resouces in a SQL Database # Video-79 import sqlite3 connection = sqlite3.connect('database.db') cursor = connection.cursor() create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)" cursor.execute(create_table) # If you try to add a user into Users table/ database, it will through an error.(Try tob fix this) # user = ("Nimish", "ravimotu") # query = "INSERT INTO Users VALUES (NULL, ?, ?)" # cursor.execute(query, user) create_table = "CREATE TABLE IF NOT EXISTS Peoples (Name text, Money text, Luxury_Item text, Price real)" cursor.execute(create_table) people = ("Neha Pathak Rajvaidya", "All the money in the World!", "Home and Car", 100) query = "INSERT INTO Peoples VALUES (?, ?, ?, ?)" cursor.execute(query, people) connection.commit() connection.close()
true
84f0796798332d8a41a8c20dffb952b67ef080bb
chris-sun/open_source
/python/small_scripts/inheritance2.py
845
4.3125
4
#!/usr/bin/python # Basic example of inheritance in python class Employee: def __init__(self, name, salary = 0): self.name = name self.salary = salary def give_raise(self, percent): self.salary = self.salary + (self.salary * percent) def work(self): print self.name + " does stuff" def __repr__(self): return "Emp: name=%s, salary=%s" % (self.name, self.salary) class Chef(Employee): def __init__(self, name): Employee.__init__(self, name, 50000) def work(self): print self.name + " cooks food" class Athlete(Employee): def __init__(self, name): Employee.__init__(self, name, 5000000) def work(self): print self.name + " plays sports" e = Employee('Joe', 20000) c = Chef('Wolfgang') a = Athlete('Lebron') for o in [e, c, a]: print o e.work() c.work() a.work()
false
9c40565ac7fd15ff8b3105d6681047f6d551d8ad
mossseank/PythonSandbox
/collatz/collatz.py
2,589
4.15625
4
# Functions for calculating the stopping value for the collatz conjecture # More information on the collatz conjecture can be found at: https://en.wikipedia.org/wiki/Collatz_conjecture from time import perf_counter import numpy as np def collatz(start, limit=None): ''' Runs through the collatz sequence for the input value. :param start int: The non-negative input integer to calculate the collatz sequence for. :param limit int: The number of iterations to calculate before giving up, or `None` for no limit. :returns tuple: (stop, limit_reached, evens, odds, time) - stop (int): the number of iterations before reaching 1 or the limit - limit_reached (bool): `True` if there was a limit and it was reached, `False` otherwise - evens (int): the number of even iterations in the sequence - odds (int): the number of odd iterations in the sequence - time (float): the time it took to calculate the collatz sequence, in milliseconds ''' start = int(start) if start < 1: return (-1, False, -1, -1, -1) if limit is not None: limit = int(limit) iter = 0 evens = 0 odds = 0 start_time = perf_counter() while start > 1 and (limit is None or iter >= limit): if start % 2 == 0: # even start = int(start // 2) iter += 1 evens += 1 else: # odd start = int(((3 * start) + 1) // 2) # Take a shortcut, make two steps at once because we can iter += 2 evens += 1 odds += 1 end_time = perf_counter() return (iter, limit is not None and start != 1 and iter == limit, evens, odds, (end_time - start_time) * 1000) def collatz_gen(start): ''' Generates the entire collatz sequence for an input, and returns it as a list. :param start int: The non-negative input integer to calculate the sequence for. :returns np.array: The sequence, including the original number, and 1. ''' start = int(start) if start < 1: return np.array([-1]) seq = [] current = start while current > 1: seq.append(current) if current % 2 == 0: current = int(current // 2) else: current = int((3 * current) + 1) seq.append(1) return np.array(seq) if __name__ == '__main__': for i in range(1, 1001): coll = collatz(i) print ('collatz({}) = {}\t\t({}, {}, {})'.format(i, coll[0], coll[2], coll[3], coll[4]))
true
508491b94a46b8f0d433eb7b8208264b074b581f
Vadiwoo/Python
/For Loop/for_loop.py
1,379
4.5
4
print("\n********** Looping through a string **********") for x in "programming": print(x) print("\n********** Looping through a list **********") myList = list(("C", "C++", "Java")) for x in myList: print(x) print("\n********** break : Stopping a for_loop using **********") for x in myList: print(x) if x == "C++": break print("\n********** continue : skipping the current iteration and moving to next one **********") for x in myList: if x == "C++": continue print(x) print("\n********** range() : the range() function returns sequence of numbers from 0 to specified number(exclusive) " "**********") for x in range(5): print(x) print("\n********** range(x,y) : the range() function with two parameters **********") for x in range(2,6): print(x) print("\n********** range(x,y, z) : the range() function with three parameters **********") for x in range(20,100, 10): print(x) print("\n********** else keyword : specifies a block of code to be executed after the for loop **********") for x in range(20,100, 10): print(x) else : print("Nicely Done") # will not be executed if for loop exists with break statement print("\n********** Nested Loop **********") colors = ["red", "orange", "yellow"] score = list(("book", "pen", "bag")) for x in colors: for y in score: print(x, y) print("\n")
true
c137706386710142f7d1526a0a296ed116e6caad
adastraperasper/coding-with-bro
/while loop.py
396
4.34375
4
#while loop = a statement that will execute it's block of code, # as long as it's condition remains true #while 1==1 : # print("Help! I'm stuck in a loop !") #name="" #while len(name) == 0: # name = input("Enter your name: ") #print("Hello " + name ) name = None while not name: name = input("Enter your name :") print ("Hello"+ name)
true
32dee799d89d60ec39e9c279b0eab64bfb6993b7
adastraperasper/coding-with-bro
/logical operators bro.py
345
4.40625
4
# logical operators (and, or, not ) = used to check 2 or more conditionds are true temp = int(input("What is teh temperature outside ?:")) if not (temp >= 0 and temp <= 30): print("The temperature is good today!") print("Go outside") elif not (temp < 0 or temp >30): print("Temp is bad today") print("Stay inside")
true
64124a0d793849a43c3f72dbc5ba67bebfbdd38b
adastraperasper/coding-with-bro
/tuple bro.py
302
4.15625
4
#tuple = Collection which is is ordered and unchangeable # used to group together related data student = ("Bro",21,"male") print(student.count("Bro")) print(student.index("male")) for x in student: print(x) if "Bro" in student: print ("Bro is here! ")
true
ddd182edb02914c32de0b8407eaa2990071c37e8
adastraperasper/coding-with-bro
/string slicing bro.py
472
4.34375
4
#slicing = create a substring by extracting elements from another string indexing[] or slice() # undexing[] or slice() # [start:stop:step] name = "mitzi the best ever " first_name = name[:3] last_name = name[4:] funky_name = name[0:8:2] reversed_name = name[::-1] print(first_name) print (last_name) print(funky_name) print(reversed_name) website1 = "http://google.com" website2 = "http://wikipedia.com" slice = slice(7,-4) print(website1[slice])
true
de4c870695fdfb0ded5a499f7f13da6d95112ab5
nishank04/Python_Full_Course
/demo/HelloWorld.py
963
4.28125
4
print("Hello, World") print(1 + 2) print(7 * 6) print() print("The end", "or is it?", "Keep learning more about python") splitString = "This string has been \nsplit over \nseveral \ntimes" print(splitString) tabbedString = "1\t2\t3\t4\t5" print(tabbedString) print('The pet shop owner said "No, no, \'e\'s uh,.,.he\'s resting".') print("The pet shop owner said \"No, no, 'e's uh,...he's resting\"") print("""The pet shop owner said "No, no, 'e's uh,...he's resting".""") anotherString = """This string has been \ split over \ several \ lines""" print(anotherString) print("C:\\Users\\nishank\\notes.txt") a = 12 b = 3 print(a + b) print(a - b) print(a / b) #it gives floating data type print(a * b) print(a // b) # it gives int data type print(a % b) print() print(a + b / 3 - 4 * 12) print(a + (b / 3) - (4 * 12)) print((((a + b) / 3) - 4) * 12) print(((a + b) / 3 -4) * 12) c = a + b d = c / 3 e = d - 4 print(e * 12) print() print(a / (b * a) / b)
false
94a94fa75ddc31c9247af0e824f22d8066209ebe
YiLinLiu123/imageFiltering
/LearningNumPy.py
1,428
4.375
4
#trying things out import numpy as np # used to import numpy library, as... assigns a local name import matplotlib as mpl import scipy as sp print ("hello world") a = np.array( [[1,2],[3,4]], dtype = complex) #example call to the np.array method to create arrays print (a) # first create structured data type dt = np.dtype([('age',np.int8)]) #describes how bytes is fixed, ordering and interpretation #essentially allows yout ot define your own data type print(dt) b = np.array([(10,),(20,),(30,)],dtype=dt) print(b) #Better example of dtype: #A structured data type containing a 16-character string (in field ‘name’) # and a sub-array of two 64-bit floating-point number (in field ‘grades’): dt = np.dtype([('name',np.unicode_,16), ('grades', np.float64, (2,))]) x = np.array([('John', (6.0, 7.0)),('Sarah', (8.0, 7.0))], dtype=dt) print(x[1]) #MSD goes into least memort address print (x[1]['grades']) print (type(x[1])) print (type(x[1]['grades'])) # Shape function # displays the matrix information a = np.array([[1,2,3],[4,5,6]]) print (a.shape) # resizing the array a.shape = (3,2) print (a.shape) #array.ndim # one dimensional array: a = np.arange(24) a.ndim #now reshape the array b=a.reshape(2,4,3) print (b) #.itemsize: length of each element of array in bytes x = np.array([1,2,3,4,5], dtype = np.float32) print (x.itemsize) #numpy.flags gives osmeflags regarding objects, kinda cool
true
c6976228c14e6e2bcf230578a0d19717f441647c
chkling/digitalcrafts-03-2021
/week_2/day2/digitalPet.py
2,289
4.15625
4
# KEEPING YOURSELF ORGANIZED # define global functions and variables first at the top of your program # define Classes next and any unique methods inside of them # define your while loop if you need the user to keep doing tasks until a certain condition is met. Remember, your condition needs to be global, and needs to be re-assigned inside your while loop class Spider: def __init__(self, name, strength, defense, hp): self.name = name self.strength = strength self.defense = defense self.hp = hp def feedSpider(self): print("Omm nom nom") self.strength += 5 self.hp += 5 def playWithSpider(self): print("He's getting angry!") self.defense += 5 def howIsSpiderDoing(self): print("How are you doing spider?") print(self.name, self.strength, self.defense, self.hp) def smile(self): print(f"{self.name} smiled.") class OmegaSpider: def __init__(self, name, strength, defense, hp, size): self.name = name self.strength = strength self.defense = defense self.hp = hp self.size = size def smile(self): print(f"{self.name} smiled.") # Creating new instances of a spider/omega spider # Dot notation refers to us using the . and referencing something that exists on the class ( aka the # thing on the right we attached self to) peter = Spider("Peter", 20, 10, 100) carnage = OmegaSpider("Carnage", 100, 100, 100, "big") print(f"Peter's starting strength is {peter.strength}.") peter.feedSpider() peter.playWithSpider() print(f"Peter's ending strength is {peter.strength}.") peter.smile() carnage.smile() def welcomeMessage(): message = int(input(""" Please choose from the following: 1. Feed spider 2. Play with spider (he gets angry) 3. Check on spider 4. Stare 5. Quit """)) return message # choice = "" # while choice != 5: # choice = welcomeMessage() # if choice == 1: # # feedSpider() # pass # elif choice == 2: # # playWithSpider() # pass # elif choice == 3: # # howIsSpiderDoing() # pass # elif choice == 4: # # print("Staring......") # pass # else: # pass
true
93f87c58022dcd4d1c31d610604097e70ed4ec82
JamesFTCC/cti110
/Module 6/P5HW2_MathQuiz_JamesLeach.py
1,410
4.1875
4
# This program has the user add or subtract random numbers. # 11/5/19 # CTI-110 P5HW2 - Math Quiz # James Leach # Inputs whether the user would like to add, subtract, or exit. Then inputs their answer to the problem. # Calculates whether the users answer was correct. # Outputs if the user got the problem right or wrong. import random def main(): print('MAIN MENU') print('---------') print('1) Add Random Numbers') print('2) Subtract Random Numbers') print('3) Exit') quiz=int(input()) if quiz == 1: add_numbers() elif quiz == 2: subtract_numbers() def add_numbers(): x = random.randint(100, 999) y = random.randint(100, 999) correct = x + y print(' ', x) print('+', y) answer = int(input()) if correct == answer: print('Good Job! You got it right!') print('') main() else: print('Sorry, the correct answer was',correct) print('') main() def subtract_numbers(): x = random.randint(100, 999) y = random.randint(100, 999) correct = x - y print(' ', x) print('-', y) answer = int(input()) if correct == answer: print('Good Job! You got it right!') print('') main() else: print('Sorry, the correct answer was',correct) print('') main() main()
true
22f8bfcb9fdc1ec11e9f0b92fe7233e56e6b3c38
JamesFTCC/cti110
/Module 3/P2HW2_TurtleGraphic_JamesLeach.py
1,459
4.53125
5
# Using Turtle to draw a specific design # 9/10/19 # CTI-110 P2HW2 - Turtle Graphic # James Leach # Imports turtle which allows the program to draw the design import turtle # Increases the size of the pen in which the turtle draws with turtle.pensize(5) # Makes the "turtle" hidden so it can not be seen while drawing turtle.hideturtle() # Draws the outer edges of the design turtle.forward(150) turtle.right(45) turtle.forward(212.1) turtle.right(45) turtle.forward(150) turtle.right(90) turtle.forward(150) turtle.right(45) turtle.forward(212.1) turtle.right(45) turtle.forward(150) # Stops the turtle from drawing while moving to a position and then allows it to draw again once it is at the position turtle.penup() turtle.setpos(150,0) turtle.pendown() # Draws a vertical straight line down the center of the design turtle.right(180) turtle.forward(300) # Stops the turtle from drawing while moving to a position and then allows it to draw again once it is at the position turtle.penup() turtle.setpos(0,-150) turtle.pendown() # Draws a horizontal straight line through the center of the design turtle.left(90) turtle.forward(300) # Stops the turtle from drawing while moving to a position and then allows it to draw again once it is at the position turtle.penup() turtle.setpos(0,0) turtle.pendown() # Draws a diagonal line through the center of the design turtle.right(45) turtle.forward(424.2)
true
3aefccb0f2195796bdbbc742913ab0a951258788
dirghagarwal/python
/BMI_2.0.py
483
4.375
4
height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi = weight/(height**2) if bmi <= 18.5 : print(f"you bmi is {bmi}, you are underweight") elif bmi <=25 : print(f"you bmi is {bmi}you have a normal weight") elif bmi <= 30 : print(f"you bmi is {bmi}you are slightly overweight") elif bmi <= 35 : print(f"you bmi is {bmi}you are obese") else : print(f"you bmi is {bmi}you are clinically obese")
false
0e7beda92cf4d11c76e994789355016666048b2a
dirghagarwal/python
/gradeautomater.py
758
4.25
4
print("THIS PROGRAM WILL HELP YOU AUTOMATE THE GRADING SYSTEM") SUBJECT1 = float(input(" Please enter Marks: ")) SUBJECT2 = float(input(" Please enter score: ")) SUBJECT3 = float(input(" Please enter Marks: ")) SUBJECT4 = float(input(" Please enter Marks: ")) SUBJECT5 = float(input(" Please enter Marks: ")) total = SUBJECT1 + SUBJECT2 + SUBJECT3 + SUBJECT4 + SUBJECT5 percentage = (total / 500) * 100 print("Total Marks = %.2f" %total) print("Marks Percentage = %.2f"%percentage) if(percentage >= 90): print("A Grade") elif(percentage >= 80): print("B Grade") elif(percentage >= 70): print("C Grade") elif(percentage >= 60): print("D Grade") elif(percentage >= 40): print("E Grade") else: print("FaiL")
false
2631ca397f3e233500527a42e78898c35c2de894
houxianxu/An-Introduction-to-Interactive-Programming-in-Python-Coursera
/week2/mini_project2.py
2,323
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import random import simplegui # initialize global variables used in your code guess_range = 100 remain_guess = 7 secret_num = random.randrange(guess_range) # helper function to start and restart the game def new_game(): global guess_range, remain_guess, secret_num print "\n" print "new game, range is from 0 to ", guess_range-1 print "remaining guesses is ", remain_guess print "\n" # define event handlers for control panel def range100(): # button that changes range to range [0,100) and restarts global guess_range, remain_guess, secret_num guess_range = 100 remain_guess = 7 secret_num = random.randrange(guess_range) new_game() def range1000(): # button that changes range to range [0,1000) and restarts global guess_range, remain_guess, secret_num guess_range = 1000 remain_guess = 10 secret_num = random.randrange(guess_range) new_game() def input_guess(guess): # main game logic goes here global guess_range, remain_guess, secret_num remain_guess -= 1 guess = float(guess) print "Guess is ", guess print "the remaining guesses is", remain_guess if secret_num == guess: print "Correct!" if guess_range == 100: range100() elif guess_range == 1000: range1000() else: if secret_num > guess: print "Lower!" else: secret_num < guess print "Higher!" # whether useing up all the chance to guess if remain_guess == 0: print "Bad luck, you lose!" # restart the game accordingly if guess_range == 100: range100() elif guess_range == 1000: range1000() # create frame frame = simplegui.create_frame("Guessing number", 200, 200) # register event handlers for control elements frame.add_button("Range100", range100, 100) frame.add_button("Range1000", range1000, 100) frame.add_input("Inut guess", input_guess, 100) # call new_game and start frame frame.start() new_game() # always remember to check your completed program against the grading rubric
true
18db56187cee0d1024a2c1b66d43d2e10248cc3f
maciekgajewski/the-snake-and-the-turtle
/examples/tdemo_elementary/tdemo_yinyang_circle.py
721
4.21875
4
#!/usr/bin/python """ turtle-example-suite: tdemo_yinyang_circle.py Another drawing suitable as a beginner's programming example. The small circles are drawn by the circle command. """ from qturtle import * def yin(radius, color1, color2): width(3) color(color1) begin_fill() circle(radius/2., 180) circle(radius, 180) left(180) circle(-radius/2., 180) end_fill() color(color2) left(90) up() forward(radius*0.375) right(90) down() begin_fill() circle(radius*0.125) end_fill() left(90) up() backward(radius*0.375) down() left(90) reset() yin(200, "red", "green") yin(200, "green", "red") hideturtle() mainloop()
true
337f5ebd0a10d49106273d48f83b42de1aaeebf8
SparshGautam/If.....Else
/If...Else PT1.py
498
4.125
4
ant_weight = 1 #variable ant_weight assigns the value to 1 elephant_weight = 2000 #variable elephant_weight assigns the value to 2000 if elephant_weight > ant_weight: #the syntax of if is given here if 2000 is greater than 1 it will print elephant weight is more print("elephant weight is more") else: #the synatx of else statement print("ant weight is more") #here if 1 is greater than 2000 it will print ant weight is more
true
386fc9d57db22fb10a5a3dd20650fb5400f646ef
hannesthiersen/zelle-2010
/05-sequences/ex_5.8-caesar_cipher.py
2,040
4.46875
4
# File: caesar_cipher-progex5.8.py # Date: 2019-10-19 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Exercise: prog ex 5.8 # Description: # One problem with the previous exercise is that it does not deal with the # case when we "drop off the end" of the alphabet. A true Caesar cipher does # the shifting in a circular fashion where the next character after "z" is # "a." Modify your solution to the previous problem to make it circular. You # may assume that the input consists only of letters and spaces. Hint: make a # string containing all the characters of your alphabet and use positions in # this string as your code. Yo do not have to shift "z" into "a" just make # sure that you use a circular shift over the entire sequence of character in # your alphabet string. #------------------------------------------------------------------------------ # FUNCTIONS #------------------------------------------------------------------------------ def main(): print("Program encodes a Caesar cipher for a plaintext message.") alphabet = "abcdefghijklmnopqrstuvwxyz" alpha_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" message = input("Insert message: ").split() key = int(input("Insert cipher key (integer value): ")) emessage = [] for word in message: eword = [] for letter in word: if letter in alphabet: eword.append( alphabet[ (alphabet.find(letter) + key) % 26 ] ) elif letter in alpha_upper: eword.append( alpha_upper[ (alpha_upper.find(letter) + key) % 26 ] ) else: eword.append(letter) emessage.append("".join(eword)) print("Encoded message:", *emessage) #------------------------------------------------------------------------------ # MAIN #------------------------------------------------------------------------------ if __name__ == '__main__': main()
true
5c26f494f2b6d97eece7aacd365fd9c43cc8823a
hannesthiersen/zelle-2010
/04-objects_and_graphics/moving_circle-discuss4.3.py
1,253
4.25
4
# File: moving_circle-discuss4.3 # Date: 2019-09-28 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Exercise: discuss ex 4.3 # Description: # Describe what happens when the following interactive graphics program runs. # # Explanation: # The program draws a circle and move the center to where the user clicks. #----------------------------------------------------------------------------- # IMPORTS #----------------------------------------------------------------------------- from graphics import * #----------------------------------------------------------------------------- # FUNCTIONS #----------------------------------------------------------------------------- def main(): win = GraphWin("Moving Circle", 400, 400) shape = Circle(Point(50, 50), 20) shape.setOutline("red") shape.setFill("red") shape.draw(win) for i in range(10): p = win.getMouse() c = shape.getCenter() dx = p.getX() - c.getX() dy = p.getY() - c.getY() shape.move(dx, dy) win.close() #----------------------------------------------------------------------------- # MAIN #----------------------------------------------------------------------------- if __name__ == "__main__": main()
true
12109978adbf061c6d72e2bd2f41148e6b672894
hannesthiersen/zelle-2010
/03-computing_with_numbers/ex_3.16-fibonacci_sequence.py
1,096
4.53125
5
# File: fibonacci_sequence-progex3.16.py # Date: 2019-09-26 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Exercise: prog ex 3.16 # Description: # A Fibonacci sequence is a sequence of numbers where each successive number # is the sum of the previous 2. The classic Fibonacci sequence begins: # 1, 1, 2, 3, 5, 8, 13, ... . Write a program that computes the `n`th # Fibonacci number where `n` is a value input by the user For example `n`=6, # then the result is 8. #----------------------------------------------------------------------------- # FUNCTIONS #----------------------------------------------------------------------------- def main(): print("Calculate the `n`th Fibonacci number.") number = eval(input("Insert the number for `n`: ")) a, b = 1, 1 for _ in range(number-2): a, b = b, b + a print(f"Fibonacci({number}) =", b) #----------------------------------------------------------------------------- # MAIN #----------------------------------------------------------------------------- if __name__ == "__main__": main()
true
32bba7766c62e4254fdf2745b373f06ec0edc57e
hannesthiersen/zelle-2010
/03-computing_with_numbers/ex_3.11-sum_naturals.py
959
4.25
4
# File: sum_naturals-progex3.11.py # Date: 2019-09-26 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Exercise: prog ex 3.11 # Description: # Write a program to find the sum of the first `n` natural numbers where the # value of `n` is provided by the user. #----------------------------------------------------------------------------- # FUNCTIONS #----------------------------------------------------------------------------- def main(): print("Calculate the sum of all naturals numbers up to a given number.") number = eval(input("Enter a natural number: ")) total = number for i in range(number): total += i formula = (number+1)*number/2 print("The sum up to", number, "is", total, "or", formula) #----------------------------------------------------------------------------- # MAIN #----------------------------------------------------------------------------- if __name__ == "__main__": main()
true
2c003b436bd0a5fc2d157c2e585e189692ec67b1
hannesthiersen/zelle-2010
/03-computing_with_numbers/ex_3.9-triangle_area.py
1,138
4.25
4
# File: triangle_area-progex3.9.py # Date: 2019-09-26 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Exercise: prog 3.9 # Description: # Write a program to calculate the area of a triangle given the length of its # three sides a, b, and c using these formulas: # # s = (a + b + c)/2 # # A = sqrt(s*(s-a)*(s-b)*(s-c)) #----------------------------------------------------------------------------- # IMPORTS #----------------------------------------------------------------------------- import math #----------------------------------------------------------------------------- # FUNCTIONS #----------------------------------------------------------------------------- def main(): print("Calculate the area of a triangle.") a, b, c = eval(input("Enter triangle side lenghts comma separated: ")) s = (a + b + c)/2 A = math.sqrt(s*(s-a)*(s-b)*(s-c)) print("The triangle area is", A) #----------------------------------------------------------------------------- # MAIN #----------------------------------------------------------------------------- if __name__ == "__main__": main()
true
f42b534f558ab4710fe26e4da147ed266ea13a87
sunanth123/pypixelator
/src/blue.py
953
4.125
4
## this function is responsible for converting an image into blue scale. from PIL import Image def blue(im): ## get the dimensions and pixels from the original image and initialize ## a new image with the same size. size = im.size pixels = im.load() newImg = Image.new('RGB', size, 0) newPixels = newImg.load() ## Iterate through each pixel of the original image and then place the pixel ## in the same position for the new image. The new pixel is an average of ## the red,green,blue pixel values of the original image. The resulting ## average is then used as the new RGB values for the new pixel, while ## keeping the blue value at its max value fo 255. for y in range(size[1]): for x in range(size[0]): single_pixel=im.getpixel((x,y)) gray = (single_pixel[0] + single_pixel[1] + single_pixel[2])/3 newImg.putpixel((x,y),(gray,gray,255)) return newImg
true
54204517788ebe39aa4d39f8099517bb2ad0b3c4
Wraient/Python-Progarams
/022.string_formatting.py
205
4.40625
4
name = "Rushikesh" age = "16" #normal print("hello " + name + ", your age is " + age) #python 3 print("hello {}, your age is {}".format(name, age)) #python 3.6 print(f"hello {name}, your age is {age}")
false
e102c855c5bba894e0f68ab4c98f733c64479367
Wraient/Python-Progarams
/162.advance.min.max.py
552
4.15625
4
names = ["Harshit", "Mohit Vashisth", "z", "ab"] maxu = max(names, key = lambda name : len(name)) print(maxu) students = { "harshit" : {"score":90, "age":24}, "mohit" : {"score":75, "age":19}, "rohit" : {"score":76, "age":23} } maxu2 = max(students, key = lambda name : students[name]["score"]) print(maxu2) students2 = [ {"name":"harshit", "score":69, "age":24}, {"name":"mohit", "score":70, "age":19}, {"name":"rohit", "score":60, "age":23} ] maxu3 = (max(students2, key = lambda item : item.get("score"))["name"]) print(maxu3)
false
441c6f93ef834c8dd43435d22e5fec96e24d8c07
sng0616/practice
/online_challenges/findPi.py
550
4.46875
4
#Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. Source: https://github.com/karan/Projects import math nInput = raw_input("How many decimal places of pi? ") while nInput.isdigit() == False: print "That is not a number." nInput = raw_input("Please submit a number. ") if nInput.isdigit() == True: inputDigit = int(nInput) + 2 actualPi = str(math.pi)[2:inputDigit] print "Pi to the nth place where n = {0}: 3.{1}" .format(nInput, actualPi)
true
fc33370389939772e9733a75cece6eb03666934e
btruck552/100DaysPython
/Module1/Day02/module1_day02_printing.py
1,810
4.625
5
""" Author: CaptCorpMURICA Project: 100DaysPython File: module1_day02_printing.py Creation Date: 6/2/2019, 8:55 AM Description: Learn the basics of a print statement """ # The print statement can be used to display strings. print("Hello World") # You can also concatenate strings within a print statement. print("Hello" + " " + "World") # By using multiplication, you can repeat a string a specific number of times. print("Rudy " * 5) # You can also add newlines and tabs into your print statement. print("Ew\n\tWhat do you mean 'Ew'? I don't like spam.") # Print statements aren't just for strings. You can also complete arithmetic operations. print(1 + 1) # But can you combine strings and integers in the same print statement? print("This is the answer to life, the universe, and everything: " + 42) # Now try this instead. print("This is the answer to life, the universe, and everything: " + str(42)) # This is how you implement [string replacement formatting](https://pyformat.info/). As you can see, by using this # method, you do not need to convert integers into strings in order to add it to this print statement. print("The number of the {} shall be {}. No more. No less".format("counting", 3)) # Instead of using string replacement formatting, you can also use formatted string literals # (or [f-strings](https://docs.python.org/3/refernce/lexical_analysis.html#f-strings) for short). print(f"The number of the {'counting'} shall be {3}. No more. No less") # The replacements can also be done using integer locations. # As a note:_Python starts counting at 0. The integers provide the location within the format() method in which to use # for replacement. print("The number of the {1} shall be {0}. No more. No less".format(3, "counting"))
true
338733b141306bb2d4f9836be4c6b36973c9e3e0
bizhan/project1
/function/lambdas.py
1,720
4.15625
4
#add_values = lambda x, y : x+ y #add_values(10,20) #map #takes two arguments, a function and an iterable #map objects could be iterated only once. nums = [1,2,3,4,5] doubles = map(lambda x: x*2, nums) print(list(doubles)) print(list(doubles))#empty people = ["Darcy",'christine','Dana','Annable'] print(list(map(lambda name: name.upper(), people))) def decrement_list(lst): return list(map(lambda x: x -1 , lst)) print(decrement_list(nums)) #filter #There is a lambda for each value in the iterable #Returns filter object which can be converted into other iterables #The object contains only the values that return true to the lambda l = [1,2,3,4,5] evens = list(filter(lambda x: x % 2 == 0 , l))# returns only True values evens = list(map(lambda x: x % 2 == 0 , l)) print(evens) names = ['austin','penny', 'anthony','angel','billy'] print(list(filter(lambda name: name[0] == 'a', names))) users = [ {"username": "samuel", 'tweets': ["hello"]}, {"username": "katie", 'tweets': ["I love cat"]}, {"username": "bob123", 'tweets': []}, {"username": "doggo_luvr", 'tweets': ['dogs are best']}, {"username": "guitar", 'tweets': []}, ] print(list(filter(lambda user: not user['tweets'] ,users))) #combine map and filter print(list(map(lambda u: u['username'].upper(),filter(lambda user: not user['tweets'] ,users)))); #list comprehension #retuns a new list with #'Your instructor is ' + each value in the array, #but only if the value is less than 5 characters names = ['Lassie', 'Colt', 'Rusty'] [f"Your instructor is {name}" for name in names if len(name) <5] list(map(lambda name: f"Your instructor is {name}", filter(lambda value: len(value) < 5, names))) #all #return True if all elements of
true
e20ca996d6726a8e4a280b919e7f4ac6d3b74c6e
bizhan/project1
/iterator_generator/iterat.py
1,376
4.25
4
#iterator is not the samething as iterable #iter and next #build loop #generators #compare generators functions and generator expressions #use generators to pause execution of expensive functions #iterator: an object can be iterated upon. an object that # returns data, one element at a time when next() is called. #iterable; an object which will return an iterator when. iter() is called on it. # "HELLO" is an iterable, but it is not an iterator. # iter("HELLO") returns an iterator #next() is called on an iterator, the iterator returns # the next item. It keeps doing so until it raises an # Stopiteration error. #custom for loop it = iter([1,2,3]) print(next(it)) print(next(it)) print(next(it)) #print(next(it)) def my_for(iterable, func): it = iter(iterable) while True: try: thing = next(it) except StopIteration: break else: func(thing) #my_for([1,2,3,4,5,6,7,8]) #my_for('HELLO') my_for({'name': 'bizhan', 'last': 'jaffar'},print) class Counter: def __init__(self, low, high, increment=1): self.current = low self.high = high self.increment = increment def __iter__(self): return self def __next__(self): if self.current + self.increment <= self.high: num = self.current self.current += self.increment return num raise StopIteration for i in Counter(0,5,2): print(i)
true
583745734236574e250246c570593339243b3df9
jaflopes/liss
/python_tp/exec3_num_mais_peq.py
649
4.21875
4
# Exercício 3: # * 2520 é o número mais pequeno que pode ser dividido por todos os números de 1 até 10 sem resto de divisão. Qual é o # número positivo mais pequeno que é uniformemente divisivel por todos os números de 1 até 20? # Requisitos Exercício 3: # * O programa deve correr, efetuar os calculos e imprimir o resultado na consola. limit = 20 def greatest_common_factor(x, y): return y and greatest_common_factor(y, x % y) or x def least_common_multiple(x, y): return x * y / greatest_common_factor(x, y) i = 1 for item in range(1, limit): i = least_common_multiple(i, item) print("Resultado: " + str(int(i)))
false
9259ebc003bef59d5d9376be6f9dcb66bbcf463f
PremankuS/Premankur_Python_Chuck
/Homeworks_Related/First Course_Last Assignment.py
564
4.25
4
largest = None smallest = None while True: number = raw_input("Enter a number or enter 'done' to stop the script: ") if number == "done": break try: number = float(number) if smallest is None: smallest = number elif number < smallest: smallest = number if number > largest: largest = number except: print "Please enter only numbers! You can also enter 'done' to stop the script" continue print "the smallest and largest are:" print smallest print largest
true
920e1706b511f010771feaef5691a0c3e1e537f7
Cica013/Exercicios-Python-CursoEmVideo
/Pacote_Python/Ex_python_CEV/exe086.py
429
4.40625
4
# Crie um programa que cria uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. # No final, mostre a matriz na tela, com a formação correta. matriz = [[], [], []] for l in range(0, 3): for c in range(0, 3): matriz[l].append(int(input(f'Digite o número da parte [{l}, {c}] da matriz: '))) for l in range(0, 3): for c in range(0, 3): print(f' [{matriz[l][c]:^5}]', end='') print()
false
50934e39fea7fec14cd67156a9aef8e0ba536139
Cica013/Exercicios-Python-CursoEmVideo
/Pacote_Python/Ex_python_CEV/exe098.py
1,023
4.21875
4
# Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo. Seu # programa tem que realizar três contagem através da função criado: # a) De 1 até 10, de 1 em 1. # b) De 10 até 0, de 2 em 2. # c) Uma contagem personalizada. def linha(): print('*=' * 30) def contador(a, b, c): if a > b: for d in range(a, b - 1, c): print(d, end=' ') else: for d in range(a, b + 1, c): print(d, end=' ') print() print('FAZENDO A CONTAGEM DE NÚMEROS') linha() print('Primeiro de 1 até 10 de 1 em 1') contador(1, 10, 1) linha() print('Agora de 10 até 0 de 2 em 2') contador(10, 0, -2) linha() print('Agora é a sua vez!!!') n1 = int(input('Digite o início da contagem: ')) n2 = int(input('Digite agora até onde vai a contagem: ')) n3 = int(input('Digite de quantos em quantos ela tem que ir: ')) linha() print('Sua contagem:', end=' ') contador(n1, n2, n3) print('\033[1;31mFIM DO PROGRAMA, ATÉ A PRÓXIMA!\033[m')
false
8fa56e783c07d79b5d8f3652267d4448010ec6d7
Cica013/Exercicios-Python-CursoEmVideo
/Pacote_Python/Ex_python_CEV/exe063.py
413
4.1875
4
# Escreva um programa que leia um número inteiro n qualquer e mostre na tela os n primeiros termos de uma # sequência fibonacci. ex: 0 1 1 2 3 5 8 print('*'*30) n = int(input('Digite quantos termos você quer que apareça: ')) print('*'*30) n1 = 0 n2 = 1 print(f'{n1} -> {n2}', end='') cont = 3 while cont <= n: n3 = n1+n2 cont +=1 print(f' -> {n3}', end='') n1 = n2 n2 = n3 print(' FIM!')
false
ef051621ac427e2c31aec7b922afd31098fceb24
victorhpf97/Aula
/2-recursiva elevado.py
343
4.1875
4
## Implemente uma função recursiva que, dados dois números ## inteiros x e n, ## calcula o valor de x^n. x=int(input("Digite um numero para ser elevado: ")) n=int(input("Digite o valor para ele se elevar")) def função(n,x): if n == 0: return 1 else: return x * função(n -1,x) print(função(n,x))
false
ce0e89f0cfda8a2b12d28ab037561f99959feb25
RRichellFA/forca
/forca.py
1,884
4.21875
4
import getpass print("Jogo da forca") print('1- O desafiante digita o segredo da forca, ele ficará escondido, portanto certifique-se de digitar corretamente.') print('2- O jogador terá 5 chances de adivinhar o segredo, letra por letra. Se ele errar perde, se completar o ' 'segredo, ganha.') forca = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | / | | =========''', ''' +---+ | | O | /|\ | / \ | | ========='''] print("Vamos começar!") segredo = getpass.getpass("Digite o segredo da forca: ").strip().upper() print(forca[0]) erros = 0 acertos = 0 letras = [] letrascertas = [] print(f"O segredo escolhido tem {len(segredo)} letras.") while erros < 5 or acertos == len(segredo): jogador = input("Digite uma letra.")[0].upper() if jogador not in letras: letras.append(jogador) letras.sort() else: print("Essa letra ja foi escolhida.") continue if jogador in segredo: print("ACERTOU") acertos +=1 print(forca[erros]) letrascertas.append(jogador) print(f"As letras corretas escolhidas foram {letrascertas}.") if acertos == len(segredo): print("Parabéns, você venceu!") break else: print("ERROU") erros +=1 print(forca[erros]) print(f"Você tem mais {5-erros} tentativas.") if erros == 5: print(forca[6]) print(f'O segredo era "{segredo}"') print("Você perdeu!") print(f"As letras escolhidas foram {letras}.") print("FIM DO JOGO")
false
57229bcb2709a3059f08fa34184f1a48f8322747
abirami11/Programming-Questions
/rotation_substring.py
266
4.40625
4
# Check if the substring is a rotation substring of the given substring def isRotationSubstring(str1, str2): str3 = str1+str1 if str2 in str3: print "Yes, its a substring" else: print "no, its not a substring" isRotationSubstring("waterbottle","bottlwater")
true
47160b0ae702e4c85df104140b17c865dcd27873
ChaitanyaNimmagadda/Python
/Python Exercise 2 - Faulty Calculator.py
714
4.25
4
# Design a calculator which will correctly solve all the problems except the following ones: # 45 * 3 = 555, 56 + 9 = 77, 56 / 6 = 4 # Your program should take operator and two numbers as input from the user and then return the result print("enter first number") n1 = int(input()) print("enter second number") n2 = int(input()) #print("sum of these numbers",int(n1) + int(n2)) op=input("select operator like: +,*,-,/") if op=="*" and n1==45 and n2==3: print(555) elif op=="*": print(n1*n2) elif op=="+" and n1 ==56 and n2==9: print(77) elif op=="+": print(n1+n2) elif op=="-": print(n1-n2) elif op=="/" and n1==56 and n2==6: print(4) elif op=="/": print(n1/n2)
false
38f3a96810e36147098bcc31a56e4df1b5a26c7c
skwak0205/Python
/Python00/test01/type02.py
546
4.21875
4
# 문자 # single * 1 a = 'python \'s\nHello, World!' print(a) # single * 3 b = '''python's Hello,World! hello python! hello Qclass ''' print(b) # double * 1 c = "abc\"def\"ghi" print(c) # double * 3 d = """abc "def" ghi""" print(d) e = 'abc"def"ghi\npython\'s string' print(e) f = "abc'def'ghi\npython's string" print(f) # r(raw) string g = r"c:\test" print(g) h = "c:\test" print(h) # str 연산 str01 = "Hello, " str02 = "World!" print(str01 + str02) print(str01 * 3 + str02)
false
bb4d7dbea30d5f0f85c1e4f90e452552cfaf0b24
skwak0205/Python
/Python01/test03/mtest03.py
853
4.125
4
''' 1. for문을 사용하여 구구단 전체를 출력하는 gugu()라는 함수를 만들자. 2. while문을 사용하여 함수 호출시 입력된 단만 출력하는 gugudan(x)를 만들자 3. main 함수에서 gugu()와 gugudan(x) 함수를 호출하되, gugudan에 입력해주는 숫자는 input을 사용하자. ''' def gugu(): # pass 나중에 실행하겠다는 뜻 for i in range(2, 10): print('<<' + str(i) + '>>단') for j in range(1, 10): print('{} * {} = {}'.format(i, j, i*j)) def gugudan(x): print('<<'+ x + '>>단') for j in range(1, 10) : print('{} * {} = {}'.format(x, j, int(x)*j)) if __name__=='__main__': gugu() print('--------------------------------------') input = input('원하는 단을 입력해 주세요 : ') gugudan(input)
false
2d22e32d72f2912e95a6d056e16c6ca1a3858af2
rai8/python-crash-course
/if_statement.py
674
4.34375
4
#if is a conditional statement-- its basis is based on conditions #basic if statement is_male=False if is_male: print("You are a male") else: print("You are not a male") #complex if statement with two variables #if you want to apply both the two variable in your conditional statement-- #we use either the (and) or (or) keyword #we can also use --and not(variable) is_junkie=False is_foodie=True if is_junkie and is_foodie: print("You are a junkie foodie") elif is_junkie and not(is_foodie): print ("You are just normal") elif not (is_junkie) and is_foodie: print ("You are just a confused being") else: print("You are neither a foodie nor junkie")
true
ec86e600e68c3448a11932626134e3419ed72a1b
bhaskara09/Selection-Bubble
/Bubble.py
361
4.125
4
def bubbleSort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [60, 29, 31, 85, 20, 2, 4, 18, 38] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),
false
7513295a5dd806eb0ac1859d62918e293bc0f9dc
yunzhe99/UCSD_Python
/python_class2/shapes_files/dunder_point.py
1,552
4.15625
4
"""Point module consiting of 3-dimensional point code""" import math class Point: """Three-dimensional point.""" def __init__(self, xloc=0, yloc=0, zloc=0): self.xloc = xloc self.yloc = yloc self.zloc = zloc def shift(self, other): """Return copy of our point, shifted by other.""" return Point( self.xloc + other.xloc, self.yloc + other.yloc, self.zloc + other.zloc ) def scale(self, value): """Return new copy of our point, scaled by given value.""" return Point( value * self.xloc, value * self.yloc, value * self.zloc ) def distance(self, other): """Return distance between two points.""" xloc = self.xloc - other.xloc yloc = self.yloc - other.yloc zloc = self.zloc - other.zloc return math.sqrt(xloc**2 + yloc**2 + zloc**2) def __repr__(self): """Return dev-readable representation of Point.""" return "Point({}, {}, {})".format(self.xloc, self.yloc, self.zloc) def __add__(self, other): """Return new copy of our point, shifted by other.""" return Point( self.xloc + other.xloc, self.yloc + other.yloc, self.zloc + other.zloc ) def __mul__(self, value): """Return new copy of our point, scaled by given value.""" return Point( value * self.xloc, value * self.yloc, value * self.zloc )
true
63adec747704a5f8cfc0896db788d611dbd0e2d6
PDXDevCampJuly/atifar
/pre_assignment_stuff/primes.py
2,224
4.5625
5
# This script calculates the prime numbers no larger than an upper bound, # which is provided as an integer argument. The primes are written to a file, # one on each line. The output filename is also provided as an argument. import argparse from math import floor, sqrt # This is the function that calculates and outputs the prime numbers. def calc_primes(max_prime): """ Calculate and print primes at most as large as max_prime. Assumes max_prime is at least 7. :param max_prime: int :return: list of int """ # Initialize the list to hold the primes primes = [2, 3, 5] # Loop through the numbers in the form of 7 + 6n up to max_prime for num in range(7, max_prime + 1, 6): # Screen out all numbers that when divided by 6 provide a remainder other than 1 or 5 if is_prime(num, primes): primes.append(num) if is_prime(num + 4, primes): primes.append(num + 4) # Remove last element of primes list if that exceeds the upper bound if primes[-1] > max_prime: primes.pop() return primes def is_prime(num, primes): """ Returns True if num is prime. :param num: int :param primes: list of int :return: boolean """ prime_bound = floor(sqrt(num)) for p in primes: if p > prime_bound: break if not(num % p): return False return True def writePrimes(primes, out_file_name): """ Create output file and write primes into it each one on a separate line. :param priems: list :param out_file_name: file :return: None """ with open(out_file_name, "w") as oFile: for p in primes: oFile.write("{}\n".format(p)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-o", "--outputfile", help="output file name", default="primes.txt") parser.add_argument("-m", "--max_prime", type=int, help="upper bound of primes", default=22) args = parser.parse_args() max_prime, out_file_name = args.max_prime, args.outputfile primes = calc_primes(int(max_prime)) # Create output file and write primes into it writePrimes(primes, out_file_name) # print(len(primes))
true
21b5a0b3d7d8ea80b5d621efdb17e17a5f70342d
HazoomExpert/DevExpert
/2class.py
2,943
4.21875
4
# 1. Create two variables name X and Y. # 2. Print “BIG” if X is bigger than Y . # 3. Print “small” if X is smaller than Y. x = 10 y = 20 if(x > y): print("Big") elif(x < y): print("small") # 1. Run a “for” loop 5 times. # 2. Print iteration number every time. for i in range(5): print(i) # 1. Create a variable and initialize it with a number 1-4. # 2. Create 4 conditions (if-elif) which will check the variable. # 3. print the season name accordingly: x = 3 if(x == 1): print("suumer") elif (x == 2): print("winter") elif (x == 3): print("fall") elif (x == 4): print("spring") # 1. how many times will the following loop run? # # 2. what will be printed last? print("The loop will run 10 times") print("56 will print last") # Create a program which uses input with the following: # 1. Ask user for his phone number # 2. Print the words “phone number” and the phone number the # user entered. def getphonenumber(): number = input("please provide your phone number..") print("phone number is: " + number) # Write a program with the following: # 1. Method named printHello() that prints the word “hello”. # 2. Method named calculate() which adds 5+3.2 and prints the # result. def printHello(): print("hello") def calculate(): print("5 + 3") # Write a program with the following: # 1. Method that receive your name and prints it. # 2. Method that receive a number, divide it by 2, and prints the # result. def getmyname(): myName = input("provide your name") print(myName) def dividenumber(): number = input("provide a number") print(number / 2 ) # Write a program with the following: # 1. Method that receive two numbers, add them, and return the # sum. # 2. Method that receive two Strings, add space between them, # and return one spaced string. def dividenumber(): numberone = input("provide a number") numbertwo = input("provide a number") return numberone + numbertwo def spacestring(): stringone = input("provide a string") stringtwo = input("provide a string") return stringone + " " + stringtwo # Create a nested for loop (loop inside another loop) to create # a pyramid shape: simbool = "#" for i in range (5): print(simbool) simbool = simbool + "#" # Write a program with the following: # 1. Method that gets a number from the user (using input). # 2. Method that receive the number from the first method, and # computes the sum of the digits the integer (e.g. 25 = 7, 2+5=7) def getnumber(): numberinput = input("Please insert a number...") return numberinput def calculate(): number = getnumber() div = 1 sum = 0 for digit in number: sum = sum + int(digit) div = div * 10 print(sum) calculate() getphonenumber() print(spacestring())
true
3c9ada7e095fcd9646f1400504ba37fdc50acf94
avi138/my_main_project
/AVI/calculater.py
1,608
4.1875
4
# def calculater(a,b,op): # if op=='+': # print("the sum of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a+b)) # elif op=='-': # print("the difference of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a-b)) # elif op=='*': # print("the multiplication of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a*b)) # elif op=='/': # print("the division of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a/b)) # def main(): # a=int(input("enter a 1 digit :")) # b=int(input("enter a 2 digit :")) # # c=int(input("enter a 3 digit :")) # operation=(input("what would you like to do? \n choose betwen +,-,*,/ :")) # calculater(a,b,operation) # if __name__=='__main__': # main() def calculater(a,b,c,op): if op=='+': print("the sum of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a+b)) elif op=='-': print("the difference of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a-b)) elif op=='*': print("the multiplication of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a*b)) elif op=='/': print("the division of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a/b)) elif op=='**': print("the square of "+ str(a) + " " + op + " "+str(b) + ' = '+ str(a**c)) def main(): a=int(input("enter a 1 digit :")) b=int(input("enter a 2 digit :")) c=int(input("enter a square :")) operation=(input("what would you like to do? \n choose betwen (+,-,*,**,/) :")) calculater(a,b,c,operation) if __name__=='__main__': main()
false
fabf6c413c1b6a485bf3d7b902b3986408ef1697
metalwmz/python_numpy_basics-_cripts
/linear_algebra.py
1,113
4.1875
4
#linear algebra #------------------------------------------------------------------ #importing the numpy module import numpy as np #creating the array objects a and b a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = np.array([[23,23,12],[2,1,2],[7,8,9]]) #dot product dot = np.dot(a,b) print("\nprinting the output of dot product:\n",dot) #vdot vdot = np.vdot(a,b) print("\n\nprinting the output of vdot product:\n",vdot) #inner inner = np.inner(a,b) print("\n\nprinting the output of inner function:\n",inner) #matmul matmul = np.matmul(a,b) print("\n\nprinting the output of matrix multiplication:\n",matmul) #linear algebric functions: #---------------------------------------------- #det det = np.linalg.det(a) print("\n\nprinting the determinant of the array object \"a\":\n",det) #solve function: #This function is used to solve a quadratic equation where values can be given in the form of the matrix. solve = np.linalg.solve(a,b) print("\n\nprinting the output:\n",solve) #inverse function: inv = np.linalg.inv(a) print("\n\nprinting the multiplicative inverse of the array object a:\n",inv)
true
3eb1c2d7dc44583c57d2fa40e59f604e47bcc48b
metalwmz/python_numpy_basics-_cripts
/array_iteration.py
749
4.375
4
#iterations can also be performed on the array i.e nditer is used to iterate over the given array using python standard iterator interface #importing the module import numpy as np #creating the array object a = np.array([[1,12,3,4],[14,15,16,1],[7,18,9,4]]) print("original array:") print(a) #iterating with for loop for x in np.nditer(a): print(x,end=" ") #creating the transpose matrix transpose_ = a.T print("\ntranspose array:") print(transpose_) #iterating the transpose using for loop for y in np.nditer(transpose_): print(y,end=" ") #copying the array element items b = a.copy(order="c") print("printing the copied array elements") print(b) #array values modification for z in np.nditer(a): z = z * 3 print(z,end=" ")
true
2ddbc1bdfb93590bcaf6abdd7c27f981e757df3e
hakalar/network_automation
/_python/project/basics/dictionary.py
888
4.375
4
student = {'name': 'John', 'age': 25, 'courses': ['Math','CompSci']} print(student['name']) print(student.get('name')) # calling non existant key print(student.get('phone')) print(student.get('phone', 'Not Found')) # add phone number, update name student['phone'] = '555-555' student['name'] = 'Jane' print(student['name']) # add phone number, update name all at once student.update({'name': 'Jane', 'age': 26, 'phone': '555-5557'}) # delete key and its value del student['age'] # deletes and returns age and value age = student.pop('age') # looping through dictionary - returns 3, because we have 3 keys print(len(student)) print(student.keys()) print(student.values()) # return pairs - keys and values print(student.items()) # looping through dictionary for key in student: print(key) # looping through dictionary for key, value in student.items(): print(key, value)
true
193aa5bc4e5378a0fc483e96a41947d5fd83c563
jcammmmm/10_days_of_statistics
/tools/p_viz.py
321
4.28125
4
# A Python program to print all # permutations using library function from itertools import permutations # Get all permutations of [1, 2, 3] l1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'] l2 = ['A', 'B', 'C', 'D', 'E'] perm = permutations(l2) # Print the obtained permutations for i in list(perm): print(*i)
true
eadb3a3bf243c9118c3ee7866829f6e308012912
Haitianisgood/exercises
/Test/if_test.py
265
4.15625
4
#coding=utf8 num = 9 if num >= 0 and num <= 10: print '0<x<10' num = 10 if num < 0 or num > 10: print 'min 0 or max 10' else: print 'undefine' num = 8 if (num >= 0 and num <=5) or (num >= 10 and num <= 15): print '0<x<8 or 10<x<15' else: print 'undefine'
false
c6624bcede3bf4b11c2bcdc5cba71639f42f063d
simchuck/coding_exercises
/coding/sumproduct.py
1,674
4.25
4
def sumproduct(list1, list2): """ Returns the sum of products of corresponding items from the given lists. """ if not len(list1) == len(list2): raise IndexError return sum([item1*item2 for item1, item2 in zip(list1, list2)]) if __name__ == '__main__': list1 = range(5) list2 = range(5) print(sumproduct(list1, list2)) # Tests ----------------------------------------------------------------------- import pytest def test_different_size_lists(): """ Test that providing different size lists returns an IndexError """ list1 = [1, 2, 3] list2 = [1, 2] expected = IndexError with pytest.raises(expected) as e_info: result = sumproduct(list1, list2) def test_non_numeric_list(): """ Test that providing a non-numeric list returns a TypeError """ list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] expected = TypeError with pytest.raises(expected) as e_info: result = sumproduct(list1, list2) def test_empty_lists(): """ Test that empty lists returns zero result. """ list1 = [] list2 = [] expected = 0 result = sumproduct(list1, list2) assert result == expected def test_zero_lists(): """ Test that lists with zero-values returns zero result. """ list1 = [0, 0, 0] list2 = [0, 0, 0] expected = 0 result = sumproduct(list1, list2) assert result == expected def test_simple_scalar(): """ Test that one list with repeated values results in scalar sum. """ list1 = [1, 2, 3, 4, 5] list2 = [2] * 5 expected = 30 result = sumproduct(list1, list2) assert result == expected
true
008a6513ddb01580c5d27b9c62f8c2c1cee28667
Hyunjae-r/The-python-workbook-solutions
/ex91.py
415
4.625
5
def precedence(operator): operator = operator.strip() if operator[0] == '+' or operator[0] == '-': return 1 elif operator[0] == '*' or operator[0] == '/': return 2 elif operator[0] == '^': return 3 else: return -1 operator = input('Enter the operator: ') res = precedence(operator) if res == -1: print('The input was not an operator') else: print(res)
true
c6b6171ffb4173456b433cbd326317497e80eb61
Hyunjae-r/The-python-workbook-solutions
/ex89.py
630
4.15625
4
def capitalize(string): string = list(string) first = True for i in range(len(string)): if first == True and 'a' <= string[i] <= 'z': string[i] = string[i].upper() first = False else: if string[i] == 'i': if string[i-1] == ' ' and string[i+1] == ' ': string[i] = string[i].upper() elif string[i] == '.' or string[i] == '?' or string[i] == '!': first = True return string string = input('Enter the string: ') string = capitalize(string) for i in range(len(string)): print(string[i], end='')
true
b645ec5d333e68ce3a77f4da9f7ac0e8dcc73337
Hyunjae-r/The-python-workbook-solutions
/ex46.py
746
4.28125
4
month = input('Enter the name of the month: ') date = int(input('Enter the date: ')) month = month.title() """MONTH = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] for month in MONTH: for date in range(1, 32): print(f'{month} {date} ', end='')""" if (month == 'March' and date >= 20) or month == 'April' or month == 'May' or (month == 'June' and date < 21): print('Spring') elif month == 'June' or month == 'July' or month == 'August' or (month == 'September' and date < 22): print('Summer') elif month == 'September' or month == 'November' or month == 'October' or (month == 'December' and date < 21): print('Fall') else: print('Winter')
true
c0913960eafc1cd3ffd057aa800a6489c5651dad
sarae17/2019-T-111-PROG
/assignments/dictionaries/name_number.py
686
4.28125
4
def enter_data(the_dict): ''' Enters data input by user into the_dict ''' name = input("Name: ") number = input("Number: ") the_dict[name] = number def dict_to_tuple(the_dict): ''' Returns a list of tuples contains the key-value pairs in the_dict''' dictlist = [] for key, value in the_dict.items(): temp = (key,value) dictlist.append(temp) return dictlist def more_data(): more = input('More data (y/n)? ') return more.lower() == 'y' # Main program starts here the_dict = {} go_again = True while go_again: enter_data(the_dict) go_again = more_data() dictlist = dict_to_tuple(the_dict) print(sorted(dictlist))
true
1fe22b8e52c4df3f0cb2d6ac3cd29c22b0b5dc19
sarae17/2019-T-111-PROG
/assignments/sets/common.py
680
4.21875
4
def common_letters_list(first_str, last_str): '''Return a list of common letters in first_str and last_str.''' common = [] for ch in first_str: if ch in last_str and ch not in common: common.append(ch) return common def common_letters_set(first_str, last_str): '''Return a set of common letters in first_str and last_str.''' set1 = set(first_str) set2 = set(last_str) return set1 & set2 # Main program starts here name = input("Enter name: ").lower() first, last = name.split() common_list = common_letters_list(first, last) common_set = common_letters_set(first, last) print(sorted(common_list)) print(sorted(common_set))
true
360c35dd1b2fea0b513a05e63335081856f134f0
sarae17/2019-T-111-PROG
/assignments/algorithms/sequency.py
1,050
4.21875
4
# Design an algorithm that generates the first n numbers in the following sequence:; 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, … # The number n is entered by the user. Each member of the sequence is written in a separate line. # Implement the algorithm in Python. Put your algorihmic description as a comment in the program file. # Algorithm: # Read the length of the sequence, n, from the user. # Loop from 1 to n: # # At step 1: set current = first = 1 # At step 2: set current = second = 2 # At step 3: set current = third = 3 # At each step i > 3 # add first, second and third to produce the current element # let first = second, second = third, third = current. # # print curent # n = int(input("Enter the length of the sequence: ")) for i in range(1, n+1): if i == 1: current = first = i elif i == 2: current = second = i elif i == 3: current = third = i else: current = first + second + third first, second, third = second, third, current print(current)
true
32102d490eaf01579a5fdfd91f758f8e60ddd1d3
sarae17/2019-T-111-PROG
/exams/midterm2/list_set.py
1,018
4.125
4
def unique_elements(a_list): ''' Returns a new list containing the unique elements in a_list ''' result = [] for elem in a_list: if not elem in result: result.append(elem) return result def make_sorted_set(a_list): a_set = unique_elements(a_list) return sorted(a_set) def intersection(set1, set2): result_set = [] for elem in set1: if elem in set2: result_set.append(elem) return result_set def union(set1, set2): result_list = set1 + set2 result_set = make_sorted_set(result_list) return result_set def get_set(): a_list = input("Enter elements of a list separated by space: ").strip().split() a_list = [int(i) for i in a_list] return make_sorted_set(a_list) # Main program starts here set1 = get_set() set2 = get_set() print("Set 1: {}".format(set1)) print("Set 2: {}".format(set2)) set3 = intersection(set1, set2) print("Intersection: {}".format(set3)) set4 = union(set1, set2) print("Union: {}".format(set4))
true
cc67a84836d061a26cb5db4b31ec0f9ccaee6096
sarae17/2019-T-111-PROG
/projects/p2/int_seq.py
475
4.21875
4
num = int(input("Enter an integer: ")) largest = 0 evens = 0 odds = 0 cum_total = 0 while num > 0: if num > largest: largest = num if num % 2 == 0: evens += 1 else: odds += 1 cum_total = cum_total + num print("Cumulative total:",cum_total) num = int(input("Enter an integer: ")) if largest != 0: print("Largest number:", largest) print("Count of even numbers:", evens) print("Count of odd numbers:", odds)
false
20e6d1250845aee4319f4a70af67dca71b6cd97d
Georgieboy68/ICTPRG-Python
/Script Writing/Teststopractice/seperatelinesarraycount.py
1,631
4.3125
4
#PYTHON ARRAYS/LISTS #3. Modify your above code to output the below on separate lines. # a. The first word # b. The 3rd word (if there are 3 or more words) # c. Every word excluding the first and last one (if there are 3 or more words) #Description. #prompt user to enter a string #parse the string and break into substrings using whitespace as a delimiter. #create a new list and copy each substring into it. #loop through the list and count the number of entries. #print count as number of words entered by user. #print the first entry in list #print the third entry in list #if there are 3 or more entries print the second to the last-1 entry in list # #BEGIN pseudo code # string1=input("Enter something") # copy string1 to list1 broken by whitespace # for count=0, index in list1 do # count++ # end for # print ("You entered ", count, " number of words") # print ("The first word you entered was > " list(1) # print ("The third word you entered was > " list(3) # newlist=list[1cls to 3]+list[4 to -1] # print ("The remaining words you entered were > " newlist) # #END pseudo code # # BEGIN program UserInput=input ("Enter a line of text > ") print ("You entered ", len(UserInput), " charactars") WordList=UserInput.split() NumWords=0 for index in WordList: NumWords+=1 print ("and ", NumWords, " Words") print ("The first word you entered was > ", WordList[0]) print ("The third word you was > ", WordList[2]) if NumWords >= 3: print ("and the remaining words you entered were > ", WordList[1:2], WordList[3:]) # END program
true
66fdd352325fc33d2b03f6521d05c54e7a8da197
Georgieboy68/ICTPRG-Python
/addingnonx.py
305
4.21875
4
#Write a program that keeps asking the user for a number, and adds it to a total. # Ensure that pressing x stops entering numbers. # Example: firstnum=input("Enter Number: ") sum=0 while firstnum != "x": sum=sum+int(firstnum) firstnum=input("Enter Number: ") print("Total: ",sum)
true
d85039c6396aab0dafbd9020a50b4321aaf4e4b1
Tim-Tadj/ComputingAlgorithmsAssignment2
/heaptest.py
2,618
4.125
4
import sys #defining a class max_heap for the heap data structure class max_heap: def __init__(self, sizelimit): self.sizelimit = sizelimit self.cur_size = 0 self.Heap = [0]*(self.sizelimit + 1) self.Heap[0] = sys.maxsize self.root = 1 # helper function to swap the two given nodes of the heap # this function will be needed for max-heapify and insertion # in order to swap nodes which are not in order (not satisfy max-heap property) def swapnodes(self, node1, node2): self.Heap[node1], self.Heap[node2] = self.Heap[node2], self.Heap[node1] # THE MAX_HEAPIFY FUNCTION def max_heapify(self, i): # If the node is a not a leaf node and is lesser than any of its child if not (i >= (self.cur_size//2) and i <= self.cur_size): if (self.Heap[i] < self.Heap[2 * i] or self.Heap[i] < self.Heap[(2 * i) + 1]): if self.Heap[2 * i] > self.Heap[(2 * i) + 1]: # Swap the node with the left child and call the max_heapify function on it self.swapnodes(i, 2 * i) self.max_heapify(2 * i) else: # Swap the node with right child and then call the max_heapify function on it self.swapnodes(i, (2 * i) + 1) self.max_heapify((2 * i) + 1) # THE HEAPPUSH FUNCTION def heappush(self, element): if self.cur_size >= self.sizelimit : return self.cur_size+= 1 self.Heap[self.cur_size] = element current = self.cur_size while self.Heap[current] > self.Heap[current//2]: self.swapnodes(current, current//2) current = current//2 # THE HEAPPOP FUNCTION def heappop(self): last = self.Heap[self.root] self.Heap[self.root] = self.Heap[self.cur_size] self.cur_size -= 1 self.max_heapify(self.root) return last # THE BUILD_HEAP FUNCTION def build_heap(self): for i in range(self.cur_size//2, 0, -1): self.max_heapify(i) # helper function to print the heap def print_heap(self): for i in range(1, (self.cur_size//2)+1): print("Parent Node is "+ str(self.Heap[i])+" Left Child is "+ str(self.Heap[2 * i]) + " Right Child is "+ str(self.Heap[2 * i + 1])) maxHeap = max_heap(10) maxHeap.heappush(15) maxHeap.heappush(7) maxHeap.heappush(9) maxHeap.heappush(4) maxHeap.heappush(13) maxHeap.print_heap() for _ in range(5): x =maxHeap.heappop() print(x)
true
79c2cb4a0b31f051a8898c7e7ae084a4b687b952
fanieblesat/py_programs
/ex_03_03.py
684
4.21875
4
#User input sc= input("Please enter the score (A number between 0.0 and 1.0): ") try: sco=float(sc) except: print("Wrong input, please try again") quit() #Establishing a corresponding grade based on the entered score if sco>=0.9: if sco <=1.0: print("Congratulations! you got an A") else: print("Wrong score, please try again") elif sco>=0.8: print("Good work! you got a B") elif sco>=0.7: print("Not so bad. You got a C") elif sco>=0.6: print("You can do it better. Your grade is D") else: if sco>=0: print ("What happened? Your grade is F") else: print("Wrong score, please try again")
true
93aa15c32a27daed89f4e2a50b8ae553e2f0ded0
Chase124/Learning-Python
/RemoveSpaces.py
966
4.15625
4
#print('Could you please type in you birthday date?') #bday = input() #print(bday.split()) #Putting the string into a list separating elements using spaces as a refrence #print(bday.replace(" ", ""))#Replacing spaces with no space #print(bday.rstrip()) # getting rid of all the spaces at the end of sentence print('Could you please format the birthday dates to (ddmmyyyy), (dd/mm/yyyy) then (dd/mm/yy)?') bdaylist = ["12 01 2009","23 04 1999"," 23 03 2005"," 16 00 2022","350 6 2009"] for b in bdaylist: print(b.replace(" ", "")) breplaced = b.replace(" ", "") print (str(breplaced)) bsplitted = str(breplaced) print ("{}/{}/{}".format(bsplitted[0:2],bsplitted[2:4],bsplitted[6:8])) print ("{}/{}/{}".format(bsplitted[0:2], bsplitted[2:4], bsplitted[4:8])) # Check if day, month and year are valid # If they are print them as usual # else print a message saying which part of the date is incorrect
true
0732c439e22564b9a1469ecca120f9721e105b32
brandontkessler/data_structures
/array_structures/array_queue.py
2,329
4.25
4
from ..decorators import is_empty class ArrayQueue: '''FIFO queue implementation using a python list as storage''' DEFAULT_CAPACITY = 10 # for initial capacity of queue def __init__(self): '''Create empty queue.''' self._data = [None] * ArrayQueue.DEFAULT_CAPACITY self._size = 0 self._front = 0 # Index for front of queue def __len__(self): '''Return number of elements in queue.''' return self._size @is_empty def first(self): '''Return but not remove element at front of queue Raise Empty if queue is empty. ''' return self._data[self._front] @is_empty def dequeue(self): '''Remove and return first element of queue (FIFO) Raise Empty if queue is empty. ''' answer = self._data[self._front] self._data[self._front] = None # This is how we 'pop' from the queue self._front = (self._front + 1) % len(self._data) # set index to next val self._size -= 1 return answer def enqueue(self, e): '''Add element to back of queue''' if self._size == len(self._data): self._resize(2 * len(self._data)) # Double size of array if capacity is full avail = (self._front + self._size) % len(self._data) # avail gets to next 'None' in queue which could be a wrap around back to index 0. # Ex. if capacity (len(self._data)) is 10, front is at 8 and size is 2, that means # our list will be None for all except indexes 8 and 9 which are the last two # places in the 10 cap list. (8 + 2) % 10 = 0 meaning it wraps back to the # initial element in the list at 0. # [None, None, ..., 'something', 'here'] will turn into: # ['added', None, ..., 'something', 'here'] self._data[avail] = e self._size += 1 def _resize(self, cap): '''Resize to a new list of greater capacity''' old = self._data self._data = [None] * cap walk = self._front for k in range(self._size): self._data[k] = old[walk] # shift indeces back to 0 walk = (1 + walk) % len(old) self._front = 0 # reset front since we shifted indeces to 0
true
73633457528772f6b4ff4ff5b15b4d83682fccc0
Cookiezi727/mrgallo
/tpw_solutions_34_38.py
2,799
4.34375
4
# Exercise 34 print("# This program will determine if an integer is even or odd. Integers only please.") integer = int(input("Please enter an integer: ")) if integer % 2 == 0: print(f"{integer} is even!") else: print(f"{integer} is odd") # Exercise 35 print("# This program will covert human years to dog years.") invalidInput = True while invalidInput: humanYears = float(input("Please enter the number of years: ")) if humanYears < 0: print("Please enter a postive number") invalidInput = True else: invalidInput = False if humanYears < 2: dogYears = humanYears * 10.5 print(f"{humanYears} human years is {dogYears} in dog years!") else: dogYears = (2 * 10.5) + (humanYears - 2) * 4 print print(f"{humanYears} human years is {dogYears} in dog years!") # Exercise 36 print("# This program will determine whether a letter is a vowel or a constanant, for those who don't know how to.") letter = str(input("Please input ONE letter: ").lower()) if letter == "y": print("\"Y\" is sometimes a vowel, sometimes a constanant.") elif letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u": print("This letter is a vowel") else: print("This letter is a constanant.") # Exercise 37 print("This program will determine the name of the shape based on the number of sides, up to 10. Integer values only") invalidInput = True while invalidInput: numOfSides = int(input("Please enter the number of sides: ")) if numOfSides <= 2 or numOfSides > 10: print("Invalid Input.") invalidInput = True else: invalidInput = False if numOfSides == 3: name = "Triangle" if numOfSides == 4: name = "Rectangle" if numOfSides == 5: name = "Pentagon" if numOfSides == 6: name = "Hexagon" if numOfSides == 7: name = "Septagon" if numOfSides == 8: name = "Octagon" if numOfSides == 9: name = "Nonagon" if numOfSides == 10: name = "Decagon" print(f"The name of a {numOfSides} sided shape is a {name}.") # Exercise 38 print("This program will determine the number of days based on the month given") validInput = False while not validInput: month = str(input("Please enter a month: ").lower()) if month == "january" or month == "march" or month == "may" or month == "july" or month == "august" or month == "october" or month == "december": days = "31" validInput = True elif month == "april" or month == "june" or month == "september" or month == "november" : days = "30" validInput = True elif month == "febuary": days = "28 or 29" validInput = True else: print("Please enter a valid month") validInput = False print(f"This month has {days} days.")
true
118a64713cc679334781b7378b6c62a9dd3e4049
jarydhunter/Cracking_the_code_interview
/Linked_lists.py
1,038
4.3125
4
# Personal implementation of a linked list, to be used in chapter 2 questions. class Node: def __init__(self, value = None): self.value = value self.next = None self.prev = None def __next__(self): if self.value == None: raise StopIteration return self.next def __iter__(self): return self class linkList: def __init__(self, head): self.head = head self.tail = head self.head.next = Node() self.head.prev = Node() def append(self, node): node.next = self.tail.next node.prev = self.tail self.tail.next = node self.tail = node def __next__(self): tmp = self.cur self.cur = self.cur.__next__() return tmp def __iter__(self): self.cur = self.head return self if __name__ == '__main__': n1 = Node(1) n2 = Node(2) n3 = Node(3) lnk = linkList(n1) lnk.append(n2) lnk.append(n3) for node in lnk: print(node.value)
false
e13feb0ccec6d0c386b919b0feed89832b8c0609
JiSaifu/PythonLab
/chapter4/chapter4.6.py
1,797
4.21875
4
# 4.6 内包表記 # 4.6.1 リスト内包表記 print('--- 4.6.1 ---') # 文法:[expression for item in iterable] number_list = [number for number in range(1, 6)] print(number_list) number_list = [number-1 for number in range(1, 6)] print(number_list) # 内包表記に条件を追加 # 文法:[expression for item in iterable if condition] a_list = [number for number in range(1, 6) if number % 2 == 1] print(a_list) rows = range(1, 4) cols = range(1, 3) for row in rows: for col in cols: print(row, col) cells = [(row, col) for row in rows for col in cols] for cell in cells: print(cell) for row, col in cells: print(row, col) # 4.6.2 辞書包括表記 print('--- 4.6.2 ---') # 文法:{key_item: value_item for item in iterable} word = 'letters' letter_counts = {letter: word.count(letter) for letter in word} print(letter_counts) print(set(word)) letter_counts = {letter: letter for letter in set(word)} print(letter_counts) # 4.6.3 集合内包表記 print('--- 4.6.3 ---') # 文法:{item for item in iterator} a_set = {number for number in range(1, 6) if number % 3 == 1} print(a_set) # 4.6.4 集合内包表記 print('--- 4.6.4 ---') # 普通の括弧での内包表記:ジェネレータ内包表記 # イテレータにデータを供給する方法の一つである number_thing = (number for number in range(1, 6)) print(number_thing) print(type(number_thing)) for number in number_thing: print(number) # ジェネレータはlist()関数でラッパすれば、 # リスト内包表記のように動作させることができる number_list = list(number_thing) print(number_list) # ジェネレータは一度しか実行できない number_thing = (number for number in range(1, 6)) number_list = list(number_thing) print(number_list)
false
aba4a8e388e3c10bb282618bf8eb4ba18a936e25
george21-meet/meet2019y1lab4
/lab4pt2.py
386
4.1875
4
#fruit=input("what kind of fruit am i sorting" ) #if fruit=="apple": # print("apples in bin 1") #elif fruit=="banana": # print("bananas in bin 3") #elif fruit=="orange": # print("oranges in bin 2") #else: # print("i dont recognize that fruit") num1 = 2 num2 = 3 num3 = 1 if num1 > num3: print('chocolate') elif num1 > num2: print('vanilla') else: print('strawberry')
false
0f63e295eb7d4f49d96ed44b444ad9caad3fd85b
Valdaz007/Python3
/05_BasicOperators.py
1,795
4.4375
4
# Basic Operators # Operators are done to Manupilates Values to get a Desirable Outcome. # Declaring And Initialising Number Variables a = 2; b = 10 # Arithmatic Operators print(f"a + b = {a + b}") # Add Denoted by + Symbol print(f"a - b = {a - b}") # Subtract Denoted by - Symbol print(f"a * b = {a * b}") # Multiply Denoted by * Symbol print(f"a / b = {a / b}") # Divide Denoted by / Symbol print(f"a % b = {a % b}") # Modulus - Gets the Remainder Denoted by % Symbol print(f"a // b = {a // b}") # Floor Division - Gets the Whole Number of the Divsion Denoted by // Symbol print(f"a ** b = {a ** b}") # Exponent Denoted by * Symbol input() #Comparison Operators print(f"a == b: {a == b}") # Compare if 'a' is Equal to 'b' print(f"a != b: {a != b}") # Compare if 'a' is Not Equal to 'b' print(f"a > b: {a > b}") # Compare if 'a' is Greater than 'b' print(f"a < b: {a < b}") # Compare if 'a' is Less than 'b' print(f"a >= b: {a >= b}") # Compare if 'a' is Greater than or Equal to 'b' print(f"a <= b: {a <= b}") # Compare if 'a' is Less than or Equal to 'b' input() # Assignment Operators # Add Variables 'a', 'b' and store Sum in variable 'a' a += b print(f"a = a + b => a += b: {a}") input() # Subtract Variables 'a', 'b' and store Difference in variable 'a' a -= b print(f"a = a - b => a += b: {a}") input() # Multiply Variables 'a', 'b' and store Product in variable 'a' a *= b print(f"a = a * b => a += b: {a}") input() # Divide Variables 'a', 'b' and store Quotient in variable 'a' a /= b print(f"a = a / b => a += b: {a}") input() a %= b print(f"a = a % b => a += b: {a}") input() a **= b print(f"a = a ** b => a += b: {a}") input() a //= b print(f"a = a // b => a += b: {a}") input()
true
4926d097dd38ba135fb40ebbdcff1de7bfd2afd1
Valdaz007/Python3
/06_Conditions.py
1,319
4.28125
4
# Conditions # Conditions Enables Program Decision Making. # Given a Condition and if the Conditions is Satisfied # a Block of Code will Execute else it will not. a = 2; b = 10 # If Statements # If Variable 'a' Equals Varialble 'b' then Execute Statement if a == b: print('a is equal to b.\n') # If Variable 'a' is Not Equals Varialble 'b' then Execute Statement if a != b: print('a is not equal to b.\n') # If Variable 'a' is Greater Than Varialble 'b' then Execute Statement if a > b: print('a is greater than b.\n') # If Variable 'a' is Less Than Varialble 'b' then Execute Statement if a < b: print('a is less than b.\n') input("Press Enter to Continue!\n") # If-Else Statement # If Variable 'a' Equals Varialble 'b' then Execute Statement Else Execute the Else Statement if a == b: print('a is equal to b.\n') else: print('a is not equal to b.\n') # If Variable 'a' is Less Than Varialble 'b' then Execute Statement Else Execute the Else Statement if a < b: print('a is less than b.\n') else: print('a is greater than b.\n') input("Press Enter to Continue!\n") # ElIf Statement if a == b: print('a is equal to b.') elif a > b: print('a is greater than b.') else: print('a is less than b.')
true
2a38237c4e98723077a477be33f2f29fdbad7c79
Valdaz007/Python3
/07_Loops.py
538
4.40625
4
# Loops # Loops allows for Executing BLock of Codes several times. # Given a Conditions a Statement can be Executed multiple times if satisfied. # Program to Print Hello, World 3x #! Rule to Self Don't Use While Loop Unless Neccessary Only Use the Pythonic Way of Looping! print("While Loop") # While Loop count = 3 while count > 0: print(f"{count}. Hello, World") count -= 1 input('\nPress Enter to Continue!\n') print("For Loop") # For Loops for i in range(3): print(f"{i}. Hello, World")
true
42c2d845239906399f15f9a57e3bfc4b2af5a7bc
Valdaz007/Python3
/03_Variables.py
744
4.1875
4
# Tuples # A Tuple consists of items seperated by a Comma (,) enclosed in Parenthesis (()). # The Main Difference between Tuples and Lists is that Lists are Mutable meaning # the Size and Values can be Changed while Tuples Cannnot thus they are Immutable. atuple = () # An Empty ValueTuple numtuple = (100, 200, 300, 450) # A Integer Value Tuple strtuple = ('Victor', 'Volsavai', '20161232') # A String Value Tuple mixtuple = ('abcd', 789, 'john', 70.2) # A Mixed Value Tuple print(atuple) print(numtuple) print(strtuple) print(mixtuple) input() # Wait for a Keyboard Event # Accessing Tuple Index print(numtuple[3]) print(strtuple[0]) print(mixtuple[1])
true
b2127244e4622b32d76276c7f4a25b0f6c3e88d7
JeremiahZhang/pybeginner
/_src/om2py0w/0wd3/tutor-4-7-4-arbitrary.py
1,356
4.25
4
# -*- coding: utf-8 -*- def write_multiple_item(file, separator, *args): # arbitrary argument Lists file.write(separator.join(args)) print '*' * 20 print range(3,6) print "this below is a list do you know?" args = [3, 6] print args print range(*args) print "can you see the meaning of this code above? yes" print '*' * 20 def parrot(voltage, state='a stiff', action='voom'): print "this parrot would not", action, print 'if you put', voltage, 'volts through it.', print 'E\'s', state, '!' d = {"voltage": "FOUR million", "state": "bleedin' demised", "action": "V00M"} parrot(d) parrot(**d) print """ ** operator can deliver keyword arguments in dictionaries""" print '*' * 20 print "lets know the lambda expressions" def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) print f(0) print f(1) print f(42) def make_sum(n): return lambda a, b: a + b + n ff = make_sum(42) print ff(0, 0) print ff(1, 1) print '*' * 20 pairs = [(2, 'two'), (1, 'one'), (3, 'three'), (4, 'four')] print pairs pairs.sort(key=lambda pair: pair[0]) # I think pair[0] mean the 1st value in lists print pairs # 此处就是按 list中的 ()中 第一位 value 排序 按数字 pairs.sort(key=lambda pair: pair[1]) # 此处 ()中 字母排序 abcde的顺序 print pairs print "print pair[1] display error: name 'pair' is not defined"
true
76283f742e7611f73e772cbb6a179cb7b238199d
SauravP52/Machine_Learning
/KNN.py
2,376
4.34375
4
#-----------------KNN.py----------------------------------# # # # Implementation of KNN Neighbors using Skikit- Learn$ # # #---------------------------------------------------------# """ Here we are using sklearn and mathplotlib library These can be downloaded using the command line code:- $~ pip install scikit-learn mathplotlib numpy """ from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt """ $ Under the KNeighboursClassifier is a class which exist under the sklearn.neighbors module we are going to use the KNeighbours Classifier algorithm to predict the outcome of our first machine learning model We will first load the iris dataset into a variable and then split our dataset into training and test dataset using the train_test_split function which exist inside the model_selection module """ #Argument of n_neighbors has been set to 1 this is the value of K in the Algorithm #you can set this as whatever pleases you knn= KNeighborsClassifier(n_neighbors=1) iris=load_iris() X_train, X_test ,y_train, y_test = train_test_split(iris['data'],iris['target'],random_state=0) knn.fit(X_train,y_train) print(knn.score(X_test,y_test)) """" ======================================== $ The code that follows is only a representation of the plot of the different features of the iris dataset you can omit this part as it has no link to the training model of our Machine Learning Hypothesis However it is highly recommended that you visualize the dataset by ploting it on the graph For more help type help(plt) ======================================== """ fig, ax = plt.subplots(3, 3, figsize=(15, 15)) plt.suptitle("iris_pairplot") for c in range(1): for i in range(3): for j in range(3): ax[i, j].scatter(X_train[:, j], X_train[:, i + 1], c=y_train, s=60) ax[i, j].set_xticks(()) ax[i, j].set_yticks(()) if i == 2: ax[i, j].set_xlabel(iris['feature_names'][j]) if j == 0: ax[i, j].set_ylabel(iris['feature_names'][i + 1]) if j > i: ax[i, j].set_visible(False) plt.show()
true
c7854d20a7dd6884ec5d6833eb33302e04ee8c01
keinuma/self-taught
/part2/books/chapter13.py
1,827
4.25
4
# カプセル化 class Rectangle: def __init__(self, w, l): self.width = w self.len = l def area(self): return self.width * self.len class Data: def __init__(self): self.nums = [1, 2, 3, 4, 5] def change_data(self, index, n): self.nums[index] = n class PublicPrivateExample: def __init__(self): self.public = 'safe' self._unsafe = 'unsafe' def public_method(self): # clientが使っても良い pass # pass文は、文必須な構文で省略する際に使用 def _unsafe_method(self): # clientが使うべきではない pass # 継承 class Shape: def __init__(self, w, l): self.width = w self.len = l def print_size(self): print('{} by {}'.format(self.width, self.len)) class Square(Shape): def area(self): return self.width * self.len def print_size(self): print('I am {} by {}'.format(self.width, self.len)) class Dog: def __init__(self, name, breed, owner): self.name = name self.breed = breed self.owner = owner class Person: def __init__(self, name): self.name = name def check_data_class(): data_one = Data() # numsがタプルに変更されるとエラーになる data_one.nums[0] = 100 print(data_one.nums) data_two = Data() data_two.change_data(0, 100) print(data_two.nums) def check_shape(): my_shape = Shape(20, 25) my_shape.print_size() a_square = Square(20, 20) print(a_square.area()) a_square.print_size() def check_person_dog(): mick = Person('Mick Jagger') stan = Dog('Stanley', 'Bulldog', mick) print(stan.owner.name) if __name__ == '__main__': check_data_class() check_shape() check_person_dog()
false
00c90e70d9cd1cc0826bb62c3c9f0b3970bc6b46
JasperLiang0130/python_practice
/mult_encrypt.py
1,939
4.1875
4
''' For KIT103/KMA115 Practical 7: Euclidean Algorithms and Applications Revised: 2018-09-11 Author: James Montgomery (james.montgomery@utas.edu.au) Multiplicative encryption and decryption functions to illustrate how they work. Can you see a way of having greater code reuse and a shorter implementation of decrypt? Has strings for lowercase and uppercase roman alphabet characters defined for convenience. ''' from string import ascii_lowercase as alphabet, ascii_uppercase as ALPHABET # s is a set def group_size(s): p = {gcd(a,b) for a in s for b in s if a>b} largest = min(p) return largest def gcd(a,b): while a>0: b,a=a, b % a return b def mult(s, key, size): return (s * key) % size def encrypt(message, key, symbols): '''Encrypts the given message using the given key; only characters in symbols are kept and encrypted.''' ciphertext = '' for c in message: if c in symbols: cIndex = symbols.find(c) ciphertext += symbols[ mult(cIndex, key, len(symbols)) ] return ciphertext def decrypt(cipher, key, symbols): '''Decrypts the given encrypted message using the given original encryption key.''' kinv = mod_inverse(key, len(symbols)) if kinv is None: print('Unable to decrypt message as key', key,\ 'and number of symbols', len(symbols), 'are not coprime') else: messagetext = '' for c in cipher: cIndex = symbols.find(c) messagetext += symbols[ mult(cIndex, kinv, len(symbols)) ] return messagetext def mod_inverse(a, b): '''Calculates and returns the multiplicative inverse of a mod b. Returns None if gcd(a, b) is not 1.''' u,v, x,y = 1,0, 0,1 while a != 0: q, r = divmod(b, a) b, a = a, r m,n = x - u*q, y - v*q x,y, u,v= u,v, m,n if b == 1: #at this point b = gcd(a, b) return x return None
true
647ed33ca61a5c5c1bc15fb653d569a2390297ff
rinkeshpanwar/datastructure
/selectionsort.py
1,270
4.15625
4
''' suppose we are having a array [10,5,7,20,40] take first index and check for lowest value in array such that value>index 5 is the smallest one so swap them [5,10,7,20,40] now go to index 2 and check which are the smallest value i array such that value[index]>index 7 is smallest so swap them [5,7,10,20,40] go until you didnt reach at n-1 index since last index will be highest value ''' def sortlist(li): for i in range(len(li)): if li[i] > min(li[i:]): swap_value = li[li.index(min(li[i:]))] swap_index = li.index(min(li[i:])) temp = li[i] li[i] = swap_value li[swap_index] = temp return li print(sortlist([23,89,90,96,897,12,0,1,-1,-234])) ''' Another way to do is A = [64, 25, 12, 22, 11] # Traverse through all array elements for i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test above print ("Sorted array") for i in range(len(A)): print("%d" %A[i]), '''
true
8b8af6bba1f4bdbf1aaa68b0c2770031c1e981b9
rinkeshpanwar/datastructure
/circularLinkesList.py
2,558
4.1875
4
class node: def __init__(self,data): self.data = data self.next = None class circularLinkedList: def __init__(self): self.head = None self.tail = None def insert(self,data): if self.head == None: temp = node(data) temp.next = temp self.head = temp self.tail = self.head print("First node is added") return 0 temp = node(data) self.tail.next = temp temp.next = self.head self.tail = temp print("added next node") return 0 def traverse(self): if self.head == None: print("Circular linked list is empty") return 0 pointer = self.head while True: print(pointer.data) pointer = pointer.next if pointer == self.head: return 0 return 0 def deleteDataNode(self,data): if self.head == None: print("Linked list is empty") return 0 if self.head.data == data: self.head = self.head.next self.tail.next = self.head print("Deleted Data at first Node") return 0 pointer = self.head while(pointer!=None): if pointer.next.data == data: if pointer.next == self.tail: pointer.next = self.tail.next self.tail = pointer print("Tail has been changed") return 0 temp = pointer.next pointer.next = temp.next del(temp) print("Data is deleted from linked list") return 0 pointer = pointer.next print("Data is not found in linked list") return -1 cll = circularLinkedList() while True: print("1.insert in circular linked list") print("2.Traverse in a circular linked list") print("3.Delete data from linked list") menuChoice = int(input("Eneter your choice->")) if menuChoice == 1: data = int(input("Enter data to be inserted")) returnValue = cll.insert(data) print("Return Value is->",returnValue) elif menuChoice == 2: returnValue = cll.traverse() print("return value is->",returnValue) elif menuChoice == 3: data = int(input("Enter data to be deleted")) returnValue = cll.deleteDataNode(data) print("return value is->",returnValue) else: break
true
7c09a6928e346d5155a385df692e215726f80b2b
rfahham/projetos
/python/projetos/2022/antecessor_sucessor.py
338
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print() print('{:-^40}'.format('')) print('{:-^40}'.format(' Cálculando o número sucessor e o antecessor ')) print('{:-^40}'.format('')) print() n = int(input('Digite um número: ')) print('Analisando o valor {}, seu antecessor é {} e o sucessor é {}' . format(n, (n-1),(n+1))) print()
false
05a7a16cb36491cb0a71009daa4149c14c93786f
sureshkandula/python-suresh-git
/conditional_statements/elif.py
534
4.3125
4
name ="suresh" if name == "shruthika": print("name is shruthika") elif name == "sirisha": print("name is correct and it is sirisha") elif name != "suresh": print("name is super correct and it is you Mr Kandula") elif name is ('name is {}'.format("suresh")): print("its a valid name my boy..you did it !!") """ name= {'fisrtname' :'suresh', 'age':8} lastname='kandula' print('firstname is {} and his age is {}'.format(name['fisrtname'],name['age'])) print('firstname is {} and his age is {}'.format('suresh',8)) """
true
13ace2ebe4bf647f89ac8e64710ebb093e30a0a5
sureshkandula/python-suresh-git
/Strings and Numbers/count-strip.py
1,294
4.25
4
string='my name is surESH kandula venkata' print (len(string)) a='a' "" print('count of a in the name:', string.count(a)) print('count of alphabets in a name:', string.count(a, 10, 20)) "" """" print('strip method') print('here is the strip for the string:', string.strip()) print('here is the rstrip for the string:', string.rstrip('venkata')) print('here is the lstrip for the string:', string.lstrip('my name')) """ """ print ('starts with :', string.startswith('my')) print('ends with :', string.endswith('venkata')) print ('starts with :', string.startswith('1my')) print('ends with :', string.endswith('venkataa')) """ ''' print('ljust rjust:', string.rjust(40, '*')) print('ljust ljust:', string.ljust(40, '*')) ''' ''' str = "Python0007" print(len(str)) print (str.rjust(20, '*')) print (str.ljust(25, '#')) ''' #print('centre of the string:', string.center(45,'a')) print('centre of the string:', max(string)) van = "ekjfdfkjdfklsd" print ("Min character: ",min(van)) print ("Max character: ",max(van)) van = "98509385698" print ("Min character: ",min(van)) print ("Max character: ",max(van)) van = "9850938#5698" print(string.title()) print(string.swapcase()) print(string.lower()) print(string.upper()) print(van.isdigit()) print(van.isdecimal()) print(van.isnumeric()) print(van.isalnum())
false
d826c9644f5c5e4f29baafbe9b23e543839ea74b
luis-e-alvarez/MIT-6.00.1x
/numberGuesser.py
847
4.125
4
# Paste your code into this box high = 100 low = 0 median = int((high+low)/2) print('Please think of a number between 0 and 100!') print('Is your secret number ' + str(median)+ '?') guess = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") while guess != 'c': if guess == 'h': high = median median = int((high+low)/2) if guess == 'l': low = median median = int((high + low) / 2) if guess != 'h' and guess != 'l': print('sorry, I did not understand your input') print('Is your secret number ' + str(median)+ '?') guess = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") print('Game over. Your secret number was: ' + str(median))
true
e9b86b7d76946ac4c59e6c50326bb342c0678e07
MychalCampos/Udacity_CS101_Lesson5
/make_hashtable.py
607
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 10 22:58:13 2015 # Creating an Empty Hash Table # Define a procedure, make_hashtable, # that takes as input a number, nbuckets, # and returns an empty hash table with # nbuckets empty buckets. @author: Mychal """ # your first attempt # def make_hashtable(nbuckets): # hashtbl = [] # i = 0 # while i < nbuckets: # hashtbl.append([]) # i = i + 1 # return hashtbl # better def make_hashtable(nbuckets): hashtbl = [] for unused in range(0, nbuckets): # goes from 0 to nbuckets-1 hashtbl.append([]) return hashtbl
false
1a9216c52d33274ed4ab19a84e0e1eaaf7871c09
yogeshrnaik/python
/linkedin/Ex_Files_Python_EssT/Exercise Files/Chap09/class.py
2,152
4.625
5
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def printSeparator(): print('*****************************************************************') class Duck: # This are class level variables. sound = 'Quack quack.' movement = 'Walks like a duck.' # first param of every method of class has to be reference to object # we can name it anything we want # but it is general practice to name it 'self' def quack(self): print(self.sound) def move(self): print(self.movement) def print_sound(duckName, duck): print(f'{duckName}.sound : {duck.sound}') def main(): print('Creating donald object of Duck class and calling its methods') donald = Duck() donald.quack() donald.move() printSeparator() donaldsBrother1 = Duck() print("Change sound in Duck class. " + "All sound variables in all objects of Duck class will change because of this...") # this changes the class level variable 'sound' # for all objects of Duck class created before this and any object created after this Duck.sound = "We sound like Donald" donaldsBrother2 = Duck() # Brother 2 will also have 'We sound like Donald' as sound print(f'Duck.sound: {Duck.sound}') print(f'donald.sound : {donald.sound}') print(f'donaldsBrother1.sound : {donaldsBrother1.sound}') print(f'donaldsBrother2.sound : {donaldsBrother2.sound}') printSeparator() print("Change sound for Donald's brother 1") # This changes sound only for Donald's brother 1 object donaldsBrother1.sound = "Donald's brother 1 sound" print(f'Duck.sound: {Duck.sound}') print(f'donald.sound : {donald.sound}') print(f'donaldsBrother1.sound : {donaldsBrother1.sound}') print(f'donaldsBrother2.sound : {donaldsBrother2.sound}') printSeparator() print('Type of class vs type of object of class') print(f'type(Duck) = {type(Duck)}') # <class 'type'> print(f'type(donald) = {type(donald)}') # <class '__main__.Duck'> print(f'type(donaldsBrother1) = {type(donaldsBrother1)}') # <class '__main__.Duck'> if __name__ == '__main__': main()
true