blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bca171ddf838b507a1e4350b8568b4ebb8e1371b
lura00/codeAlong
/main.py
1,243
4.40625
4
# Python - intro codealong # - Funktioner hello = 'This is a string inside a variable' universe = 42 bar = 1.25 foo = '42' space = ' .:. ' # print(type(hello)) # print(type(world)) # print(type(d)) # print('hello' + space + 'world' + space + str(bar)) # print(type(bar)) # skriv en funktionsdefinition som tar in en parameter # parametern består av en sträng som består av en fråga # funktionen ska ställa frågan till användaren # det användaren svarar skall konverteras till int eller float # samt returneras tillbaka till anropande kod def ask_user(prompt): #print(f'The function was called with argument {prompt}') s = input(prompt) #print(type(s)) return eval(s) def calculate_area (length): # Skriv en funktion som tar in en längd som argument # och returnera ytan av en kvadrat med denna längd area = length ** 2 return area answer = ask_user('please enter a length in meters: ') # print(f'The user answered {answer}') #s = eval(input('please enter a distance in cm: ')) # print(s) result = calculate_area(answer) print(f'The area av the squere is {result}') #area = s ** 2 # print('The area of a square with side ' + str(s) + # ' cm is equal to ' + str(area) + ' cm^2')
false
a43e82b529ad15126d1849ae9df7be3cdcf985b1
ssd2192/Python
/Calculate Total Price.py
819
4.28125
4
#This program calculate the total price #This program demonstrate for loops #the main function def main(): #A basic for loop print("I will display the number 1 through 5.") for num in [1,2,3,4,5]: print(num) #The second counter code for counter in range(1,61): print(counter) #The accumulator code total = 0 for counter in range(5): number = int(input("Enter a number: ")) total += number print("The total is ", total) #The Average Age code totalAge = 0 averageAge = 0 number = int(input("How many ages do you want to enter: ")) for counter in range(0, number): age = int(input("Enter an age: ")) totalAge += age averageAge = totalAge/number print("The average age is", averageAge) #calls main main()
true
42a8a1b7a05089a311266174c20349c03a97b929
Saifullahshaikh/LAB-04
/program 4.py
451
4.125
4
print('saifullah 18B-092-CS') print('Lab 4, Program4') # Python program to display all the prime numbers within an interval l_limit = int(input('Enter lower limit range:')) u_limit = int(input('Enter upper limit range:')) print('prime numbers between', l_limit,'and',u_limit,'are:') for number in range (l_limit,u_limit+1): if number > 1: for i in range(2,number): if(number%i)==0: break else: print(number)
true
6695089618b8e29f1607757edbf2a4b02e3852c6
rious16/Project-Demo
/bicycles.py
1,385
4.40625
4
#SR 6/17/19 - creating and modify lists '''bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0].title()) print(bicycles[1].title()) print(bicycles[-1].upper()) #append bicycles.append('schwin') print(bicycles) message_bike = f"My first bicycle was a {bicycles[-1].title()}." print(message_bike)''' cars = [] cars.append('honda') cars.append('toyota') cars.append('geo') cars.append('ford') cars.insert(0,'GMC') #popped '''popped_cars = cars.pop() print(cars) print(popped_cars) last_owned = cars.pop() print(f'The last car I owned was a {last_owned.title()}.') first_owned = cars.pop(0) print(f'The first car I owned was a {first_owned.title()}.') print(cars)''' #sort '''cars.remove('ford') print(cars) too_expensive = 'GMC' cars.remove(too_expensive) print(cars) print(f'\nA {too_expensive.upper()} is too expensive.')''' '''cars.sort() print(cars) cars.sort(reverse=True) print(cars)''' #sorted '''print("\nHere is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) ''' #reverse print(cars) cars.reverse() print(cars) #Looping using for for car in cars: print(f"The {car.title()} was very expensive,") #^needs to be indented?? print(f"because the {car} was so fast!\n")
false
c7754fc657d836d75acc7a21a62dbf3ffd485faf
kirbalbek/mipt_3sem_contest_pyth
/3cont_task6.py
373
4.1875
4
stri = input() max_num = 0 num_stri = str() for i in stri: if (i == "0" or i == "1" or i == "2" or i == "3" or i == "4" or i == "5" or i == "6" or i == "7" or i == "8" or i == "9"): num_stri+=i elif num_stri == '': stri = '' else: if int(num_stri) > max_num: max_num = int(num_stri) num_stri=str() print(max_num)
false
c6b46736a832b0d30d6c4f8b285e43676ce71e16
zhugaocen/python
/test/day4/demo2.py
1,115
4.21875
4
''' 只要能用循环遍历的对象都是可迭代(iterable)的对象 list() str() dict() for i in iterable: pass for i in [1,2,3]: print(i) 1.可迭代的对象内部都有 _iter_() 2.会调用iterable数据类型当中的_iter_(),将它转为迭代器 3.迭代器可调用_next_()方法取值,直到抛出StopIteration异常,结束迭代 ''' # lis = [1,2,3] # lis_iter = lis.__iter__() # try: # while True: # print(lis_iter.__next__()) # except StopIteration: # pass ''' range(start,stop,step) start默认为0,左闭右开 ''' # for i in range(1,11,2): # print(i) ''' 程序:当我输入11 --> 壹拾壹元整 壹壹 ch_num[1] ''' ch_num = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] ch = ['园', '拾', '佰', '仟', '萬'] ipt = input("请输入多少钱:") len_ipt = len(ipt) for i in ipt: # print(i) len_ipt -= 1 # nums = ch_num[int(i)] # print(nums) # res = ch[len_ipt] # print(res) # print("{}{}".format(ch_num[int(i)], ch[len_ipt]),end='') print(f"{ch_num[int(i)]}{ch[len_ipt]}",end='') print("整")
false
c55797ba6907860620276b417b4b6e471e9dad58
aleff90/my-python-app
/main.py
1,386
4.1875
4
print("Hello Amigoscode") name, age = "Jamila", 20 pi = 3.14 number = [1, 2, 3, 4] print(name) print(age) print(pi) print(number) print("---") brand = "Amigoscode" age = 2 pi = 3.14 numbers = [] isAdult = True print(type(brand)) print(type(age)) print(type(numbers)) print(type(pi)) print(type(isAdult)) print("---") otherBrand: str = "Amigoscode2" otherIsAdult: bool = False print(type(otherBrand)) print(type(otherIsAdult)) #method def hello(): return "hello" #I am a comment #print("hello") """ I am a comment a second comment third comment print("hello") """ print("---") anotherBrand = 'Amigoscode' #print(anotherBrand.upper()) #print(anotherBrand.replace('A','a')) #print(anotherBrand.replace('A','33')) print(len(anotherBrand)) print(anotherBrand == "amigoscode") print(anotherBrand != "amigoscode") print("code" in anotherBrand) print("code" not in anotherBrand) #print in one line print("---") comment = "da asd dammoda " \ "dasdasnk" \ "dasnjnasd" \ "da" print(comment) #print in each line print("---") otherComment = """ asdhgjeeijkj sdfsdf gds gdsgsd """ print(otherComment) print("---") #name = "Kamilla" #email = """ #hello {}, #how are you? #It was nice talking to you #""" #print(email.format(name)) name = "Kamilla" email = f""" hello {name}, how are you? It was nice talking to you age {4+4} """ print(email)
true
c46fa7bdb008919ac113e71dc0777b6301fd190c
thonathan/Ch.03_Input_Output
/3.0_Jedi_Training.py
1,384
4.4375
4
# Sign your name:__________ethan januszewski______ # In all the short programs below, do a good job communicating with your end user! # 1.) Write a program that asks someone for their name and then prints a greeting that uses their name. # username= input("please input your name: ") # print("hello",username,) # 2. Write a program where a user enters a base and height and you print the area of a triangle. # base= int(input("how long: ")) # hieght= int(input("how tall: ")) # area=0.5*(base*hieght) # print() # print("Here is your area: ",area,) # 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference. # r= int(input("radius: ")) # circumfrance=2*r*3.14 # print() # print("Here is your circumfrance: ",circumfrance,) # 4. Ask a user for an integer and then print the square root. # number= int(input("What is your number: ")) # square_root= number**0.5 # print() # print("Here is your square root==>",square_root,) # 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma. # Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next. # mass= int(input("What is your mass: ")) # acceleration= int(input("What is your acceleration: ")) # force= mass*acceleration # print() # print("May the mass times acceleration be with you",force,) # print("Get it?")
true
3eb364562c76bb3adb21d2f98fad550886c63d34
Javirandu/CodeWars
/IQTest.py
689
4.34375
4
""" iq_test("2 4 7 8 10") => 3 # Third number is odd, while the rest of the numbers are even iq_test("1 2 1 1") => 2 # Second number is even, while the rest of the numbers are odd Careful: index must start at 1 """ numbers =("2 4 7 8 10") numbers = numbers.split() even = 0 odd = 0 index = None oddNumber = 0 evenNumber = 0 for number in numbers: number= int(number) division = number % 2 if division == 0: even +=1 evenNumber = number else: odd +=1 oddNumber = number if even < odd: print(str(evenNumber)) index = numbers.index(str(evenNumber)) print(index+1) else: index = numbers.index(str(oddNumber)) print(index+1)
true
0ff9ccdd80a97ca5605b82e444fd027f73c16d10
Pinecone628/Data-Structure-and-Algorithm
/Single Link List.py
2,699
4.125
4
class SingleNode(object): """The node of single link list""" def __init__(self, item): # _item is the data saved in this note # _next is the index of next note self.item = item self.next = None class SingleLinkList(object): """Single Link List""" def __init__(self): self._head = None def is_empty(self): """Judge if it is empty""" return self._head is None def length(self): """Return the length of the Single Link list""" cur = self._head count = 0 while cur is not None: count += 1 cur = cur.next return count def travel(self): """travel the Single Link list""" cur = self._head while cur is not None: print(cur.item, end=" ") cur = cur.next print("") def add(self, item): """Add item in the head""" node = SingleNode(item) node.next = self._head self._head = node def append(self, item): """Add item at the end of the Single Link list""" node = SingleNode(item) if self._head is None: self._head = node else: cur = self._head while cur.next is not None: cur = cur.next cur.next = node def insert(self, pos, item): """Add item at the pos""" if pos <= 0: self.add(item) elif pos > (self.length() - 1): self.append(item) else: node = SingleNode(item) count = 0 pre = self._head while count < (pos-1): count += 1 pre = pre.next node.next = pre.next pre.next = node def search(self, item): """Find the whether the item exists in the list, return True or False""" cur = self._head while cur is not None: if cur.item == item: return True else: cur = cur.next return False def remove(self, item): """Remove the item""" cur = self._head pre = None while cur is not None: if cur.item == item: if pre is None: self._head = cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next if __name__ == "__main__": sl = SingleLinkList() sl.append(1) print(sl.search(1)) sl.append(2) sl.add(3) sl.insert(2, 4) sl.travel() sl.remove(4) print(sl.search(6)) sl.travel()
true
0177cccb98f4a2f548f21647a7b5571b31f2d874
leexiulian/learn-python
/conprehensive.py
648
4.34375
4
#创建一个列表 Lists = ["country","city","language","hello","custom","music","book","computer","mountain","sub"] #在列表末尾添加一个元素 Lists.append("add") #在指定位置插入一个元素 Lists.insert(0,"river") #del 删除一个元素 del Lists[-2] #pop弹出一个最后元素 Lists.pop() #pop弹出第五个元素 Lists.pop(4) #删除列表中的元素computer Lists.remove("computer") #打印列表 print(Lists) #获取列表的长度并打印 print(len(Lists)) #按字母顺序进行并打印 print(sorted(Lists)) #将列表进行永久性排序 Lists.sort() #逆向排序 Lists.reverse() #将列表输出 print(Lists)
false
9e18011f4eb3e34a61e112f4186d021415fb4f41
tmendonca28/Practice-Projects
/hours_to_seconds.py
313
4.15625
4
""" Calculates number of seconds in 7 hours, 21 minutes and 37 seconds: To be passed in as time string HH:MM:SS Coursera Python: Rice University """ def convert_to_seconds(time_string): h, m, s = time_string.split(':') return (int(h)*3600) + (int(m)*60) + int(s) print(convert_to_seconds("07:21:37"))
true
ed64cb0b9ee2e787c23e89c3fce84bf6db92a525
samudero/PyNdu001
/DefaultArguments.py
862
4.25
4
# Default Arguments [155] """ Created on Mon 19 Mar 2018 @author: pandus """ # ------------------------ Area of rectangles def area(a, b): return a * b print("The area is {}.".format(area(3, 1))) print("The area is {}.".format(area(2.5, 1))) print("The area is {}.".format(area(2.5, 2))) # ------------------------ Solution 2 [157] def area(a, b=1): return a * b print("the area is {}".format(area(3))) print("the area is {}".format(area(2.5))) print("the area is {}".format(area(2.5, 2))) # ------------------------ keyword argument values [158] def f(a: object, b: object, c: object) -> object: print("a = {}, b = {}, c = {}" .format(a, b, c)) f(1, 2, 3) f(c=3, a=1, b=2) f(1, c=3, b=2) # if we use only keyword arguments in the function call, then we dont need to know the order of the arguments
true
5c4607b151c26b291cc481aad575317b555d2138
dos09/PythonDesignPatterns
/src/design_patterns/behavioural/visitor.py
2,470
4.28125
4
""" Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate. If you have different classes and must add some functionality to them, but don't want to change these classes (avoid breaking something) can create Visitor class where to store the methods. Each class will have method accepting visitor and calling the appropriate visitor's method. Example: -having class XMLData class CSVData - need to add functionality to extract data to JSON - create class Visitor: def xml_to_json(obj)... def csv_to_json(obj)... - change class XMLData def accept(self, visitor): visitor.xml_to_json(self) class CSVData def accept(self, visitor): visitor.csv_to_json(self) """ class DataExtractVisitor: def __init__(self): self.data = [] def extract_data_from_human(self, human): raise NotImplementedError() def extract_data_from_alien(self, alien): raise NotImplementedError() class NameExtractVisitor(DataExtractVisitor): def extract_data_from_human(self, human): self.data.append('human name: %s' % human.name) def extract_data_from_alien(self, alien): self.data.append('alien name: %s' % alien.name) class AgeExtractVisitor(DataExtractVisitor): def extract_data_from_human(self, human): self.data.append('human age: %s' % human.age) def extract_data_from_alien(self, alien): self.data.append('alien age: %s' % alien.age) class Humanoid: def __init__(self, name, age): self.name = name self.age = age class Human(Humanoid): def accept_data_extract_visitor(self, visitor): visitor.extract_data_from_human(self) class Alien(Humanoid): def accept_data_extract_visitor(self, visitor): visitor.extract_data_from_alien(self) def run(): alien = Alien('AU', 384) human = Human('Bah', 20) name_extractor = NameExtractVisitor() age_extractor = AgeExtractVisitor() alien.accept_data_extract_visitor(name_extractor) human.accept_data_extract_visitor(name_extractor) alien.accept_data_extract_visitor(age_extractor) human.accept_data_extract_visitor(age_extractor) print(name_extractor.data) print(age_extractor.data) if __name__ == '__main__': run()
true
2aa45afa6bfff93794d754f27d5fc1afb799eae7
dos09/PythonDesignPatterns
/src/design_patterns/structural/decorator.py
1,062
4.4375
4
""" Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. """ class Warrior: def __init__(self, name): self.name = name def attack(self): raise NotImplementedError() class Orc(Warrior): def attack(self): print('the orc %s attacks' % self.name) class Tauren(Warrior): def attack(self): print('the tauren %s attacks' % self.name) class FartingDecorator: # FartingWarrior def __init__(self, warrior): self.warrior = warrior def attack(self): self.warrior.attack() self._fart() def _fart(self): print('%s is farting out loud' % self.warrior.name) if __name__ == '__main__': orc = Orc('Banana') farting_orc = FartingDecorator(Orc('Mogka')) farting_tauren = FartingDecorator(Tauren('Muuu')) orc.attack() farting_orc.attack() farting_tauren.attack()
false
9d751f32fe936e4c0f7f619dd64eb4993cb53a9e
adlienes/Python-Learning-Practices
/Functions/prime_number.py
449
4.1875
4
print("""********** Prime Number Example Press "q" to Exit ************""") def isPrime(number): if(number==1): return False elif(number==2): return True else: for i in range(2,number): if(number%i==0): return False else: return True while True: a=input("Enter Value Number : ") if(a=="q"): break else: a=int(a) if(isPrime(a)): print("Number is Prime Number") else: print("Number isn't Prime Number")
true
258b478e63a8c4cc8e9401011cbadc90371cae1b
adlienes/Python-Learning-Practices
/Loops/user_login.py
682
4.15625
4
print("""************** User Login Example *********************""") sys_user_name="adlienes" sys_password="123456" login_rigt=3 while True: user_name=input("Enter UserName Value : ") password=input("Enter Password Value : ") if(user_name!=sys_user_name and password==sys_password): print("Username is incorrect") login_rigt-=1 elif(user_name==sys_user_name and password!=sys_password): print("Password is incorrect") login_rigt-=1 elif(user_name!=sys_user_name and password!=sys_password): print("Username and Password is incorrect") login_rigt-=1 else: print("User Login succesful") break if(login_rigt==0): print("Login Rigt End") break
true
dfeef8f47363ff1c95a4450032c4eff8df6e8c07
SkyDeBaun/CS173
/hw01/practice/count_word_sentences.py
859
4.15625
4
import nltk import sys text = "I ate fruit the entire day. For breakfast, I had dates. For lunch, I had mangoes. For dinner, I had cantaloupe." #test run----------------------------------------------- count sentences of a string var #sentences = nltk.sent_tokenize(text) #print("Test Count: ") #print(len(sentences)) filename = sys.argv[1] #get the filename from user input (via terminal) #print count of sentences (and words) from a given file-------------- def count_sentences(filename): with open(filename, 'r') as infile: text = infile.read() words = nltk.word_tokenize(text) sentences = nltk.sent_tokenize(text) count = len(sentences) print("Sentence count of " + filename + ": " + str(count) + "\n") print("Word count of " + filename + ": " + str(len(words)) + "\n") count_sentences(filename)
true
77113ba201d2c60b12e5517a1382863415be4829
Arshdeep86/encpyhton
/session10G.py
1,631
4.125
4
""" OOPS : object Oriented programming Structure how we design software Its methodology 1. Object 2. Class Real world : object : anything which exists in Realaity class : represent how an object will look like : Drawing of an object Principle of OOPS 1. think od object 2. create its class 3. From class create real object computer science : object : Multi value container Homogeneous/ Hetro data in object is stored as Dictionary where keys are known as attributes which will hold values as data class : Represent how an object will look like what it should contain as data provide certain functionalities to process the data as well in object Principle of OOPS 1. think od object we need analyze detailed requirements from client regarding his/her software needs. Identify all those terms which will have lot of data associated with it that term -> object and data associated -> attributes 2. create its class 3. From class create real object """ # creating a class class Customer: pass # from class create real object #object construction statement cRef = Customer() print("cRef is :", cRef) print("type of cRef:", type(cRef)) print("hashcode of cRef : ", id(cRef)) print("cRef dictionary", cRef.__dict__) # Add data in object cRef.name = "john Watson" cRef.phone = "+91 7634872364823" cRef.email = "john@example.com" # update data in object cRef.phone = "156464" # delete data in object #del cRef.name # delete an object del cRef print("cRef dictionary", cRef.__dict__)
true
31f2f036151c84bac16ea348623853222bb2b930
Arshdeep86/encpyhton
/practice.py
720
4.25
4
students = ["john", "jennie", "jim", "jack", "joe"] print(students) # 1. concatenation | immutable #newStudents = students + ["fionna", "george"] #print(newStudents) print(students + ["fionna", "george"]) print(students) print(students*2) print() # 3. Membership testing print("john" in students) print("arsh" not in students) # 4. Indexing print(students[0]) print(students[len(students)-1]) # 5. Slicing print(students[0:2]) # 0 is inclusive and 2 in exclusive print(students[1:4]) filteredStudents = students[1:4] print(filteredStudents) # basic for loop # for i in range(0, len(students)): # print(students[i]) # Enhanced version of for loop --> For-Each loop for student in students: print(student)
true
a02ec46140ef6cf6ebc0b5bae91959eaf473c102
Joshuabhad/mypackage
/mypackage/recursion.py
1,699
4.65625
5
def sum_array(array): """ Calculate the sum of a list of arrays Args: (array): Numbers in a list to be added together Returns: int: sum of all numbers in a array added together Examples: >>> sum_array([1,2,3,4,5]) 15 >> sum_array([1,5,7,3,4]) 20 >> sum_array([10,10,20,10]) 50 """ if len(array)==0: return 0 else: return array[0] + sum_array(array[1:]) def fibonacci(n): """ Calculate nth term in fibonacci sequence Args: n (int): nth term in fibonacci sequence to calculate Returns: int: nth term of fibonacci sequence, equal to sum of previous two terms Examples: >>> fibonacci(1) 1 >> fibonacci(2) 1 >> fibonacci(3) 2 """ if n <= 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) def factorial(n): """ Calculate the factorial of a given number Args: n (int): the input number Returns: int: the factorial of a number e.g 5! = 5*4*3*2*1 = 120 Examples: >>> factorial(6) 720 >> factorial(4) 24 """ if n < 1: return 1 else: fac = n * factorial( n - 1 ) return fac def reverse(word): """ Output a string in reverse Args: word: string that you would input Returns: a string in reverse order Examples: >>> reverse('apple') 'elppa' >> reverse('friend') 'dneirf' """ if word == "": return word else: return word[-1] + reverse(word[:-1])
true
b3059a0919c8555269660867b98c6966da71a027
Mechtagon/Oware-in-Python
/oware.py
1,677
4.25
4
def tutstart(tutorial): #Starts the tutorial if user chooses yes, procedes to game if user chooses no if tutorial == "N": print("You have selected NO") elif tutorial == "Y": print("You have selected YES") else: while tutorial != "Y" and tutorial != "N": print("That is not a valid answer, try again") tutorial = input().upper() if tutorial == "N": print("You have selected NO") elif tutorial == "Y": print("You have selected YES") printboard() def printboard(L1, L2): #Function responsible for printing board updates print("Player 1 Side") print(("|" +("-" * 5))*6 + "|") #prints top row of the board for i in range(len(L1)): #prints Player 1 seeds print("|" +(" " * 2 + str(L1[i]) + " " * 2), end = "") print("|", end = "") #prints last line on row with seed values print() print("|" + (("-" * 5) + "|") * 6) #prints middle row of board for i in range(len(L2)): print("|" +(" " * 2 + str(L2[i]) + " " * 2), end = "") print("|", end = "") #prints last line on row with seed values print() print(("|" +("-" * 5))*6 + "|") #prints bottom row of the board print("Player 2 Side") print() if __name__ == "__main__": print("Hello! Welcome to the game of Oware!") print("Would you like to start the tutorial? (Y/N)") tanswer = input().upper() tutstart(tanswer) #start the tutorial print() p1seeds = [4, 4, 4 ,4 ,4, 4] p2seeds = [4, 4, 4 ,4 ,4, 4] printboard(p1seeds, p2seeds)
true
c0c2783bf59552be84dcc7b496944a954447ba20
nthnluu/brown-cs18-master.github.io
/content/from15/animals.py
2,658
4.40625
4
from dataclasses import dataclass """ This file serves three purposes: 1. Give an example of a class hierachy. Here we have a parent class named Animal and two child classes (Dillo and Boa). We are explicitly using dataclasses rather than regular Python classes because the goal is to get familiar with programming with functions rather than methods 2. Show how to write explicit test cases, along with initial criteria for developing a good collection of tests 3. Provide a crash course in the Python syntax that you will need for the CS15 practice problems. The code here corresponds to the code that the main CS18 lecture will be developing in Java over the first 4 lectures. """ #--- Classes ------------------------------- @dataclass class Animal: length: float @dataclass class Dillo(Animal): is_dead: bool baby_dillo = Dillo(8, False) adult_dillo = Dillo(24, False) huge_dead_dillo = Dillo(65, True) @dataclass class Boa(Animal): name: str eats: str mean_boa = Boa(36, "Slinky", "nails") thin_boa = Boa(24, "Slim", "lettuce") #--- Functions and Tests ---------------------- def can_shelter(d: Dillo) -> bool: """determine whether boa is dead and long""" return d.is_dead and (d.length > 60) # test cases: each contains an expression and the expected answer # a good set of tests exercises all options of a conditional def test_distinct(): assert(can_shelter(baby_dillo) == False) assert(can_shelter(adult_dillo) == False) assert(can_shelter(huge_dead_dillo) == True) def len_within(num: float, low: float, high: float) -> bool: """determine whether first num between next two, inclusive""" return low <= num and num <= high # all functions should have test methods # a good set of tests checks all boundary conditions in the data def test_len_within(): assert(len_within(5.99, 6, 10) == False) assert(len_within(6, 6, 10) == True) assert(len_within(10, 6, 10) == True) assert(len_within(10.2, 6, 10) == False) def is_normal_size(a: Animal) -> bool: """determine whether given animal is normal length for its type""" if isinstance(a, Dillo): return len_within(a.length, 12, 24) elif isinstance(a, Boa): return len_within(a.length, 30, 60) else: raise("Unknown Animal") # a good set of tests exercises all variants of the data def test_normalsize(): assert(is_normal_size(baby_dillo) == False) assert(is_normal_size(adult_dillo) == True) assert(is_normal_size(Dillo(25, True)) == False) assert(is_normal_size(thin_boa) == False) assert(is_normal_size(mean_boa) == True) #--- Run the tests ---------------------------- test_distinct() test_len_within() test_normalsize()
true
c569f12589e8df0b04dd4f128b284e2b9ae4e139
Abeerdxx/python-spotcheck-solutions
/Functions/sc3.py
288
4.125
4
def determine_biggest(num1, num2): if num1 > num2: return num1 # Note that we don't need an "else", because `return` ends the function! return num2 biggest = determine_biggest(91234, 91241) print("Biggest number is " + biggest) # outputs: Biggest number is 91241
true
d05302ab199d7c464b2cbe9ef90d261a1f464e7f
Abeerdxx/python-spotcheck-solutions
/Conditionals/sc2.py
470
4.375
4
username = "serious_cat612" correctUsername = "serious_dog612" # Two ways to check that `username` is not an empty string: # if username # - this works because Python sees an empty string as "False" # or: # if username != "" # - simple comparison of strings if username: if username == correctUsername: print("Welcome back, serious_dog612") else: print("Sorry, that username is incorrect") else: print("Please enter a username")
true
8dfc4ba6cf0d5798d7fdb7a868e98dc0b8bac595
Sundarmax/Interview-practice-problems
/linkedlist/reverse.py
1,307
4.21875
4
# Reverse a sinly linked list class Node: def __init__(self,data): self.item = data self.next = None class LinkedList: def __init__(self): self.startnode = None self.insert_at_last(1) self.insert_at_last(2) self.insert_at_last(3) self.insert_at_last(4) self.insert_at_last(5) def insert_at_last(self,data): if self.startnode is None: new_node = Node(data) new_node.item = data new_node.next = self.startnode self.startnode = new_node else: n = self.startnode while n.next is not None: n = n.next new_node = Node(data) new_node.item = data n.next = new_node def TraverseList(self): n = self.startnode while n is not None: print(n.item, end = " ") n = n.next print(' ') def ReverseLinkedlist(self): current = self.startnode temp = None prev = None while current is not None: temp = current current = current.next temp.next = prev prev = temp self.startnode = prev newlist = LinkedList() newlist.ReverseLinkedlist() newlist.TraverseList()
false
34bceeb5b0fef28efecc306c4e45a0fe94d5837a
rates37/Numerical-Methods
/Root Finding Methods/bisection_method.py
2,298
4.4375
4
# Author: Satya Jhaveri # # The bisection method is a root finding method that utilizes a 'divide and conquer' strategy # to find the root of a function. # It can be used on any continuous function, f, given two values a and b for which f(a) and f(b) # have differing signs. This root finding method works by halfing the interval between a and b, # and checking which interval [a, (a+b)/2] or [(a+b)/2, b] contains the root. This is a consequence # of the Intermediate Value Theorem. The interval that contains the root is then 're-used' in the # above process repeatedly until the method produces a value that meets the precision required. # from typing import Callable # (For type hinting function) def bisection(f: Callable, lower: float, upper: float, precision: float) -> float: """ Approximates the root to a function using the bisection method. Args: f (Callable): A continuous function to approximate a root of lower (float): The lower bound of the interval which contains the root upper (float): The upper bound of the interval which contains the root precision (float): The maximum amount of error that is acceptable in method results Returns: (float): Value which, when passed to f, returns a number of magnitude < precision. Raises: ValueError: If precision is not greater than 0, if f(lower) and f(upper) are of the same sign, or if lower == upper. """ # Validating inputs: if lower >= upper: raise ValueError("Lower cannot be greater than or equal to upper.") if f(lower) * f(upper) > 0: raise ValueError("f(lower) and f(upper) must have different signs.") if precision <= 0: raise ValueError("Precision cannot be zero or negative.") # Actual method: mid = (lower + upper) / 2 # Split the interval into two smaller intervals while abs(f(mid)) > precision: # Loop until the precision is met # Choosing the range for the new interval: if f(lower) * f(mid) < 0: upper = mid else: lower = mid # Set mid to the middle of the new interval: mid = (lower + upper) / 2 return mid
true
ab3d3a4191f9bb176f1b6859e500ce27ee554f42
rates37/Numerical-Methods
/Integral Approximating Methods/rectangle_method.py
2,893
4.8125
5
# Author: Satya Jhaveri # # The rectangle method is the most basic method for integral approximation, and is # commonly used as examples examples in math textbooks. # # As the name suggests, this method uses rectangles to approximate the value of # an integral. It creates rectangles that roughly fit the shape of the function # and finds the sum of the rectangles between the intervals. # # This file also contains a version of the rectangle method that can be used on # discrete, non-uniform input data. # from typing import Callable, List def rectangle(f: Callable, a: float, b: float, n: int) -> int: """ Calculates the value of a definite integral using the rectangle method using a specified number of rectangles. Args: f (Callable): A continuous function to integrate over a (float): The lower integral interval b (float): The upper integral interval n (int): The number of rectangles to use in the approximation Raises: ValueError: If lower integral is higher than upper integral ValueError: If the number of rectangles is less than 1 Returns: int: The approximated value of the integral """ # Checking Inputs: if a > b: raise ValueError("Lower integral interval must be lower than upper interval.") if n < 1: raise ValueError("The number of rectangles to use cannot be less than one") # Actual method: step = (b - a) / n acc = 0 for i in range(n): acc += step * f(a + i * step) return acc def rectangle_vec(x: List[float], y: List[float]) -> float: """ Approximates the value of an integral using the rectangle method on discrete data. Note: This method does not include the first data point and thus is very useless. However it establishes concepts of how to handle discrete data, which prove useful in more complex integral-approximating methods. Args: x (List[float]): A list of the independent variable values y (List[float]): A list of the dependent variable values Raises: ValueError: If there is a different number of independent variable values than dependent variable values Returns: float: The approximated value of the integral """ # Validating inputs: if len(x) != len(y): raise ValueError("The number of points in each vector must be equal.") # Actual Method: n = len(x) # Sorting the input data based on independent variable values: tuple_list = [(x[i], y[i]) for i in range(n)] tuple_list.sort(key=lambda x: x[0], reverse=False) x = [tuple_list[i][0] for i in range(n)] y = [tuple_list[i][1] for i in range(n)] acc = 0 for i in range(1, n): acc += (x[i] - x[i-1]) * y[i] return acc
true
b273bd04f27732462868a08b008181d80aacdd91
MaxAkonde/python
/course_1_assignement_7/04_03.py
484
4.25
4
items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"] acc_num = 0 for i in items: if i.find('w') > -1: acc_num += 1 print(acc_num) # Write code to count the number of strings in list items # that have the character w in it. Assign that number to the # variable acc_num. # HINT 1: Use the accumulation pattern! # HINT 2: the in operator checks whether a substring is present in a string. # Hard-coded answers will receive no credit.
true
03eb98b9898bd3fb03fdaab571661333dfb65876
MaxAkonde/python
/course_1_assignement_12/08_04.py
477
4.1875
4
p_phrase = "was it a car or a cat I saw" r_phrase = "" i = 1 while i <= len(p_phrase): r_phrase += p_phrase[len(p_phrase) - i] i+=1 print(r_phrase) # A palindrome is a phrase that, if reversed, # would read the exact same. Write code that # checks if p_phrase is a palindrome by reversing # it and then checking if the reversed version is # equal to the original. Assign the reversed version # of p_phrase to the variable r_phrase so that we can check your work.
true
0636058e5836ce187edfe4f308a6d94a859141aa
raghubegur/PythonLearning
/codeSamples/HelloWorld.py
555
4.28125
4
# My first python program # greeting='Hello' # firstName=input('What is your first name: ') # lastName=input('What is your last name: ') # print(greeting + ', ' + firstName.capitalize() + ' ' + lastName.capitalize()) # myOutput = 'Hello, {} {}'.format (firstName,lastName) # print(myOutput) # myOutput = 'Hello, {0} {1}'.format (firstName,lastName) # print(myOutput) # myOutput = 'Hello, {1}, {0}'.format (firstName,lastName) # print(myOutput) # myOutput = f'Hello, {firstName} {lastName}' # print(myOutput) print('Hello | World')
true
c6585871884787fa9729130684d839955daefd54
wzwhit/leetcode
/151翻转字符串里的单词.py
1,036
4.25
4
# 给定一个字符串,逐个翻转字符串中的每个单词。 # 示例 1: # 输入: "the sky is blue" # 输出: "blue is sky the" # 示例 2: # 输入: " hello world! " # 输出: "world! hello" # 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 # 示例 3: # 输入: "a good example" # 输出: "example good a" # 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 # 说明: # 无空格字符构成一个单词。 # 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 # 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 class Solution: def reverseWords(self, s: str) -> str: if not s: return s ss = s.split(' ') ss = [i for i in ss if i != ''] # print(ss) ss.reverse() ss = ' '.join(ss) return ss
false
0cb145ee9c77cfae4fbc1f0f76f304b33de333af
wzwhit/leetcode
/206反转链表.py
1,085
4.15625
4
# 反转一个单链表。 # 示例: # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # 进阶: # 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? # 迭代 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head: return head p = ListNode(0) p.next = head p1 = head.next p2 = head while p1: p2.next = p1.next p1.next = p.next p.next = p1 p1= p2.next return p.next # 递归 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head or not head.next: return head p = self.reverseList(head.next) head.next.next = head head.next = None return p
false
09595aaa0329b2ecc81337d11748e325d76b9841
alfredo-svh/DailyCodingProblem
/277.py
1,802
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 2 22:57:03 2020 @author: Alfredo """ # Daily Coding Problem #277 # Problem: # UTF-8 is a character encoding that maps each symbol to one, two, # three, or four bytes. # For example, the Euro sign, €, corresponds to the three bytes # 11100010 10000010 10101100. The rules for mapping # characters are as follows: # - For a single-byte character, the first bit must be zero. # - For an n-byte character, the first byte starts with n ones and a # zero. The other n - 1 bytes all start with 10. # Visually, this can be represented as follows. # Bytes | Byte format # ----------------------------------------------- # 1 | 0xxxxxxx # 2 | 110xxxxx 10xxxxxx # 3 | 1110xxxx 10xxxxxx 10xxxxxx # 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx # Write a program that takes in an array of integers representing byte # values, and returns whether it is a valid UTF-8 encoding. def utf8(arr): n = len(arr) if n < 1 or n > 4: return False bts = [] #take the binary representations of the integers for i in range(n): if arr[i] >=0 and arr[i] <= 255: bts.append(format(arr[i], '08b')) else: return False if n ==1: return bts[0][0] == '0' #validating first byte for i in range(n): if bts[0][i] == '0': return False if bts[0][n]=='1': return False #validating the rest of the bytes for i in range(1, n): if bts[i][0] != '1' or bts[i][1] != '0': return False return True # Testing utf8([226, 130, 172]) # True utf8([226, 194, 172]) # False utf8([226]) # False utf8([100]) # True utf8([194, 130]) # True
true
a8adf2a2a8c1c2babf1467b15181e4bece74beb5
alfredo-svh/DailyCodingProblem
/431.py
2,259
4.1875
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 5 22:59:46 2021 @author: Alfredo """ # Daily Coding Problem #431 # Problem: # Create a basic sentence checker that takes in a stream of characters and # determines whether they form valid sentences. If a sentence is valid, # the program should print it out. # We can consider a sentence valid if it conforms to the following rules: # 1. The sentence must start with a capital letter, followed by a lowercase # letter or a space. # 2. All other characters must be lowercase letters, separators (,,;,:) or # terminal marks (.,?,!,‽). # 3. There must be a single space between each word. # 4. The sentence must end with a terminal mark immediately following a word. def isWord(word, separators, terminals): # There must be a single space between each word. if word == '': return False # All other characters must be lowercase letters, separators (,,;,:) or # terminal marks (.,?,!,‽). for c in word: if not ((c.isalpha() and c.islower()) or c in separators or c in terminals): return False return True def isValid(sentence): if len(sentence) < 2: return # The sentence must start with a capital letter, followed by a lowercase # letter or a space. if not (sentence[0].isupper() and ((sentence[1].isalpha() and sentence[1].islower()) or sentence[1] == ' ')): return separators = {',', ';', ':'} terminals = {'.', '?', '!', '‽'} arr = sentence.split(' ') arr.pop(0) for word in arr: if not isWord(word, separators, terminals): return # The sentence must end with a terminal mark immediately following a word. if sentence[-1] not in terminals or sentence[-2] == ' ': return print(sentence) # ----------------------------------------------------------------------------- # Testing isValid("Hello, World!") # isValid("Hello, world!") # "Hello, world!" isValid("Is this a test?") # "Is this a test?" isValid("this is a test!") # isValid("This is a test!") # isValid("This is #a test!") # isValid("A.") # isValid("Amen.") # "Amen."
true
df47d08e88fb728bfe280e55ba79c0e540fd662b
WeiS49/Python-Crash-Course
/python_work/ch9/nine/car.py
1,187
4.1875
4
""" A class that can be used to represent cars. """ class Car: """ A simple attempt to simulate car. """ def __init__(self, make, model ,year): """ Initialize the properties describing the car. """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ Return a neat descriptive name. """ # 对于这种变量, 不需要写self long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """ Print a message indicating the mileage of the car. """ print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): """ Set the odometer reading to a specified value. Refuse to call back the mileage schedule. """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """ Increase the odometer a specified amount. """ self.odometer_reading += miles
true
18e158f0a787a7643c0c7847174ed005e0b96660
spvisal/python_sandbox
/while-loops/Ex-ModifiedGamePreferences.py
834
4.3125
4
# Start with an empty list. You can 'seed' the list with # some predefine values if you like. games = ["football", "cricket", "tenis"] # Set the new_game to something other than quit new_game = '' # Start a loop that will run until user enters 'quit' while new_game != 'quit': # Ask the user for new game new_game = input("Please enter the game of your choice ") # Add the new game to our list only of it is not quit if new_game != 'quit': # Check if the game is already their in the list or not and then only add to list. is_available = new_game in games if is_available == False: games.append(new_game) else: print("You are trying to add " + new_game + " is already available..Please add another game..") # Show that new game has been added. print(games)
true
76939fde9bb8dd2a7d2458b12c341668551ee7eb
WizardOfArc/PythonMathGeekery
/Fibonacci.py
662
4.28125
4
#!/usr/bin/python """This module and program is designed to find the nth fibonacci number. It also includes a function that will make a table and compare the nth Fibonacci number to phi**n. """ from math import sqrt def findFib(n): fiboList = [] for i in range(n): #fill a list of n length with zeros fiboList.append(0) return fibo(n, fiboList) def fibo(n, fiboList): if fiboList[n-1] != 0: return fiboList[n-1] else: if (n <= 2): fiboList[n-1] = 1 return 1 else: fiboList[n-1] = fibo(n-1, fiboList) + fibo(n-2, fiboList) return fiboList[n-1]
true
ef069c10e833e2e7f4e876620d7bf5242f49749f
benedictpennyinskip/Iteration
/Iteration - Development exercises - 4.py
301
4.28125
4
#Ben Penny-Inskip #29/10/2014 #Iteration - Development exercises - 4 number = int(input("Please enter a number")) largest = number while number != -1: number = int(input("Please enter a number")) if number > largest: largest = number print("The largest number is {0}".format(largest))
true
f7ee144596bf2e21224191228e3a16612f0b4f93
twtrubiks/python-notes
/defaultdict_tutorial.py
1,090
4.25
4
# defaultdict means that if a key is not found in the dictionary, # then instead of a KeyError being thrown, a new entry is created. # The type of this new entry is given by the argument of defaultdict. from collections import defaultdict def ex1(): # For the first example, default items are created using int(), which will return the integer object 0. int_dict = defaultdict(int) print('int_dict[3]', int_dict[3]) # print int(), thus 0 # For the second example, default items are created using list(), which returns a new empty list object. list_dict = defaultdict(list) print('list_dict[test]', list_dict['ok']) # print list(), thus [] # default dic_list = defaultdict(lambda: 'test') dic_list['name'] = 'twtrubiks' print('dic_list[name]', dic_list['name']) print('dic_list[sex]', dic_list['sex']) def ex2_letter_frequency(sentence): frequencies = defaultdict(int) for letter in sentence: frequencies[letter] += 1 return frequencies if __name__ == "__main__": ex1() print(ex2_letter_frequency('sentence'))
true
0a325f526cce355ecc04b60bc6d8dabb032d4e0c
uuzaix/Practice
/Words_Inverter_Oleg.py
858
4.125
4
#def invert_words(s): #words_list = s.split() #words_list.reverse() #result = ' '.join(words_list) #return result def invert_letters(s): words_list = s.split() print words_list inverted_words = [] for word in words_list: index = 0 single_word = [] for letter in word: a = len(word)-1-index single_word.insert (a, letter) print single_word index = index + 1 inverted_words.append (single_word) print inverted_words #result = ' '.join(words_list) #return result #def test(actual, expected): #if actual == expected: #print "Test passed" #else: #print "Test failed: expected: %s, got: %s" % (expected, actual) #def test_invert_words(): #test (invert_words('I am a cat'), 'cat a am I') #test (invert_words('I am a cat'), 'I ma a tac') #test (invert_words(''), '') #test_invert_words() invert_letters('123456')
true
c29e4aa3b7d58d7dd94152163ea75f8428e39753
Myles-Trump/ICS3U-Unit5-06
/main.py
734
4.4375
4
#!/usr/bin/env python3 # Created by: Myles Trump # Created on: May 2021 # This program rounds decimals def rounding(rounding_num, decimal): # process integer = decimal * 10 ** rounding_num decimal_rounded = int(integer) decimal_final = decimal_rounded / 10 ** rounding_num # output print("\nYour number is rounded to {0}".format(decimal_final)) def main(): # this function calls other functions as well as # takes input # input decimal = float(input("Input a decimal to round: ")) print("Input how many decimal places ", end="") rounding_num = int(input("you'd like to round to: ")) # call fucntions rounding(rounding_num, decimal) if __name__ == "__main__": main()
true
b012f1cf1cd83ea8642b94815b6aa102871225d6
athulpa/Mini_Projects
/Sudoku_solver/emptysolver_naiveRec.py
2,072
4.34375
4
# This file solves completes an empty sudoku and makes it a full and correct one. # It is meant to illustrate the naive rescursion algorithm for solving sudokus. # The same algorithm is modified slightly to solve partially complete sudokus. from sudoku import Sudoku sud = Sudoku() # sud is a numpy array (i.e. values only) # Checks if all numbers 1..9 are present in every row, col and box. def complete(sud): for i in range(9): for num in range(1, 10): if(num not in sud[i, :]): # print(num, 'not in row', i+1) return False if(num not in sud[:, i]): # print(num, 'not in col', i+1) return False if(num not in sud[(i//3)*3:(i//3)*3+3, (i%3)*3:(i%3)*3+3]): # print(num, 'not in box', i+1) return False return True # Checks if any number 1..9 is repeating in any row, col or box. # Returns False if repetitions are found. def valid(sud): for i in range(9): for num in range(1, 10): if((sud[i, :]==num).sum()>1): return False if((sud[:, i]==num).sum()>1): return False for i in range(9): for num in range(1, 10): if((sud[(i//3)*3:(i//3)*3+3, (i%3)*3:(i%3)*3+3]==num).sum()>1): return False # print(True) return True # A recursive function that inserts values at pos and calls itself with pos+1. def solve(pos): if(pos==81): print('Complete') sud.disp() resp = input('Conitnue? ') if(resp.lower() in ['y', 'yes']): return False else: return True i = pos//9 j = pos%9 for num in range(1, 10): sud.values[i, j] = num if(valid(sud.values) == True): retval = solve(pos+1) if(retval==False): continue else: return True sud.values[i, j]=0 return False
true
b885de4f6dbc63cb0cbb917ea5d8066d3342f5d3
alluballu1/OOP-tasks
/Tasks/Exercise 3/Exercise3Task6.py
1,377
4.3125
4
# File name: Exercise3Task6.py # Author: Alex Porri # Description: Dice class for rolling, two objects, rolling both and getting the sum of them. import random # Creating the dice class class Dice: def __init__(self): # List of colors and the dice's see-throughness LIST_OF_COLORS = ("Blue", "Green", "Cyan", "Red") SOLIDNESS = ("Opaque", "Translucent") # See-through, color and the eye value are selected at random. All attributes are private. self.__color = LIST_OF_COLORS[random.randint(0, 3)] self.__Number_up = random.randint(1, 6) self.__translucent_or_opaque = SOLIDNESS[random.randint(0, 1)] # Function for rolling the dice def roll_dice(self): self.__Number_up = random.randint(1, 6) # get functions for returning wanted values def get_color(self): return self.__color def get_side_up(self): return self.__Number_up def get_solidness(self): return self.__translucent_or_opaque def main(): my_dice = Dice() your_dice = Dice() my_dice.roll_dice() your_dice.roll_dice() first_value = my_dice.get_side_up() second_value = your_dice.get_side_up() print("My dice value: " + str(first_value), "Your dice value: " + str(second_value), "Sum of the two values: " + str(first_value+second_value), sep="\n") main()
true
9261de0da85ac9d860d1f17ca9f90995af4dc29b
alluballu1/OOP-tasks
/Tasks/Exercise 1/Exercise1Task7.py
813
4.40625
4
# File: Exercise1Task7.py # Author: Alex Porri # Description: Count the sum and the squared sum of a arithmetic progression import math # Function that handles the user input of the maximum value, wanted calculation and printing of the sums def sum_of_arithmetic_progression(): MAXIMUM_VALUE = input("Add a maximum value for the arithmetic progression: ") LIST_OF_NUMBERS = [0] NEXT_NUMBER = 0 SUM_OF_NUMBERS = 0 SQUARED_SUM_OF_NUMBERS = 0 while int(LIST_OF_NUMBERS[(len(LIST_OF_NUMBERS)-1)]) < int(MAXIMUM_VALUE): NEXT_NUMBER += 2 LIST_OF_NUMBERS.append(NEXT_NUMBER) for EACH in LIST_OF_NUMBERS: SUM_OF_NUMBERS += EACH SQUARED_SUM_OF_NUMBERS += math.sqrt(EACH) print(SUM_OF_NUMBERS, SQUARED_SUM_OF_NUMBERS, sep="\n") sum_of_arithmetic_progression()
true
953cae8390a5385b1718744c22144326b8994b0b
alluballu1/OOP-tasks
/Tasks/Exercise 2/Exercise2Task8.py
1,143
4.15625
4
# File name: Exercise2Task8.py # Author: Alex Porri # Description: Coin class (for flipping) import random class coin: # The __init__ method initializes the sideup data attribute with "heads" def __init__(self): self.SIDEUP = "Untossed: Heads" # The toss method generate a random number # int the range of 0 to 1. If the number # 0 = "heads", otherwise "tails" def toss(self): TOSS_VALUE = random.randint(0, 3) if TOSS_VALUE == 0: self.SIDEUP = "Heads" elif TOSS_VALUE == 1: self.SIDEUP = "Tails" elif TOSS_VALUE == 2: self.SIDEUP = "It landed on it's side!" else: self.SIDEUP = "Uhh... I think it fell into a rabbit hole. Somehow." # the get_sideup method returns the value referenced by sideup. def get_sideup(self): return self.SIDEUP # The main function def main(): # Create an object from the coin class MY_COIN = coin() # Toss the coin print("Tossing the coin...") MY_COIN.toss() # Display the side print("Landed on: " + MY_COIN.get_sideup(), sep="\n") main()
true
fad9680026c546cab0612989eb36523144fe187f
crwhite3/BeginningPythonMath
/UglyCalculator/calc.py
1,986
4.34375
4
def add (firstNumber, nextNumber):#Defines add function and variable to be used print "Adding %s + %s" % (firstNumber, nextNumber)#Displays summary of function return float(firstNumber + nextNumber) #performs the math of the function def subtract (firstNumber, nextNumber): print "Subtract %s - %s" % (firstNumber, nextNumber) return float(firstNumber - nextNumber) def multiply (firstNumber, nextNumber): print "Multiply %s * %s" % (firstNumber, nextNumber) return float(firstNumber * nextNumber) def divide (firstNumber, nextNumber): print "Dividing %s / %s" % (firstNumber, nextNumber) return float(firstNumber / nextNumber) #assigning necessary variables firstNumber = float(raw_input("What is your first number?\n")) againLoop = "Y" while againLoop == "Y": function = str (raw_input( "Would you like to Add (+), Subtract (-), Multiply (*), or Divide (/)?\n")) nextNumber = float(raw_input("What is your next number?\n")) #Logic test assessing user input and calls the appropriate function to be performed if function == "+": result = add (firstNumber, nextNumber) print "Result is: %s" % result firstNumber = result againLoop = str (raw_input("\nDo you nedd to perform more calculations on the result? (Y)es or (N)\n")).upper() elif function == "-": result = subtract (firstNumber, nextNumber) print "Result is: %s" % result firstNumber = result againLoop = str (raw_input("\nDo you nedd to perform more calculations on the result? (Y)es or (N)\n")).upper() elif function == "*": result = multiply (firstNumber, nextNumber) print "Result is: %s" % result firstNumber = result againLoop = str (raw_input("\nDo you nedd to perform more calculations on the result? (Y)es or (N)\n")).upper() elif function == "/": result = divide (firstNumber, nextNumber) print ("Result is: %s") % result firstNumber = result againLoop = str (raw_input("\nDo you nedd to perform more calculations on the result? (Y)es or (N)\n")).upper()
true
e7d5654e23dfeaa2a26871b353666b5883f1d512
weed478/wdi6
/is_prime.py
452
4.125
4
def is_prime(n): if n < 2: return False elif n == 2: return True elif n % 2 == 0: return False div = 3 while div * div <= n: if n % div == 0: return False div += 2 return True def prime_factors(n): i = 2 while i*i <= n: if n % i == 0: while n % i == 0: n //= i yield i i += 1 if n > 1: yield n
false
efa81b312818f2ecf5fc96ce76b3476e9d87dd46
findman/PythonCookbook
/chapter1/p1_24.py
516
4.125
4
#!/usr/bin/env python3 # -*- coding:utf8 -*- prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } p1 = {key:value for key,value in prices.items() if value > 200} print(p1) tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'} p2 = {key:value for key,value in prices.items() if key in tech_names} print(p2) # 先序列推导再赋值 p3 = dict((key, value) for key, value in prices.items() if value > 200) print(p3) # p4 = { key:prices[key] for key in prices.keys() & tech_names } print(p4)
false
12b6886308102193e21bbb2c63f990bfdd6cdb49
findman/PythonCookbook
/chapter2/p06_case_insensitive.py
881
4.34375
4
#!/usr/bin/env python3 # -*- coding:utf8 -*- """ Topic: 字符串忽略大小写的搜索替换 Desc : """ import re def matchcase(word): def replace(m): text = m.group() #print(text) if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace def case_insensitive(): text = 'UPPER PYTHON, lower python, Mixed Python' # re.IGNORECASE忽略大小写 print(re.findall('python', text, flags=re.IGNORECASE)) print(re.sub('python', 'snake', text, flags=re.IGNORECASE)) # 这里matchcase 返回的是replace函数,来处理snake print(re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)) if __name__ == '__main__': case_insensitive()
false
0201d473e2646450aedfc34eaade89e9a2f6a0e5
findman/PythonCookbook
/chapter1/p1_14.py
735
4.125
4
#!/usr/bin/env python3 # -*- coding:utf8 -*- prices = { 'ACME':45.23, 'AAPL':612.78, 'IBM':205.55, 'HPQ':37.20, 'FB':10.75 } # zip反转key和value,然后返回zip对象 min_price = min(zip(prices.values(), prices.keys())) max_price = max(zip(prices.values(),prices.keys())) print('min_price:', min_price) print('max_price:', max_price) # 从输出可以看到zip实际是将字典转换为了元组 # 同时它是一个只能访问一次的迭代器 p = zip(prices.values(), prices.keys()) print(p) for k in p: print(type(k)) print(k) """ <class 'tuple'> (205.55, 'IBM') <class 'tuple'> (10.75, 'FB') <class 'tuple'> (612.78, 'AAPL') <class 'tuple'> (37.2, 'HPQ') <class 'tuple'> (45.23, 'ACME') """
false
d462f493e951336566da1d7593e90a7357ddc2a6
kpkishankrishna/20186029_CSPP-1
/cspp1-assignments/m5/p4/square_root_newtonrapson.py
364
4.125
4
''' Author@ : kpkishankrishna This program evaluates the square root of number using Newton Raphson method ''' def main(): '''Main function.''' num_1 = int(input()) epsilon = 0.01 guess = num_1/2.0 while abs(guess**2-num_1) >= epsilon: guess = guess-(((guess**2)-num_1)/(2*guess)) print(guess) if __name__ == "__main__": main()
false
c7e734b743be46e5733a818dd04fa5049153c053
kpkishankrishna/20186029_CSPP-1
/cspp1-assignments/m7/Functions - Assignment-1/assignment1.py
2,172
4.375
4
''' # author@ :kpkishankrishna # Functions | Assignment-1 - Paying Debt off in a Year # Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the # credit card company each month. # The following variables contain values as described below: # balance - the outstanding balance on the credit card # annualInterestRate - annual interest rate as a decimal # monthlyPaymentRate - minimum monthly payment rate as a decimal # For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining # balance. Be sure to print out no more than two decimal digits of accuracy - so print # Remaining balance: 813.41 # instead of # Remaining balance: 813.4141998135 # So your program only prints out one thing: the remaining balance at the end of the year in the format: # Remaining balance: 4784.0 # A summary of the required math is found below: # Monthly interest rate= (Annual interest rate) / 12.0 # Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance) # Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) ''' def payingdebtoff_inayear(updatedbalance_eachmonth, annual_interestrate, monthly_paymentrate): ''' Input updated balance, annual interst rate, montly payment rate ''' for count_month in range(1, 13): del count_month monthly_interestrate = annual_interestrate/12.0 minimummonthly_payment = monthly_paymentrate * updatedbalance_eachmonth monthlyunpaid_balance = updatedbalance_eachmonth - minimummonthly_payment updatedbalance_eachmonth = monthlyunpaid_balance + \ (monthly_interestrate * monthlyunpaid_balance) return round(updatedbalance_eachmonth, 2) def main(): ''' Main function ''' data = input() data = data.split(' ') data = list(map(float, data)) print("Remaining balance:", (payingdebtoff_inayear(data[0], data[1], data[2]))) if __name__ == "__main__": main()
true
c4211d20313c6b5c31f05d50629d459eab87f6ec
Mayankjh/First_python_prog
/area_calc.py
285
4.15625
4
# first program # name = input('tell me your name punk') # age = input('...and your age:') # # print('hello','Your name', age) #calc the area of the circle radius = input('enter the radius of your circle (m):') area = 3.142*int(radius)**2 print('The area of your circle is :',area)
true
d95512dda52e38e7f457f3feddf57472c09c3799
Iltifath/Numeric-Programming
/Arithmetic.py
816
4.1875
4
#Arithmetic #Create a program that reads two integers, a and b, from the user. Your program should compute and display: #• The sum of a and b #• The difference when b is subtracted from a #• The product of a and b #• The quotient when a is divided by b #• The remainder when a is divided by b #• The result of log10 a #• The result of ab #Import math library import math #Get two integers a=int(input('Enter two integers\na:')) b=int(input('b:')) #Addition print("Sum of two integers:",a+b) #Subtraction print("Difference of two integers:",a-b) #Multiplication print("Multiplication of two inetgers",a*b) #Quotient print("Quotient of two integers:",a//b) #Reminder print("Reminder of two integers:",a%b) #Lograthmoc print("Log of first integer:",math.log10(a)) #Result ab print("Result of ab:",a*b)
true
82b8401a06300eef748b46b24d4b524f11079e28
ugiacoman/Basics
/10classes/carpoint.py
1,159
4.21875
4
# CS 141 Lab 10 # carpoint.py # # Modified by: # # Defines a class that represents a Cartesian point. class Point: # The class constructor that initializes an instance of the class. def __init__(self, x, y): self.xCoord = x self.yCoord = y # Returns a string representation of the point. Automatically used # by the print() function when printing a Point object. def __str__(self): return '(' + str(self.xCoord) + ',' + str(self.yCoord) + ')' # Returns the x-coordinate of the point def getX(self): return self.xCoord # Returns the y-coordinate of the point def getY(self): pass # Returns true if the point is (0,0) and false otherwise def isOrigin(self): pass # Returns true if this point is the same as the otherPoint, and # false otherwise. def isEqual(self, otherPoint): return self.xCoord == otherPoint.xCoord and \ self.yCoord == otherPoint.yCoord # Returns the distance between this point and the otherPoint. def distance(self, otherPoint): pass
true
cb86d88a37d9e23408c723ca1faf2ee2e2694f24
loudtiger/stuff
/reversestringrecursively.py
270
4.21875
4
#Reverse a String recursively import sys inputValue = sys.argv[1] charList = list(inputValue) def reverse(charList): if len(charList) == 1: return charList[0] else: return charList[len(charList)-1] + reverse(charList[0:len(charList)-1]) print reverse(charList)
false
cc2a4ff92db512037ddbddeab1fbc1c553625694
noyonict/Sorting-Algorithm-in-Python
/insertion_sort.py
698
4.25
4
def insertion_sort(a): """Insertion Sort in python 3""" for i in range(1, len(a)): j = i-1 while a[j] > a[j+1] and j >= 0: a[j], a[j+1] = a[j+1], a[j] j -= 1 def insertion_sort_v2(a): """Insertion Sorting v2 algorithm in python 3""" for i in range(1, len(a)): cur_num = a[i] for j in range(i-1, 0, -1): if a[j] > cur_num: a[j+1] = a[j] else: a[j+1] = cur_num break array = [12, 3, 43, 43, 9, 3, 2, 2, 43, 23, 53, 3, 3, 23, 23, 12, 53, 91] print(array) insertion_sort(array) print(array) insertion_sort_v2(array) print(array)
false
12e6adce2d28803b3430fa94ec70c625eb4397aa
Wong-S/algorithm-notes
/recursion.py
870
4.15625
4
# TO increase stack memory..... # import sys # sys.setrecursionlimit(1000) # ================= def recursiveMethod(n): if n < 1: print("n is less than 1") else: recursiveMethod(n - 1) print(n) # ============================= # Factorial # n! = n * (n-1)! def factorial(n): # Step 3: Unintentional case -- factorial only takes positive numbers, so deal with negatives using assert method. # Make sure it's a positive number AND an integer. If not, it'll throw an exception. We are forcing "n" to not be a non negative integer # Note: Running the function with floats will throw an error assert n >= 0 and int(n) == n, "The number must be positive integer only!" if n in [0, 1]: # Step 2: Base case return 1 else: return n * factorial(n - 1) # Step 1: Recursive case print(factorial(3))
true
a3e4227bb10c60bfec36ea4a7226f2d2acc0be7f
reygvasquez/Problem-Solving-in-Data-Structures-Algorithms-using-Python
/AlgorithmsChapters/DAC/NutsAndBolts.py
1,263
4.28125
4
def make_pairs(nuts, bolts) : make_pairs_util(nuts, bolts, 0, len(nuts) - 1) print("Matched nuts and bolts are : ", nuts, "&", bolts) # Quick sort kind of approach. def make_pairs_util(nuts, bolts, low, high) : if (low < high) : # Choose first element of bolts list as pivot to partition nuts. pivot = partition(nuts, low, high, bolts[low]) # Using nuts[pivot] as pivot to partition bolts. partition(bolts, low, high, nuts[pivot]) # Recursively lower and upper half of nuts and bolts are matched. make_pairs_util(nuts, bolts, low, pivot - 1) make_pairs_util(nuts, bolts, pivot + 1, high) # Partition method similar to quick sort algorithm. def partition(arr, low, high, pivot) : i, j = low, low while (j < high) : if (arr[j] < pivot) : arr[i], arr[j] = arr[j], arr[i] # Swap i += 1 elif(arr[j] == pivot) : arr[high], arr[j] = arr[j], arr[high] # Swap j -= 1 j += 1 arr[i], arr[high] = arr[high], arr[i] # Swap return i # Testing Code nuts = [1, 2, 6, 5, 4, 3] bolts = [6, 4, 5, 1, 3, 2] make_pairs(nuts, bolts) """ Matched nuts and bolts are : [1, 2, 3, 4, 5, 6] & [1, 2, 3, 4, 5, 6] """
true
a8f29417c4d2154dbee06dc6bfcd99b4433c84d1
Pythonyte/lc
/number-of-ways-to-calculate-a-target-number-using-only-array-element.py
463
4.1875
4
https://www.geeksforgeeks.org/number-of-ways-to-calculate-a-target-number-using-only-array-elements/ def findTotalWays(arr, i, k, comb): if (i >= len(arr) and k != 0): return 0 # If target is reached, return 1 if (k == 0): print(comb) return 1 return (findTotalWays(arr, i + 1, k, comb) + findTotalWays(arr, i + 1, k - arr[i], comb + [arr[i]])) arr = [-3, 1, 3, 5] k = 6 print(findTotalWays(arr, 0, k, []))
false
57dbbb9e6dc4566129553d60b850206b482c9262
pedromfnakashima/codigos_versionados
/Meus códigos/Python/Economia/Antigos/groupby_1b.py
1,251
4.40625
4
""" https://www.tutorialspoint.com/python_pandas/python_pandas_groupby.htm """ #import the pandas library import pandas as pd import numpy as np df = pd.DataFrame({'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'Kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]}) print(df.groupby('Team').groups) print(df.groupby(['Team','Year']).groups) grouped = df.groupby('Year') for name,group in grouped: print(name) print(group) print(grouped.get_group(2014)) print(grouped['Points'].agg(np.mean)) grouped = df.groupby('Team') score = lambda x: (x - x.mean()) / x.std()*10 print(grouped.transform(score)) df print(df.groupby('Team').filter(lambda x: len(x) >= 3)) # x é o df pequeno df.groupby('Team').first() df = df.sort_values(['Team', 'Points'], ascending=[True,False]) segundo_maior = df.groupby('Team').nth(1) dois_elementos = df.groupby('Team').head(2) ####################################### ####################################### #######################################
false
50b3e6f753bcc68badc76abfd0833df12e55b830
IriNor/uppgifter
/vecka2/uppgift 21.py
1,149
4.375
4
"""Skapa funktioner som: 1) Kvadrerar ett tal n, kalla funktionen square exempel: square(1) -> 1 square(2) -> 4 square(3) -> 9 square(4) -> 16 2) Räknar ut omkretsen på en cirkel givet radien r circumference(2) -> 12.5664 3) Räknar ut radien på en cirkel givet omkretsen radius(12.5664) -> 2 4) Räknar ut fakultet för ett tal n Fakultet är produkten av alla tal från 1 till talet n, skrivs i matematiken med ett !, exempel: 5! som är 1*2*3*4*5 = 120 3! är 1*2*3 = 6 Den engelska termen för fakultet är factorial så det är ett lämpligt funktionsnamn""" def square(n: int)->int: return n*n def circle_omkretsen(n: int)-> int: p = 3.14159 return 2 * p * n def circle_radien(n: int) -> int: p = 3.14159 c_o = 12.56636 return c_o / p / n if __name__ == '__main__': print(square(1)) print(square(2)) print(square(3)) print(square(4)) print(circle_omkretsen(2)) print(circle_radien(2)) factorial = 1 n = input("Skriv ett nummer: ") if int(n) >= 1: for i in range(1, int(n)+1): factorial = factorial * i if __name__ == '__main__': print("! av ", n, " är : ", factorial)
false
321f5e29191f378967a2506fe0aa98e1041e0f1b
pecholi/jobeasy-python-course
/lesson_1/homework_1_4.py
955
4.28125
4
# Create three strings using three different methods. Save your result to result_string_1, result_string_2, # result_string_3 variables result_string_1 = 'a' result_string_2 = "b" result_string_3 = result_string_1 + result_string_2 # Enter your first and last name. Join them together with a space in # between. Save a result in a variable result_full_name and # save the length of the whole name in result_full_name_length variable. first_name = 'James' last_name = 'Bond' result_full_name = first_name + ' ' + last_name result_full_name_length = len(result_full_name) # Enter the capital city of California State in lower case. Change the case to title case. # Save the result in result_ca_capital variable ca_capital_city = 'sacramento' result_ca_capital = ca_capital_city.capitalize() # Enter the name of our planet. Change the case to upper case. Save the result in # result_planet variable planet = 'earth' result_planet = planet.upper()
true
1bb5ff8de5379d3822e58371d0d144fc7f7a62b3
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 01/Exercise01_04.py
325
4.40625
4
""" (Print a table) Write a program that displays the following table: a a^2 a^3 1 1 1 2 4 8 3 9 27 4 16 64 """ print(f'{"a":<5}{"a^2":<7}{"a^3":<7}') # Display heading for i in range(1, 5): # 1 up to 5, but not including 5 print(f'{i:<5}{i**2:<7}{i**3:<7}')
true
ba7705aa817f7972159bb736acd2960304a9c5bc
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 04/Ch_04_Project_03.py
778
4.3125
4
''' (Days of a month) Write a program that prompts the user to enter the year and the first three letters of a month name (with the first letter in uppercase) and displays the number of days in the month. ''' import sys year = int(input("Enter a year: ")) month = input("Enter a month: ") isLeapYear = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) months_with_31_days = ["Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"] months_with_30_days = ["Apr", "Jun", "Sep", "Nov"] if month == "Feb": if isLeapYear: days = 29 else: days = 28 elif month in months_with_31_days: days = 31 elif month in months_with_30_days: days = 30 else: print(month, "is not a correct month name") sys.exit() print(month, year, "has", days, "days")
true
e5e09c374d52289299d6ff658d6bb76565a55794
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 07/Ch_07_Project_02_Occurrence_of_Numbers.py
780
4.28125
4
''' (Count occurrence of numbers) Write a program that reads some integers between 1 and 100 and counts the occurrences of each. Note that if a number occurs more than one time, the plural word “times” is used in the output. Note the integers are entered in one line separated by a space. ''' int_input = input("Enter integers between 1 and 100, inclusive: ") int_list = [int(num) for num in int_input.split(' ')] unique_integers = [] for num in int_list: if num not in unique_integers: unique_integers.append(num) unique_integers.sort() for num in unique_integers: occurrences = int_list.count(num) if occurrences > 1: print(str(num), "occurs", str(occurrences), "times") else: print(str(num), "occurs", str(occurrences), "time")
true
54e6787bec098cdac3637a8ad7bc4f8bc1ebb9cd
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 09/Ch_09_Project_02_Regular_Polygon.py
2,467
4.46875
4
''' (Geometry: n-sided regular polygon) An n-sided regular polygon’s sides all have the same length and all of its angles have the same degree (i.e., the polygon is both equilateral and equiangular). Design a class named RegularPolygon that contains: - A private int data field named n that defines the number of sides in the polygon. - A private float data field named side that stores the length of the side. - A private float data field named x that defines the x-coordinate of the center of the polygon with default value 0. - A private float data field named y that defines the y-coordinate of the center of the polygon with default value 0. - A constructor that creates a regular polygon with the specified n (default 3), side (default 1), x (default 0), and y (default 0). - The accessor and mutator methods for all data fields. - The method getPerimeter() that returns the perimeter of the polygon. - The method getArea() that returns the area of the polygon. The formula forcomputing the area of a regular polygon is area = (n * s^2) / (4 * tan(PI / n)). Write a test program that creates three RegularPolygon objects, created using RegularPolygon(), RegularPolygon(6, 4) and RegularPolygon(10, 4, 5.6, 7.8). For each object, display its perimeter and area. ''' import math class RegularPolygon: def __init__(self, n: int=3, side: float=1, x: float=0, y: float=0): self.__n = n self.__side = side self.__x = x self.__y = y # Setters (Mutators) def set_n(self, n: int) -> None: self.__n = n def set_side(self, side: float) -> None: self.__side = side def set_x(self, x: float) -> None: self.__x = x def set_y(self, y: float) -> None: self.__y = y # Getters (Accessors) def get_n(self) -> int: return self.__n def get_side(self) -> float: return self.__side def get_x(self) -> float: return self.__x def get_y(self) -> float: return self.__y def getPerimeter(self) -> float: return self.__n * self.__side def getArea(self) -> float: return (self.__n * self.__side ** 2) /\ (4 * math.tan(math.pi / self.__n)) def main(): rp = RegularPolygon() rp1 = RegularPolygon(6, 4) rp2 = RegularPolygon(10, 4, 5.6, 7.8) print(rp.getPerimeter(), rp.getArea()) print(rp1.getPerimeter(), rp1.getArea()) print(rp2.getPerimeter(), rp2.getArea()) main()
true
32b05a5b4b83400f5d8e0fd13575c23495c7a61e
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 02/Exercise_02_17.py
670
4.5625
5
''' (Health application: compute BMI) Body mass index (BMI) is a measure of health based on weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. ''' weight_pounds = float(input('Enter weight in pounds: ')) weight_kilograms = weight_pounds * .45359237 height_inches = float(input('Enter height in inches: ')) height_meters = height_inches * .0254 bmi = weight_kilograms / (height_meters ** 2) print(f'BMI is {bmi}')
true
53c2dcf2bc27e854f8f8e367ffd7bc56c973f77a
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 08/Ch_08_Project_05_Column_Sorting.py
1,570
4.5
4
''' (Column sorting) Implement the following function to sort the columns in a two-dimensional list. A new list is returned and the original list is intact. def sortColumns(m): Write a test program that prompts the user to enter a 3 by 3 matrix of numbers and displays a new column-sorted matrix. Note that the matrix is entered by rows and the numbers in each row are separated by a space in one line. ''' def main(): print("Enter a 3-by-3 matrix row by row: ") matrix = [] for i in range(3): s = input().strip().split() matrix.append([float(x) for x in s]) # Obtain the sorted matrix, without changing the original list sorted_matrix = sortColumns(matrix) # Display result print("The column-sorted list is") for i in range(3): for j in range(3): print(sorted_matrix[i][j], end=' ') print() def sortColumns(m: list) -> list: lst = m[:] # Copy the list passed through as an argument # Go column-by-column for col in range(len(lst[0])): # Go through each row in a column for row in range(len(lst) - 1): # Compare each row in a column to the next row in the same column for next_row in range(row + 1, len(lst)): # If the value in the next row of the same column is less than # current row if lst[next_row][col] < lst[row][col]: # Switch the values lst[row][col], lst[next_row][col] = lst[next_row][col], lst[row][col] return lst main()
true
fa8952bf19b5bcf5d7c67189a553f027ce2c8329
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 15/RecursiveReverseString.py
628
4.40625
4
''' (Print the characters in a string reversely) Write a recursive function that displays a string reversely on the console using the following header: def reverseDisplay(value): For example, reverseDisplay("abcd") displays dcba. Write a test program that prompts the user to enter a string and displays its reversal. ''' def main(): s = input("Enter a string: ") reverseDisplay(s) def reverseDisplay(value): reverseDisplay_helper(value, len(value) - 1) def reverseDisplay_helper(value, index): if index != -1: print(value[index], end='') reverseDisplay_helper(value, index - 1) main()
true
56f6202687067d9e75668bf807408a8adc0f581f
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 09/Ch_09_Project_05_Split_String.py
968
4.46875
4
''' (Split a string) Write the following function that splits a string into substrings using delimiter characters. def split(s, delimiters); For example, split("AB#C D?EF#45", "# ?") returns a list containing AB, C, D, EF, and 45. Write a test program that prompts the user to enter a string and delimiters and displays the substrings separated by exactly one space. (You are not allowed to use the regex for splitting a string in this exercise.) SAMPLE RUN: Enter a string: Welcome to Python Enter delimiters: oe W lc m t Pyth n ''' def main(): s = input("Enter a string: ") delimiters = input("Enter delimiters: ") print(' '.join(split(s, delimiters))) def split(s, delimiters): substring = [] temp_s = '' for ch in s: if ch not in delimiters: temp_s += ch else: substring.append(temp_s) temp_s = '' if temp_s: substring.append(temp_s) return substring main()
true
5c2db5df316d83f8bb5c7e05acddc2e4a31d451a
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 15/RecursiveBinaryToDecimal.py
790
4.21875
4
''' (Binary to decimal) Write a recursive function that parses a binary number as a string into a decimal integer. The function header is as follows: def binaryToDecimal(binaryString): Write a test program that prompts the user to enter a binary string and displays its decimal equivalent. ''' def main(): n = input("Enter a binary number: ") print(n, "is decimal", binaryToDecimal(n)) # https://www.wikihow.com/Convert-from-Binary-to-Decimal def binaryToDecimal(binaryString): # Base case, if there was only 1 binary number provided if len(binaryString) == 1: return int(binaryString[0]) * (2 ** (len(binaryString) - 1)) else: return int(binaryString[0]) * (2 ** (len(binaryString) - 1)) +\ binaryToDecimal(binaryString[1:]) main()
true
2f43f33a8a3a6d43ea4333bdee2cbe8e7a9ce9be
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 06/Ch_6_Project_05.py
1,977
4.40625
4
''' (Binary to hex) Write a function that parses a binary number into a hex number. The function header is: def binaryToHex(binaryValue) Write a test program that prompts the user to enter a binary number and displays the corresponding hexadecimal value. Use uppercase letters A, B, C, D, E, F for hex digits. ''' def main(): binary = input("Enter a binary number: ") print("The hex value is", binaryToHex(binary)) def binaryToHex(binaryValue: str) -> str: binary_temp = binaryValue hex_value = "" # Stores the hex value # Line up to 4 binary numbers , e.g. 01 would become 0001 while len(binary_temp) % 4 != 0: binary_temp = "0" + binary_temp # Go through every 4 numbers of the binary number # E.g., 11101100101001 --> 0011 1011 0010 1001 binary_section = "" start_index = 0 while start_index < len(binary_temp): # Look at a section (4 numbers) of the binary number binary_section = binary_temp[start_index:start_index + 4] # Calculate the decimal number # E.g. 1010 -> 1 of 8, 0 of 4, 1 of 2, and 0 of 1 -> 8 + 0 + 2 + 0 = 10 decimal_num = 0 for i in range(len(binary_section)): if i == 0: decimal_num += (int(binary_section[i]) * 8) elif i == 1: decimal_num += (int(binary_section[i]) * 4) elif i == 2: decimal_num += (int(binary_section[i]) * 2) else: decimal_num += (int(binary_section[i]) * 1) # Convert the decimal number to the hex value, e.g. 10 -> A if decimal_num > 9: # 10 -> A, 11 -> B, ... 15 -> F hex_value += chr(ord('A') + (decimal_num - 10)) else: # Append 0 - 9 to hex value hex_value += str(decimal_num) # Go to the next section of 4 numbers in the binary number start_index += 4 # Return the hex value return hex_value main()
true
84646a1c05ab847dc3affde872767ef4e0a9b41e
CUGshadow/Python-Programming-and-Data-Structures
/Chapter 03/Ch_03_Project_02.py
746
4.1875
4
''' (Algebra: solve 2 × 2 linear equations) You can use Cramer’s rule to solve the following 2 × 2 system of linear equation: ax + by = e cx + dy = f x = (ed - bf) / (ad - bc) y = (af -ec) / (ad - bc) Write a program that prompts the user to enter a, b, c, d, e, and f and display the result. If ad - bc is 0, report that “The equation has no solution.” ''' a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) d = float(input('Enter d: ')) e = float(input('Enter e: ')) f = float(input('Enter f: ')) if a * d - b * c == 0: print('The equation has no solution.') else: x = (e * d - b * f) / (a * d - b * c) y = (a * f - e * c) / (a * d - b * c) print('x is', x, 'and y is', y)
false
517e025137e0d87cc2b4d09644ebe3d8e5c4076d
finder-ls/python
/python基础/基本索引.py
369
4.125
4
# 区别于切片概念的区间取值,基本索引是取单个值。 # 超过索引范围使用会报错,切片则不会报错,切片是返回【求的索引范围与实际存在的索引范围】交集部分。 a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(a[-1]) print(a[0]) # 超过下标范围报错,IndexError: list index out of range print(a[-11]) print(a[10])
false
d8a08ff21f8bd286d2509ea93c815401c64e8dd6
finder-ls/python
/python函数/range函数.py
842
4.71875
5
# python2中使用range返回时list;python3中返回是<class 'range'> ''' 一、语法: range(stop) range(start,stop,step) # 左闭右开 start:计数从start开始,默认是从0开始。eg:range(5)等价于range(0,5) stop:计数到stop结束,但不包括stop。eg:range(0,5)是[0,1,2,3,4],没有5 step:步长,默认为1。eg:range(0,5)等价于range(0,5,1) 注意: 返回值:一个可迭代对象(类型是对象),不是列表,所以打印的时候不会打印列表 list() 函数[对象迭代器]可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表 ''' for i in range(10): print(i) print(type(range(10))) # <class 'range'> print(type(list(range(10)))) # 使用list()将range生成的对象转换成列表 print(type(tuple(range(10)))) print(type(set(range(10))))
false
d09c0e59b2fab0d0839189bf68a6672d37571297
finder-ls/python
/python基础/变量练习-个人信息.py
572
4.25
4
""" 姓名:小明 年龄:18岁 是否男生:是 身高:170 体重:70公斤 """ # pyton 中,定义变量时不需要指定变量的类型 # 在运行时,python解释器,会根据赋值语句等号右边的数据自动推导出变量中保存数据的准确类型 # str表示时一个字符串类型 name = "小明" # int 表示一个整数类型 age = 18 # bool 表示一个布尔类型,真 True 或者 假 False gender = True # 是男生 # float 表示是一个小数类型,浮点数 height = 170 weight = 70 print(name, age, gender, height, weight)
false
6ff0a4dabe3c70376f6e2f64889aeca6444488d8
deepikaasharma/print_vs_return
/main.py
560
4.21875
4
'''A quick print vs return example''' # define a function that returns the input 'x', multipled by 2 def return_2x(x): return 2*x # call the function and print its return value print(return_2x(3)) # define a new function that prints the result of multiplying the input 'x' by 2 def print_2x(x): print(2*x) # call the function to see the result print_2x(3) # What happens if we call print() on our print_2x function? Can you explain the output? print(print_2x(3)) ''' Galvanize Data Science Prep https://www.galvanize.com/data-science/prep '''
true
d4375fa92382fc18132ad7df4cd0bd245ef8d4fd
sarsatis/PythonMasterClass
/2_program_flow/3_truthy_values.py
310
4.21875
4
# https://docs.python.org/3/library/stdtypes.html # In the below code 0 and '' is treated as boolean values if 0: print("True") else: print("False") name = input("Please enter your name: ") # if name: if name != "": print("Hello, {}".format(name)) else: print("Are you the man with no name?")
true
0c026a5e80b4071bdd00609228bb4702b9309fa8
anzhihe/learning
/python/source_code/source_code_of_lp3thw/ex6old.py
1,481
4.34375
4
# 将“字符串”赋值给"变量x",该字符串中有个位置是用“%d”(包含格式)来代替的。%d这个符号看起来有两个作用:第一个作用是“占位符”——正名这个位置将来会有个东西放在这里;第二个作用是“这个东西的格式”,既然其使用了%d,我认为其应该是digital——数字的。 x= "There are %d types of people." %10 # 建立了给新的变量binary,将字符串“binary”赋值给了它。一般来说,变量会用简单的写法,竟然也可以直接使用单词。 binary="binary" do_not="don't" y="Those who know %s and those who %s."%(binary,do_not) print (x)# print() 是个函数,必须有() print (y) print ("I said: %r."% x) print ("I also said:'%s'."%y)#Print后面每次都要加满括号。 hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print (joke_evaluation% hilarious) w="This is the left side of..." e= "a string with a right side." print (w+e) # 只要将格式化的变量放到字符串中,再紧跟着一个百分号%,再紧跟着变量名即可。唯一要注意的地方,是如果你想要在字符串中通过格式化字符放入多个变量的时候,[你需要将变量放到()圆括号里,变量之间采用逗号,隔开。] #试着使用更多的格式化字符,例如%s、%d、%r。例如 %r%r就是是非常有用的一个,它的含义是“不管什 么都打印出来”。
false
fd5d1449626d48e01be32a8d4fd680a25843a74b
anzhihe/learning
/python/practise/learn-python/python_advanced/lambda.py
1,554
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @FileName: lambda.py @Function: lambda表达式 @Author: Zhihe An @Site: https://chegva.com @Time: 2021/7/22 """ """lambda表达式""" """ 定义函数的语法格式: def 函数名([形式参数1, 形式参数2, ..., 形式参数n]): 函数体 当函数体中只有一行return语句时,函数的定义可以用一个lambda表达式来代替,其语法格式为: lambda [形式参数1, 形式参数2, ..., 形式参数n]: 关于形式参数的表达式 与定义函数的语法格式相比,lambda表达式: (1) 没有函数名 (2) 没有关键字def (3) 没有小括号 (4) 关于形式参数的表达式相当于函数的返回值 lambda表达式就是匿名简化版的函数 """ def add(num1, num2): return num1 + num2 print(add(1, 2)) # 3 print((lambda num1, num2: num1 + num2)(1, 2)) # 3 """ 在python中,一切皆为对象。所以,lambda表达式也是对象,从而lambda表达式可以被赋值给变量 """ le = lambda num1, num2: num1 + num2 print(le(1, 2)) # 3 """ 因为lambda表达式是匿名简化版的函数,所以,lambda表达式可以作为函数的实参 """ result = map(lambda x: x * x, [1, 2, 3, 4]) print(list(result)) # [1, 4, 9, 16] """ 因为lambda表达式是匿名简化版的函数,所以,lambda表达式可以作为函数的返回值 """ def do_sth(): return lambda num1, num2: num1 + num2 print(do_sth()(1, 2)) # 3
false
cd11ecd53f404c7542d9bf13f91e97309abfe904
beepscore/LearnPythonTheHardWay
/ex15.py
925
4.25
4
#!/usr/bin/python #import sys module from sys import argv # get filename as a command line argument # advantage- can be supplied programmatically, doesn't require user input # argv[0] is the script name # reference http://docs.python.org/library/sys.html script, filename = argv # note txt_file is a file object, not a string txt_file = open(filename) print "Here's your file %r:" % filename print txt_file.read() txt_file.close() # get filename from user input # advantage- user can choose file at runtime. print "Type the filename again:" file_again = raw_input("> ") txt_file_again = open(file_again) print txt_file_again.read() txt_file_again.close() #to open python from command line and read file: #$ python #>>> text_file = open('ex15_sample.txt') #>>> print text_file.read() #This is stuff I typed into a file. #It is really cool stuff. #Lots and lots of fun to have in here. #>>> text_file.close() #>>> quit()
true
c4335cc9a4381cef34004879fbd1cc58a3b44c67
Uttam-1234/BMI-CALCULATOR
/main.py
489
4.28125
4
# 🚨 Don't change the code below 👇 height = input("enter your height in m: ") weight = input("enter your weight in kg: ") # 🚨 Don't change the code above 👆 print(type(height)) #Convert the str type to int type with a variable int_weight=int(weight) #Height should be float int_height=float(height) #Calculate the bmi using type bmi=int_weight/(int_height**2) print(type(bmi)) #Convert the float type to int type int_bmi=int(bmi) print(type(int_bmi)) print(int_bmi)
true
6e1a78abd2aff8a23f7958dac2e99942c2dbea07
GeorgeNagel/randolang
/generate_words.py
1,144
4.1875
4
"""Generate new words and save them to file. Usage: python generate_words <method> <number_of_words> <order> method - One of "tuples", "letters", "syllables", "phones" number_of_words - The number of new words to generate order - The order of the markov tree used. When using the 'tuples' method, the number of words to join. """ import sys from randolang import generate_words from tools.words_cache import WordsCache if __name__ == '__main__': method = sys.argv[1] if len(sys.argv) < 3: number_of_words = 100 else: number_of_words = int(sys.argv[2]) if len(sys.argv) < 4: order = 2 else: order = int(sys.argv[3]) print "Number of words: %d. Method: %s. Order: %d" % ( number_of_words, method, order ) print "Generating words..." words_cache = WordsCache() words_cache.load_all_caches() words_cache = generate_words(number_of_words=number_of_words, order=order, words_cache=words_cache, method=method) words_cache.save_all_caches() print "Done"
true
29d403cb40f1dcee3170c4c1caa39e132ef772b1
sindhumantri/common_algorithms
/bisection_method.py
734
4.125
4
def opposite_signs(a, b): return ((a < 0 and b > 0) or (a > 0 and b < 0) or (a == 0 or b == 0)) # This last case is specific to bisection method. def bisection_method(f, a, b, iterations): """Find a root of function f in the interval [a, b].""" mid = (a + b) / 2 for _ in xrange(iterations - 1): if opposite_signs(f(a), f(mid)): b = mid mid = (a + b) / 2 elif opposite_signs(f(mid), f(b)): a = mid mid = (a + b) / 2 else: return mid return mid def main(): f = lambda x: 3.0 * (x + 1.0) * (x - 0.5) * (x - 1.0) print bisection_method(f, -2.0, 1.5, 3) if __name__ == "__main__": main()
false
9916fcf47f26737cf43c695edd564c406a728829
sindhumantri/common_algorithms
/quickselect.py
1,177
4.125
4
import random def partition(arr, left, right, pivot_index): """Partition arr around element at pivot index so that all elements less than the pivot are left of the pivot and all elements greater than the pivot are right of the pivot.""" pivot = arr[pivot_index] arr[pivot_index], arr[right] = arr[right], arr[pivot_index] store_index = left for index in xrange(left, right): if arr[index] < pivot: arr[store_index], arr[index] = arr[index], arr[store_index] store_index += 1 arr[store_index], arr[right] = arr[right], arr[store_index] return store_index def quickselect(arr, k): """Find the kth smallest item in an unsorted array arr.""" left = 0 right = len(arr) - 1 while True: pivot_index = random.randint(left, right) pivot_index = partition(arr, left, right, pivot_index) if k == pivot_index: return arr[k] elif k < pivot_index: right = pivot_index - 1 else: left = pivot_index + 1 def main(): arr = [8, 9, 7, 6, 5, 4, 2, 3, 1] print quickselect(arr, 3) if __name__ == "__main__": main()
true
24ce7aa02c5cfbc931d63f8ac00e584e9bf9a72b
Harsh652-cpu/16Novpy21
/prac7.py
222
4.1875
4
#program to calculate the sum and average of first 10 numbers i=0 s=0 while(i<=10): s=s+i i=i+1 avg=float(s)/10 print("The sum of first 10 numbers is:-"+str(s)) print("The average of first 10 numbers is:"+str(avg))
true
2b99f46891c48027b6cf11e9d1cfbbd0f4e373d1
Harsh652-cpu/16Novpy21
/prac1.py
700
4.1875
4
#Write a program to calculate tax given the following conditions: #if taxable income is 1,50,001-300,000 then charge 10% tax #if taxable income is 3,00,001-500,000 then charge 20% tax #if taxable income is above 5,00,001 then charge 30% tax min1=150001 max1=300000 rate1=0.10 min2=300001 max2=500000 rate2=0.20 min3=500001 rate3=0.30 income=int(input("Enter the income:")) taxable_income=income-150000 if(taxable_income<=0): print("No tax") elif(taxable_income>=min1 and taxable_income<max1): tax=(taxable_income-min1)*rate1 elif(taxable_income>=min2 and taxable_income<max2): tax=(taxable_income-min2)*rate2 else: tax=(taxable_income-min3)*rate3 print("Tax="+str(tax))
true
ce306863c390ced4690e35d4ee16f805da1d6e6d
Liu-moreira/exerciciogustavo
/exercicio1.py
380
4.125
4
# # Faça um programa que pergunta a idade do usuário e informe se # # ele está apto a votar ou não. idade = int(input('Qual a sua idade?: ')) if idade < 16: print('Voto inválido!') elif idade >= 16 and idade < 18: print('Voto opcional!') elif idade >= 18 and idade <= 70: print('Voto Obrigatório!') else: if idade > 70: print('Voto opcional!')
false
d9967d93a4284abedc77e374ba55eccae235d094
yorktronic/data_science
/thinkful/Unit1/other_scripts/fibonacci.py
507
4.1875
4
# Provide num and fibonacci will produce a list with that many numbers in the fibonacci sequence def fibonacci(n): if n == 0: return [0] elif n == 1: return [0, 1] else: sequence = [0,1] while len(sequence) <= n: sequence.append(sequence[-2] + sequence[-1]) return sequence def fizbuzz(): for num in range(1,100): if ((num % 3 == 0) and (num % 5 == 0)): print "FizBuzz!" elif (num % 3 == 0): print "Fizz!" elif (num % 5 == 0): print "Buzz!" else: print num
true
df9e4d0d832b6b6d951b29de736e7d19dbed2c88
STiashe/python
/lesson1/5.py
1,691
4.25
4
x = int(input('ВВЕДИТЕ ЗНАЧЕНИЕ ВЫРУЧКИ ВАШЕЙ ФИРМЫ: РУБ. ')) # выручка y = int(input('ВВЕДИТЕ ЗНАЧЕНИЕ ИЗДЕРЖЕК ВАШЕЙ ФИРМЫ: РУБ. ')) # издержки z = int(input('ВВЕДИТЕ ЧИСЛЕННОСТЬ СОТРУДНИКОВ ВАШЕЙ ФИРМЫ: ')) # сотрудники if x > y: # если выручка больше издержек r = x - y # высчитываем прибыль q = (((x - y) / x) /100) * 100 # высчитываем рентабельность v = x / z # высчитываем прибыль на 1 сотрудника и отображаем результаты print('ВАША ФИРМА ОТРАБОТАЛА С ПРИБЫЛЬЮ: РУБ. ', r) print('РЕНТАБЕЛЬНОСТЬ ФИРМЫ: ', q) print('ЧИСЛЕННОСТЬ СОТРУДНИКОВ ВАШЕЙ ФИРМЫ: ', z) print('ПРИБЫЛЬ ФИРМЫ В РАСЧЕТЕ НА ОДНОГО СОТРУДНИКА: ', v) elif x < y: # если выручка меньше издержек t = y - x # высчитываем долги v = x / z # высчитываем прибыль на 1 сотрудника и отображаем результаты print('ВАША ФИРМА ОТРАБОТАЛА С ИЗДЕРЖКАМИ И УШЛА ДОЛГИ НА: РУБ.', t) print('ЧИСЛЕННОСТЬ СОТРУДНИКОВ ВАШЕЙ ФИРМЫ: ', z) print('ПРИБЫЛЬ ФИРМЫ В РАСЧЕТЕ НА ОДНОГО СОТРУДНИКА: ', v) elif x == y: print('ВАША ПРИБЫЛЬ И ИЗДЕРКИ РАВНЫ')
false
288479416357cc9dbf7633599a9687285b409f7b
hkommineni/Crypto3
/Week12/Week12.py
2,529
4.1875
4
from Crypto.Util.number import getStrongPrime # Author: Harish Kommineni # Date: November 2, 2016 #This method is to find the inverse of given two numbers using Extended Euclidean Algorithm def invmod(a, b): m = b x, lastx = 0, 1 y, lasty = 1, 0 while b: q = a / b a, b = b, a % b x, lastx = lastx - q * x, x y, lasty = lasty - q * y, y return lastx % m # This method is to implement the RSA Algorithm def implementRSA(): """Implement RSA""" def encrypt(m, e, n): m = long(m.encode('hex'), 16) return pow(m, e, n) def decrypt(c, d, n): m = pow(c, d, n) m = hex(long(m)) return m[2:-1].decode('hex') bits = 1024 e = 3 p, q = getStrongPrime(bits, e), getStrongPrime(bits, e) print 'Value of p:', p print 'Value of q:', q print q n = p * q et = (p-1) * (q-1) d = invmod(e, et) m = "No Pain No Gain!" print 'Encrypting:', m c = encrypt(m, e, n) print 'c:', c m = decrypt(c, d, n) print 'Decrypted: ', m def e3RsaAttack(): """Implement an E=3 RSA Broadcast attack""" #http://stackoverflow.com/a/358134 def nth_root(x,n): """Finds the integer component of the n'th root of x, an integer such that y ** n <= x < (y + 1) ** n. """ high = 1 while high ** n < x: high *= 2 low = high/2 while low < high: mid = (low + high) // 2 if low < mid and mid**n < x: low = mid elif high > mid and mid**n > x: high = mid else: return mid return mid + 1 m = "No Pain No Gain!" print 'Encrypting:', m m = long(m.encode('hex'), 16) bits = 1024 e = 3 pubkeys = [getStrongPrime(bits, e) * getStrongPrime(bits, e) for _ in xrange(3)] captures = [pow(m, e, n) for n in pubkeys] c0, c1, c2 = [c % n for c,n in zip(captures, pubkeys)] n0, n1, n2 = pubkeys ms0 = n1 * n2 ms1 = n0 * n2 ms2 = n0 * n1 N012 = n0 * n1 * n2 result = ((c0 * ms0 * invmod(ms0, n0)) + (c1 * ms1 * invmod(ms1, n1)) + (c2 * ms2 * invmod(ms2, n2))) % N012 m = nth_root(result, 3) m = hex(long(m)) m = m[2:-1].decode('hex') print 'Decrypted: ', m # This is the main method to implement Week12 exercises. if __name__ == '__main__': for f in (implementRSA, e3RsaAttack): print f.__doc__.split('\n')[0] f() print
false
9143d522a670e4da8bbbfeb23a3c994592725e50
john-ppd/Python
/files_reading_from_external.py
945
4.46875
4
#since the file my_list.txt is in the same folder as this file, I can simply call it without a complete path #there are different modes when you open a file, read will only let you read but not modify, write is you write, append you can only add to a value, r+ lets you read and write. read = r, write = w, append = a, r+ #this will read the file, we want to store the text in a variable my_list = open("my_list.txt", "r") #it is a good first step to check if a file is readable, will return true if it is (is true because its in read mode, if in write mode would not accept print(my_list.readable()) ''' #this will read entire file, it will set cursor at the end of the file so we cannot use .readline or .readlines()[1] functions with it uncommented print(my_list.read()) ''' #this will read one line and then move the cursor to the beginning of the next line print(my_list.readlines()[1]) #remember to close the file too my_list.close()
true
db45a82b39778a6c1de6ce28579315fe6d8fc2fb
Diganta13/Data-Analysis-with-python
/core_materials_python/refact_code_1.py
1,026
4.15625
4
# Initialize temperatures for various planets # http://www.smartconversion.com/otherInfo/Temperature_of_planets_and_the_Sun.aspx mercury = 440 venus = 737 mars = 210 # Compute temperature in Farenheit def compute_celsius(temp): """ Given a floaring point temperature temp in Kelvin, return the corresponding temperature in Celsius """ return temp - 275.15 def compute_farenheit(temp): """ Given a floating point temperature temp in Kelvin, return the corresponding temperature in Farenheit """ temp_celsius = compute_celsius(temp) return temp_celsius * 9 / 5 + 32 mercury_result = compute_farenheit(mercury) venus_result = compute_farenheit(venus) mars_result = compute_farenheit(mars) # Print out results def print_temp(planet, temp): """ Print out the average daily temps """ print("The daily average temperature on", planet, "is", temp, "Farenheit") print_temp("Mercury", mercury_result) print_temp("Venus", venus_result) print_temp("Mars", mars_result)
true
7818a8d59d3637b4e94978ae139f3695151a66f8
whybux/python_learn
/day07/practise03.py
700
4.21875
4
""" 练习3:设计一个函数返回给定文件名的后缀名。 获取文件名的后缀名 :param filename: 文件名 :param has_dot: 返回的后缀名是否需要带点 :return: 文件的后缀名 """ def get_suffix(filename='', has_dot=True): index = filename.rfind(".") if index >= 0: index = index if has_dot else index + 1 return filename[index:] return "" def main(): print(get_suffix("aaa.bbb", True)) print(get_suffix("aaa.bbb", False)) print(get_suffix("aaa.c.bbb", True)) print(get_suffix("aaa.c.bbb", False)) print(get_suffix("aaabbb", False)) print("___", get_suffix()) if __name__ == "__main__": main()
false
63b4f42ffebc0ffb661dd97d62d05cb536c5e922
zzlin55/LearnPython
/calculator.py
1,962
4.53125
5
# Author: Clifford Zhan # Date: 25.6.2019 # Project Name: Calculator # Version 1: a calculator that take the input from user and print result of calculation. Integers only. # Note: use regular expression to check validity. # The calculation includes + - * /. # To be add: # 1. calculation with more numbers # 2. Specify the calculation accuracy # 3. add more functions so it like stardard calculator # 4. UI import re # Convert string to number, and identify sign. def StrToNum(string): inputsign = 0 signcount = 0 for idx,char in enumerate(string): if char in ['+','-','*','/']: inputsign = char signcount = signcount+1 #Check if numbers are available. #use slice to find 2 numbers before and after sign. number1 = int(string[0:idx]) number2 = int(string[(idx+1):]) if signcount>1: print('You input too many signs at a time') break if inputsign == 0: print('you should input a sign to perform calculation') return number1,number2,inputsign #use regular expression to check if input is correct def stringcheck(string): stringformat = r'^\d+[\+\-\*\/]\d+$' if re.match(stringformat,string): #print('Input is valid') return 1 else: print('Input is invalid, please input a number followed by a sign and a number') return 0 print('Please input numbers with sign+-*/, finish with enter. Integers only') print('Type \'q\' to quit program') while(1): inputformula = input() if inputformula =='q': break if stringcheck(inputformula): num1,num2,inputsign = StrToNum(inputformula) if inputsign == '+': result = num1+num2 elif inputsign == '-': result = num1-num2 elif inputsign == '*': result = num1*num2 else: result = num1/num2 print('result is:',result)
true
ca05a3429ca658733c3210a94fc89ab5e86c7dcf
kpazoles/CodeAcademy
/Battleship.py
2,681
4.15625
4
from random import randint board=[["O"]*5 for x in range(5)] def print_board(board): for row in board: print " ".join(row) print "Let's play Battleship!" print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) #assigns a random location to the first ship first_ship_row = random_row(board) first_ship_col = random_col(board) #assigns a location to a second ship, and checks to make sure it isn't the same location as the first ship second_ship_row = random_row(board) while second_ship_row==first_ship_row: second_ship_row=random_row(board) second_ship_col = random_col(board) while second_ship_col==first_ship_col: second_ship_col=random_col(board) #print first_ship_row, first_ship_col #print second_ship_row, second_ship_col #assigns values for whether the ships are sunk (1) or not (0) first_ship_sunk=0 second_ship_sunk=0 #loops through 4 turns for turn in range(4): print "Turn ", turn+1 guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:")) if (guess_row == first_ship_row and guess_col==first_ship_col): print "Congratulations! You sank a battleship!" first_ship_sunk=1 #changes board to indicate positon where ship was sunk board[guess_row][guess_col]="-" elif guess_row==second_ship_row and guess_col==second_ship_col: print "Congratulations! You sank a battleship!" second_ship_sunk=1 board[guess_row][guess_col]="-" #this will execute as long as one of the ships isn't sunk yet elif first_ship_sunk+second_ship_sunk<2: #checks to see if guess is on the board if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "Oops, that's not even in the ocean." #checks to see if the guess has been made already in a previous turn elif(board[guess_row][guess_col] == "X") or (board[guess_row][guess_col]=="-"): print "You guessed that one already." else: print "You missed my battleships!" #marks location of guess on the board board[guess_row][guess_col] = "X" #at the end of the turn, if both the ships have been sunk, the game is over and the player has won if first_ship_sunk==1 and second_ship_sunk==1: print "You sank all my battleships - You win!" break print_board(board) #if first_ship_sunk==1 and second_ship_sunk==1: # print "You sunk all my battleships! You win!" else: print "Game Over"
true
842ed1f4027c1a2cdb3cecd0c09734f778f662a6
jackeast23/PythonBible
/hello_you.py
577
4.40625
4
# Ask user for name name = input('What is your name? ') # Ask user for age age = input('How old are you? ') # Ask user for city city = input('What city do you live in? ') # Ask user what they enjoy hobby = input('What do you enjoy doing in your freetime? ') # Create output text user_bio = name + " is " + age + " years old and lives in " + city + ". " + name + " likes " + hobby + "." string = "Your name is {} and you are {} years old. You live in {} and you like {}." output = string.format(name, age, city, hobby) # Print output to screen print(user_bio) print(output)
true
f28aaf85f82489bb2f8ecc7661b3d33c293a8b96
Lindisfarne-RB/GUI-L3-tutorial
/Lesson19.py
2,007
4.5625
5
'''Using rowspan and columnspan Sometimes when we're using a grid layout system, we might want a widget to span over more than one row or column like so: To do this, we can specify a columnspan or rowspan inside the .grid() function. A columnspan of 3 means that widget should take up 3 columns. Another parameter we can set for widgets using the grid function is sticky. This makes the widget stick to specified edges of its container. To set sticky you pass in any combination of the letters N, S, W, E (compass directions) as either a string: sticky="NS" or a tuple: sticky=(N, NW) Using sticky="WE" will make a widget the full width it can be, and sticky="NS" will make it full height. "NSWE" will make it fill all the space available to it. CREATE We've modified the code slightly so that you can explore columnspan and rowspan. Edit the code to make button4 span 3 columns. Make button5 span 2 rows. Make button8 span 2 columns. Click RUN to see how this looks. Hmm... button4 should fill the width of the window, add a sticky parameter to make it do that. Do the same for button8. Lastly, button5 should fill the height of the space it is in, add a sticky parameter to do that. ''' from tkinter import * from tkinter import ttk root = Tk() root.title("Grid Test") button1 = ttk.Button(root, text="Row 0, Col 0") button1.grid(row=0, column=0) button2 = ttk.Button(root, text="Row 0, Col 1") button2.grid(row=0, column=1) button3 = ttk.Button(root, text="Row 0, Col 2") button3.grid(row=0, column=2) button4 = ttk.Button(root, text="Row 1, Col 0") button4.grid(row=1, column=0, columnspan=3, sticky="WE") button5 = ttk.Button(root, text="Row 2, Col 0") button5.grid(row=2, column=0, rowspan=2, sticky="NS") button6 = ttk.Button(root, text="Row 2, Col 1") button6.grid(row=2, column=1) button7 = ttk.Button(root, text="Row 2, Col 2") button7.grid(row=2, column=2) button8 = ttk.Button(root, text="Row 3, Col 1") button8.grid(row=3, column=1, columnspan=2, sticky="WE") root.mainloop()
true