blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c71ce71d8c52327bf05eeea042ab5da2df22a512
jensengroup/molstat
/lectures_code/week_1/ex4_exercise_start.py
490
4.15625
4
# Example 4 # Exercise import random import matplotlib.pyplot as plt # initialize some variables n_particles = 100 n_steps = 1 dt = 0.01 # create the x - and y - coordinates x_positions = [ random.random() for i in range( n_particles ) ] y_positions = [ random.random() for i in range( n_particles ) ] # plot the x - and y - coordinates in a figure . plt.plot(x_positions , y_positions , 'ro') #explain what 'ro' does plt.axis((-10, 10, -10, 10)) plt.savefig('coordinates_start.png')
false
3fe9a1a897eddacb78317092d2f3dd7129fea614
ZacNovak/EvolveU
/Courses_Videos/Automate the Boring Stuff/collatz.py
307
4.1875
4
def collatz(number): if number%2 == 0: number = number//2 print(number) return number else: number = number*3+1 print(number) return number try: n = input("Enter number: ") while n != 1: n = collatz(int(n)) except ValueError: print('whoops, type an integer, bro.')
true
03eacd7b592698d45f3099f9e88f6f2577bf90f7
pradeepsathyamurthy/Python-Programming
/course1/Assignment5/chp5_excersises.py
2,086
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 23 22:22:54 2016 @author: pradeep Sathyamurthy """ # Count the number of items in the list lst=[12,23,23,12,12,43,56,67,43,34] counter=0 for lists in lst: counter=counter+1 # This is called counter print("Number of items in the list is: ",counter) # Total of a set of number lst=[12,23,23,12,12,43,56,67,43,34,1] sum=0 for lists in lst: sum=sum+lists # This is called accumilator print("Sum of the items in the list: ",sum) # Finding the largest value in the list lst=[12,23,23,12,12,43,56,67,43,34,1,-68] largest=0 for lists in lst: if(lists > largest): largest=lists print("Largest number in the list is: ",largest) # Finding the smallest number in the list lst=[12,23,23,12,12,43,-82,56,67,43,34,1,-68] smallest=None print("def smallest: ",smallest) for lists in lst: if(smallest is None or lists < smallest): smallest=lists print("Smallest Number is: ",smallest) # Alternate lst=[12,23,23,12,12,43,-82,56,67,43,34,1,-68] smallest=min(lst) print("Smallest Number is: ",smallest) # Excercise 5.1 counter=0 total=0 avg=0 while True: num=input("Enter a Number: ") if (num=='Done' or num=='done'): break else: try: num=int(num) total=total+num counter=counter+1 continue except: print("Invalid Input") continue avg=total/counter print(total, counter, avg) # Excercise 5.2 maxi=0 mini=None num=0 while True: num=input("Enter a Number: ") if (num=='Done' or num=='done'): break else: try: num=int(num) if(num==max or num > maxi): maxi=num if(mini is None or num < mini): mini=num except: print("Invalid Input") continue print("Maximum Number:::::: ",maxi) print("Minimum Number:::::: ",mini) print("Program Ends!")
true
daef715c5429fe4d82e4b353ca5dafebc40cbe7c
divyag13/Python-practice
/problem solving track/Beautiful Day at the movies.py
2,498
4.65625
5
'''Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number , its reverse is . Their difference is . The number reversed is , and their difference is . She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day. Given a range of numbered days, and a number , determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where is evenly divisible by . If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range. Function Description Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range. beautifulDays has the following parameter(s): i: the starting day number j: the ending day number k: the divisor Input Format A single line of three space-separated integers describing the respective values of , , and . Constraints Output Format Print the number of beautiful days in the inclusive range between and . Sample Input 20 23 6 Sample Output 2 Explanation Lily may go to the movies on days , , , and . We perform the following calculations to determine which days are beautiful: Day is beautiful because the following evaluates to a whole number: Day is not beautiful because the following doesn't evaluate to a whole number: Day is beautiful because the following evaluates to a whole number: Day is not beautiful because the following doesn't evaluate to a whole number: Only two days, and , in this interval are beautiful. Thus, we print as our answer. ''' #!/bin/python3 import math import os import random import re import sys # Complete the beautifulDays function below. def beautifulDays(i, j, k): count = 0 for num in range(i,j+1): rev = 0 div = num while num>0: rem = num%10 num = num//10 rev = rev*10 + rem print(rev) if (div - rev)%k ==0: count +=1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) result = beautifulDays(i, j, k) fptr.write(str(result) + '\n') fptr.close()
true
83782df34d181d4adec61930fcb10797d1a088f4
MrJay10/Graph-Algorithms
/Topological Sort.py
1,678
4.28125
4
class Graph: """ Uses a set data structure to store edges. """ def __init__(self, graph_dict=dict()): self._graph = graph_dict def add_vertex(self, vertex): if vertex not in self._graph.keys(): self._graph[vertex] = set() # make a new node and associate a set to store neighbors def add_edges(self, v1, v2): if v1 not in self._graph.keys(): self._graph[v1] = {v2} else: self._graph[v1].add(v2) self.add_vertex(v2) # add v2 as a node if it is not already present def vertices(self): return self._graph.keys() def top_sort_util(self, vertex, visited, stack): visited.add(vertex) for v in self._graph[vertex]: if v in visited: continue self.top_sort_util(v, visited, stack) stack.append(vertex) def top_sort(self): visited = set() # set which stores visited vertices stack = list() # stack to store topologically sorted vertices vertices = self.vertices() for vertex in vertices: if vertex in visited: continue self.top_sort_util(vertex, visited, stack) return stack if __name__ == '__main__': graph = Graph() graph.add_edges('a', 'c') graph.add_edges('b', 'c') graph.add_edges('b', 'e') graph.add_edges('c', 'd') graph.add_edges('d', 'f') graph.add_edges('e', 'f') graph.add_edges('a', 'c') graph.add_edges('f', 'g') t_sort = graph.top_sort() while t_sort: print(t_sort.pop(), end='')
true
eca80b6798e76f5275934187e9e041e5d8c25be6
fport/feyzli-python
/63.0 Generator.py
603
4.25
4
#Generator """ liste = list() for i in range(100): liste.append(i**2) for i in liste: print(i) """ def sayilariKaresiniAl(): for i in range(1,101): yield i**2 #cagırdigimiz zaman calıscak iterator = iter(sayilariKaresiniAl()) print(next(iterator)) #1 yazdırcak ve hafızadan silcek print(next(iterator)) # fazla bellek tutması gereken yerlerde generator kullanıyor. print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator)) print(next(iterator))
false
c854d3085c7622ac255b7ff6f204cfbaede056d5
DRomanova-A/Base_project_python
/основы программирования python (ВШЭ)/solutions/week-2/task_2_15_seq_len.py
944
4.28125
4
''' Длина последовательности Программа получает на вход последовательность целых неотрицательных чисел, каждое число записано в отдельной строке. Последовательность завершается числом 0, при считывании которого программа должна закончить свою работу и вывести количество членов последовательности (не считая завершающего числа 0). Числа, следующие за числом 0, считывать не нужно. Формат ввода: Вводится последовательность целых чисел, заканчивающаяся числом 0. ''' n = int(input()) len_ = 0 while n != 0: n = int(input()) len_ += 1 print(len_)
false
2b12422a6b2182048d72c61f1294295994931e8a
asej123456/practice
/6.3.py
508
4.125
4
m = input("Enter your integer : ") n = eval(m) l = n def Reverse(n): k = len(m) num = 0 i = 1 while i <= k: num += ((n % 10**i)//10**(i-1))*10**(k-i) #print("when i is " + str(i) + " num is " + str(num) ) #take the Sumnum n -= (n % 10**i) #print("when i is " + str(i) + " n is " + str(n)) i += 1 if num == l : print("This is a reverse number !") else: print("This is NOT a reverse number ") Reverse(n)
false
f782096d47cb4d8d4de5ea8b699610c642226dc8
Andi947/PythonMasterClass
/ProgramFlowChallenge/ProgramFlowChallengeQ.py
1,618
4.3125
4
# Create a program that takes an IP address entered at the keyboard # and prints out the number of segments it contains, and the length of each segment. # # An IP address consists of 4 numbers, separated from each other with a full stop. But # your program should just count however many are entered # Examples of the input you may get are: # 127.0.0.1 # .192.168.0.1 # 10.0.123456.255 # 172.16 # 255 # # So your program should work even with invalid IP addresses. We're just interested in the number of segments # and how long each one is # # Once you have a working program, here are some more suggestions for invalid input to test # .123.45.678.91 # 123.4567.8.9. # 123.156.289.10123456 # 10.10t.10.10 # 12.9.34.6.12.90 # '' - that is, press enter without typing anything # # This challenge is intended to practise for loops and if/e;se statements, so although # you could use other techniques (such as splitting the string up), that's not the # approach we're looking for here. ipAddress = input("Please enter your 4 number IP Address separated by '.': \n") noOfSegments = 0 lengthOfSegment = 0 ipAddressSegLengths = [] i = "" seg = '' for i in ipAddress: if i == ".": noOfSegments += 1 ipAddressSegLengths += str(lengthOfSegment) lengthOfSegment = 0 seg = '' else: lengthOfSegment += 1 if i != '.': lengthOfSegment = 0 lengthOfSegment += len(seg) ipAddressSegLengths += str(lengthOfSegment) print("The IP Address {0} has {1} segments.".format(ipAddress, noOfSegments)) print("They are of the following lengths: {}".format(ipAddressSegLengths))
true
287413cbded58f9f4ee1b18606b54890d0d87e2a
handaeho/lab_python
/lec04_exception/exception01.py
1,010
4.15625
4
""" error, exception : 프로그램 실행 중, 발생할 수 있는 오류 프로그램 실행 중, 오류가 발생했을 때, 해결 방법 => 오류가 발생한 위치를 찾아, 발생 하지 않도록 수정 필요. 아니면, 발생 하더라도 무시하고 실행 되도록 프로그램을 작성해야함. """ # prnit(1) ~~~> NameError # int() : 문자열을 정수로 변환 / float() : 문자열을 실수로 변환 n = int(input('input >>>')) # 입력된 내용이 문자열이 아닌 정수로 n에 저장 n1 = int('123') # '123'이 문자열이 아닌 정수로 n1에 저장 # n1 = int('123.') ~~~> '.' 때문에 ValueError 발생(정수로 바꿀 수 없기 때문) numbers = [1, 2, 3] # print(numbers[3]) ~~~> 범위 내에 없는 index를 출력하려고 하니까 IndexError 발생 # print('123' + 456) ~~~> 문자열('123')과 숫자(456)은 타입이 달라 '+'를 할 수 없음. TypeError 발생 # print(123/ 0) ~~~> ZeroDivisionError: division by zero. 0으로 나누기 불가
false
8f53e8274ab3d7eb9cf8c42f0677b64377b43b9b
shreyamalogi/Awesome_Python_Scripts
/BasicPythonScripts/Voting System/voting_system.py
1,335
4.15625
4
#two nominees for election nominee_1 = input("Enter the name of Nominee_1 : ") nominee_2 = input("Enter the name of Nominee_2 : ") nom_1_votes = 0 nom_2_votes = 0 #assigning voting ids votes_id = [1,2,3,4,5,6,7,8,9,10] num_of_voter = len(votes_id) #checking voting id if it is correct then allowing voter to vote and if already voted it will show already done while True: if votes_id==[]: print("voting session is over") if nom_1_votes>nom_2_votes: percent=(nom_1_votes/num_of_voter)*100 print(nominee_1," has won with ",percent,"% votes") break elif nom_2_votes>nom_1_votes: percent=(nom_2_votes/num_of_voter)*100 print(nominee_2," has won with ",percent,"% votes") break else: voter = int(input("Enter your voter id no. : ")) if voter in votes_id: print("You are a voter!!!") votes_id.remove(voter) vote = int(input("Enter your vote 1 or 2 : ")) if vote ==1: nom_1_votes+=1 print("Thank You for casting your vote") elif vote ==2: nom_2_votes+=1 print("Thank You for casting your vote") else: print("You are not a voter here or else you have already voted")
true
28ba4c6bc6ff7629b992bbb82af1a075cdd3ea3b
archdr4g0n/CSC221
/m2lab practice.py
1,153
4.21875
4
##Tracy Batchelor ##CSC 221 ##M2 Lab ##27 Sep 2017 def main(): verb_list = [ 'go', 'stop', 'eat', 'drop'] noun_list = [ 'tree', 'sword', 'apple', 'key', 'north'] phrase = input('Type in two words, a verb and a noun: ') #print(phrase.split(" ")) #make list action_list = phrase.split() print (action_list) verb = action_list[0] noun = action_list[1] # check if verb == 'quit': print('exiting') if verb not in verb_list: print('verb not in list') elif noun not in noun_list: print('I don\'t know how to',phrase) else: execute(verb,noun) # evaluate verb def execute(verb, noun): # print('I will', verb,'the',noun) verbs = {'go':'went', 'eat':'ate', 'stop':'stopped','drop':'dropped'} pastTense = verbs[verb] print('I ', pastTense, noun) main() ##x = ‘blue,red,green’ ##x.split(“,”) ## ##[‘blue’, ‘red’, ‘green’] ##>>> ## ##>>> a,b,c = x.split(“,”) ## ##>>> a ##‘blue’ ## ##>>> b ##‘red’ ## ##>>> c ##‘green’
false
2bfc5feb939e270c5127397a3e657ea3c5d12d02
bharatmazire/Python
/Programs/Advance/Turtle/ColorSpiral.py
606
4.15625
4
import turtle t = turtle.Pen() # initialize pen turtle.bgcolor("black") # setting background color to black # you can choose between 2 and 6 sides for some cool shapes ! sides = 6 # setting sides colors = ['red', 'yellow', 'blue', 'orange', 'green', 'purple'] # listing some colors for x in range(360): # looping t.pencolor(colors[x%sides]) # selecting color from list t.forward(x * 3/sides + x) # forwarding pen to some distance t.left(360/sides +1) # moving pen head to some distance (here : 61) t.width(x*sides/200) # setting pen width to some amount
true
0241ed1e96e4317fe84e7840345c6036ca41fc62
bharatmazire/Python
/Programs/Basic/RegularExpressions/pat_sub_count.py
909
4.15625
4
#!/usr/bin/python import re def read_file(fd): readed_file = fd.read() fd.close() return readed_file def replace_pattern(readed_file): pattern = input("enter the pattern to replace : ") count = eval(input("enter the count to replace : ")) new_replace = input("enter new replacement : ") if count <= len(re.findall(pattern,readed_file)): new_to_write = re.sub(pattern,new_replace,readed_file,count) print (new_to_write) return new_to_write else: print ("count invalid :") replace_pattern(readed_file) def write_file(new_to_write,file_name): fd = open(file_name,"w") print (fd.write(new_to_write)) fd.close() #fd = open(file_name) #print(fd.read()) def main(): file_name = input("enter file name to open : ") fd = open(file_name) readed_file = read_file(fd) new_to_write = replace_pattern(readed_file) write_file(new_to_write,file_name) if __name__ == '__main__': main()
true
fe62cacbc079324cb57d7ee09f9447560aa5d7a9
bharatmazire/Python
/Programs/Basic/ObjectOrientedProgramming/simple_bank.py
2,694
4.1875
4
#!/usr/bin/python # Write a program with class Bank having various bank fuction class Bank(object): ''' obj.Bank(<name> , <age>) it will create object of bank class which will allow to perform deposite , withdraw and cheack operation account nnumber will be generated automatically along with object ''' account_number = 0 def __init__(self,name,age): ''' Inital constructor It will initialise initial balance with 500 and automatic next account number will assigned to account number ''' Bank.account_number += 1 self.b_acc = Bank.account_number self.amount = 500 self.name = name self.age = age def deposite(self,amount): ''' It use to deposite the amount in account ''' self.amount += amount return self.amount def withdraw(self,amount): ''' It is used to withdraw amount from account probably sufficient amount should present in account ''' if self.amount >= (amount + 500): self.amount -= amount return self.amount else: return "not possible " def cheak(self): ''' Used to return the current balance and account number of account ''' return self.amount , self.b_acc #..................................................................................................... def object_creation(obj): ''' This function is not under class Bank It use to perdform various operations on account ''' operation = 0 while operation != 4: print("enter operation to perform !!") operation = eval(input("1.deposite 2.withdraw 3.cheack 4.exit : ")) if operation == 1: amount = eval(input("enter amount to deposite : ")) print ("total amount in account is : {}".format(obj.deposite(amount))) elif operation == 2: amount = eval(input("enter amount to withdraw : ")) print("total amount in account is : {}".format(obj.withdraw(amount))) elif operation == 3: amt , num = obj.cheak() print ("total amount in account is :{} with account number : {}".format(amt , num)) else: print ("thank you !!!") if __name__ == '__main__': choice = 0 obj = [] while choice != 2: name = input("enter name of user : ") # name of user age = eval(input("enter age of user : ")) # age of user obj_temp = Bank(name,age) # object of that same name as of user name object_creation(obj_temp) obj.append(obj_temp) choice = eval(input("enter choice 1.again 2.stop : ")) while True: op_c = input("enter name of user on whome you want to perform operation : ") if op_c in [x.name for x in obj]: for i in obj: if op_c == i.name: object_creation(i) break
true
aaff129eadfd169c154f999d582fd6cc043e78b6
bharatmazire/Python
/Programs/Basic/RegularExpressions/replaceTo_replaceBy.py
402
4.34375
4
#!/usr/bin/python import re def main(): string = input("enter the string : ") replaceTo = input("enter replace to string part : ") replaceBy = input("enter replace by string part : ") if replaceTo in string: new = re.sub(replaceTo,replaceBy,string) print ("new replaced string is : ",new) else: print ("{} is not present in {}",format(replaceTo,string)) if __name__ == '__main__': main()
true
ae979f185952c29e554b41b9e9318a774f762734
dunia98/Python-Course
/Week 2/Practice2-A (1).py
398
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[3]: def print_prime_numbers(n): n=int(input("enter number and check if it is a prime number or not :")) for i in range(1,n): i=i+1 if i%n==0: print(f"{n} is a composite number") break else: print(f"{i} is a prime number") print_prime_numbers(20) # In[ ]:
true
2a305c2d05c2d7218c4cf3a67b030617552356ad
zjj9527/pythonStuday
/继承/def_father.py
1,282
4.375
4
# Python 继承 # 继承允许我们定义继承另一个类的所有方法和属性的类。 # 父类是继承的类,也称为基类。 # 子类是从另一个类继承的类,也称为派生类。 # 1.创建父类 # 任何类都可以是父类,因此语法与创建任何其他类相同: class Person: def __init__(self,fname,lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname,self.lastname) p1 = Person("Bill","Gates") p1.printname() # 2. 创建子类 # 要创建从其他类继承功能的类,请在创建子类时将父类作为参数发送: class Student(Person): pass # 如果您不想向该类添加任何其他属性或方法,请使用 pass 关键字。 s1 = Student("Elon","Musk") s1.printname() # 3.添加__init__()方法 # 每次使用类创建新对象时,都会自动调用 __init__() 函数。 # 调用super()函数 # 添加属性 class Students(Person): def __init__(self,fname,lname,year): super().__init__(fname,lname) # 或者使用 Person.__init__(self,fname,lname) self.graduationyear = year # 添加方法 def welcome(self): print("Welcome",self.firstname,self.lastname,"to the class of",self.graduationyear) x = Students("Elon","Musk",2019) x.welcome()
false
93bb408e3a1105b37432b9d70c7f7111d8853723
TanYiXiang/Automate-The-Boring-Stuff-With-Python-Exercises
/Chapter 8/Regex Search.py
1,100
4.3125
4
# Regex Search.py # Author: Tan Yi Xiang # Source: Automate the Boring stuff with python Ch. 8 Project import os import sys import re """Search for a regex pattern in all txt files in a directory.""" def checkRegex(regex, textFileContents): """Check text file for regex matches Args: regex (Pattern[str]): The regex expression used to find matches. textFileContents(str) The contents of the text file. """ regexMatch = regex.findall(textFileContents, re.I) print(regexMatch) folderPath = input("Enter the directory path which you want to search for:\n") if not os.path.isdir(folderPath): print("The directory does not exist") sys.exit() regexExpressionString = input('Enter the regex expression to search for:\n') regexExpression = re.compile(regexExpressionString) for file in os.listdir(folderPath): if file.endswith('.txt'): textFilePath = os.path.join(folderPath, file) textFile = open(textFilePath, 'r+') textFileString = textFile.read() checkRegex(regexExpression, textFileString)
true
f84ecdd879aa5aabf4b921346efaa6a5a9dcfea9
hubbm-bbm101/lab5-exercise-solution-b2210356117
/2210356117_email.py
519
4.28125
4
# Write a Boolean function that checks if a string contains ‘@’ sign and at least one ‘.’ dot (disregard the order for # the sake of simplicity). Use that function to check if a user input is a valid e-mail or not. email = input("enter your mail: ") symbol_1 = False symbol_2 = False for i in email: if i == "@": symbol_1 = True elif i == ".": symbol_2 = True if symbol_1 and symbol_2: print("This is a valid e-mail address.") else: print("This isn't a valid e-mail address")
true
e8706edc4906ccc7152a25881655fac2d86932c9
Chriszhangmw/LeetCode
/Sort/Car Fleet.py
1,364
4.125
4
''' N cars are going to the same destination along a one lane road. The destination is target miles away. Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road. A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. The distance between these two cars is ignored - they are assumed to have the same position. A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. How many car fleets will arrive at the destination? Example 1: Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 and 8 become a fleet, meeting each other at 12. The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself. The cars starting at 5 and 3 become a fleet, meeting each other at 6. Note that no other cars meet these fleets before the destination, so the answer is 3. ''' def method(po,sp,target): car = [(p,s) for p,s in zip(po,sp)] car = sorted(car) t = [(target-p)/s for p,s in car] stack = [] # for time in t[::-1]:
true
f6d30a5ac740eb84100dc23f9ba2e338f44c1f87
mako101/training_dragon_python_basics
/Day1/Olu_AgeAppExercise/arenaLogic.py
2,305
4.25
4
#create an application that ask the user for his or her name, age, and gender #if user's age is less than 18, you should display "Hello [title] [name], you are not allowed into this arena" #if user's age is between 18 and 50, #if user is male, application should ask user to pay #if user is female, application should ask user not to pay #if payment is successful, application should display "Hello [title] [name], you are allowed into this arena" #if payment is not made, application should display "Thank you [title] [name], bye!!!" #if user is above 50, application should display "Hello [title] [name], you are allowed into this arena" #In above, #[title] is # Master for male below 18 and Mr for all males #Miss for female below 18 and Ms for all females #[name] is the user's name #please use modules def getResult(name, age, gender): #convert gender to upper gender = str(gender).upper() #convert age age = int(age) ###################Hiding function start####################### #function encapsulation def getTitle(age, gender): if gender == "M" and age < 18: return "Master" elif gender == "M" and age > 18: return "Mr" elif gender == "F" and age < 18: return "Miss" elif gender == "F" and age > 18: return "Ms" ###################Hiding function end####################### #get the title title = getTitle(age, gender) #logic if age < 18: #print not allowed print("Hello", title, name, "you are not allowed into this arena") elif age >=18 and age <= 50: if (gender == "M"): #male pays #ask for payment pay = str(input("Do you wish to pay? (Type Y for Yes and N for No)")).upper() if pay == "Y": #print allowed print("Hello", title, name, "you are allowed into this arena") else: #print bye print("Thank you", title, name, ", bye!!!") else: #female don't pay print("Hello", title, name, "you are allowed into this arena") elif age > 50: #print allowed print("Hello", title, name, "you are allowed into this arena")
true
37935b18e1c4477a6a50fab4da49366197608acd
mako101/training_dragon_python_basics
/Day3/Circular_App/circle.py
768
4.15625
4
class Circle(object): # this is a class variable, that will be used in methods pi = 3.14 def __init__(self, radius = 1): self.__radius = radius def getArea(self, radius = -1): # polimorfism here # if we have passed the radius value, it will use the user defined one # if we dont, it will usen the default __radius value # the app will run either way! # using default value if radius == -1: return self.pi * self.__radius ** 2 else: return self.pi * radius ** 2 # same here def getCircumference(self, radius = -1): if radius == -1: return 2 * Circle.pi * self.__radius else: return 2 * Circle.pi * radius
true
f84f343394cecde4e008192eaec8bde93c1e0ca5
kevinlu1248/ccc_python_lessons
/Lesson 1/review.py
693
4.15625
4
# Just a quick review # string formatting, conditionals, loops, and function # string formatting x = 5 print("x is {}".format(x)) print("x is {number}".format(number=x)) # if elif else statements age = 16 if age >= 18: print("You are an adult") elif 0 < age < 18: print("You are a minor") else: print("I don't even know what you are...") # while and for loops i = 0 while i < 5: print("i = {}".format(i)) i += 1 # this is equivalent to for i in range(5): # basically (0, 1, 2, 3, 4) print("i = {}".format(i)) # functions def area(s): return s * s side_length = 5 print("The area of a square of side length {} is {}".format(side_length, area(side_length)))
true
b22124819ab8f3c7860c33273eecff0c555d9364
canjelica/enter-if-you-dare
/Alpha-Health-Problem.py
1,208
4.5625
5
def isMagicString(string): """Returns True if string satisfies given requirements. 1) All of its characters are numbers (0-9) 2) At least one third of its characters are ‘3’ 3) The sum of its digits is a multiple of 3 >>> isMagicString("387") True >>> isMagicString("123") True >>> isMagicString("12345") False >>> isMagicString("123345") True >>> isMagicString("") False >>> isMagicString("123hs%") False >>> isMagicString("hi") False >>> isMagicString("3387") True """ overall_true = 0 one_third = len(string) / 3 is_3 = 0 digits_sum = 0 if string.isdecimal() == True: overall_true += 1 print(overall_true) else: return False for char in string: char = int(char) if char == 3: is_3 += 1 if is_3 >= one_third: overall_true += 1 print(overall_true) digits_sum = digits_sum + char print(digits_sum) if digits_sum % 3 == 0: overall_true += 1 print(overall_true) return overall_true >= 3
true
2eefcd9fdec0039bd16e965269fe3afbf2d1fa86
sirbobthemarvelous/Jupyter-Notebook-Tutorials
/Python for Beginners/(4) Lists, Tuples, and Sets.py
2,455
4.1875
4
horses = ['Howard', 'Mark', 'Phillip', 'Connie'] #a list of strings gorse = ['Carl', 'June'] wumbers = [1,4,2,3,5] print(horses.append('Ashley')) #appends another value to the end print(horses.insert(0,'Vriska')) #insert it at a specific index place #you can also insert a List instead of Just a value print(horses.extend(gorse)) # appends a List as a Single index print(horses.remove('Howard')) #removes a thing popped = horses.pop() #removes the last item on the List, useful for Stacks print(popped) #it also returns the last item on the List which you removed gorse.reverse() #reverses the order horses.sort() #sort by alphabetical order or by a specific number order #you can use .sort(reverse=True) to sort it in Reverse order borted = sorted(horses) #gives a sorted version without Sorting it print(borted) print(min(wumbers)) #return minimum number of list of numbers # max() returns max number, sum() returns sum of numbers in the list print(horses.index('Vriska')) #gives u the index of the thing in the list print('Mark' in horses) #gives whether it's true something is within the List for index,thing in enumerate(horses): #loops through a List print(index, thing) #enumerate gives the index number next to all of them print(horses) #prints out the values #len(list) just gives you the number of indecies not the string length print(horses[3]) #prints out a specific item in the list print(horses[-1]) #use negative numbers to go backwards, -1 is the last item print(horses[0:3]) #its like a substring for lists [) #or just use horses[:3] and it'll assume it starts from the beginning horseStr = 'chain'.join(horses) #prints out the things with a phrase joining them together horseSpl = horseStr.split('chain') #split this string into parts based on the delimiter print(horseStr) #lists are mutable, Tuples are NOT Torses = ('Firefox','Chrome','Tor', 'Safari') #tuples use paranthasis #Sets use curly brackets Sorses = {'Bob','Ally', 'Micheal','Sarah'} #Sets don't care about order, used to check Inclusion and Duplicated OVAses = {'Zyfre', 'Dylan', 'Sarah', 'Ally'} print(Sorses) print('Bob' in Sorses) #check if it's in there print(Sorses.intersection(OVAses)) #checks similar elements #.difference(OVAses) would show the ones that aren't shared #.union(OVAses) would show all elements in both without duplicates emptyList = [] #or list() emptyTuple = () #or tuple() emptySet = set() # {} would make an empty DICTIONARY
true
bebb31ff007d43ae2c3f1b1cee556228b6620ea6
iSn1ckers/Class_V2
/Class_V2.py
2,057
4.28125
4
# Домашнее задание к лекции 1.7 «Классы и их применение в Python» # Необходимо реализовать классы животных на ферме: # # Коровы, козы, овцы, свиньи; # Утки, куры, гуси. # Условия: # # Должен быть один базовый класс, который наследуют все остальные животные. # Базовый класс должен определять общие характеристики и интерфейс. class Animal: def __init__(self, name, age): self.name = name self.age = age class Cattle(Animal): hoofs = 4 class Birds(Animal): wings = 2 class Cows(Cattle): def got_milk(self): print('Mmm milk') class Goats(Cattle): def goat_milk(self): print('Козы как и коровы дают молоко') class Sheeps(Cattle): def wool(self): print('Благодаря овцам у вас будет шерсть') class Pigs(Cattle): def meat(self): print('Свинина, ням ням') class Ducks(Birds): def __init__(self, name, age, say): super().__init__(name, age) self.say = say class Chicken(Birds): def eggs(self): print('Куры это не только мясо, но и яйца') class Geese(Birds): def geese_meat(self): print('Гуси гуси га га га') burenka = Cows('burenka', 4) gavrusha = Cows('Gavrusha', 0.5) darkwing_duck = Ducks('Darkwing Duck', 9, "I am the terror that flaps in the night!") some_duck = Ducks('Duck', 1, 'quack quack') pig = Pigs('pig', 2) #print("Name: {} \nAge: {}\n".format(burenka.name, burenka.age)) #print("Name: {} \nAge: {} \nSay: {}\n".format(darkwing_duck.name, darkwing_duck.age, darkwing_duck.say)) #print("Name: {} \nAge: {}\n".format(gavrusha.name, gavrusha.age)) #print("Name: {} \nAge: {} \nSay: {}\n".format(some_duck.name, some_duck.age, some_duck.say)) #burenka.got_milk()
false
56114c35f38e89aceba7fc2062f2531756b9d50f
randallale/Ch.05_Looping
/5.1_Coin_Toss.py
666
4.28125
4
''' COIN TOSS PROGRAM ----------------- 1.) Create a program that will print a random 0 or 1. 2.) Instead of 0 or 1, print heads or tails. Do this using if statements. Don't select from a list. 3.) Add a loop so that the program does this 50 times. 4.) Create a running total for the number of heads and the number of tails and print the total at the end. ''' import random heads = 0 tails = 0 times = 0 start = True number = 0 while start == True: times += 1 print(times) number = random.randrange(2) if number == 0: heads += 1 number += 1 else: tails += 1 if number >= 20: start = False print(times)
true
cabb98b665041156a9068f07ea0a05785f638708
shirsrour/python_assignment_one
/hw_question1.py
944
4.375
4
def trifeca(word): """ Checks whether word contains three consecutive double-letter pairs. """ pairs = 0 i = 0 pairs = 0 while i < len(word): if i+1 == len(word): return False if word[i] == word[i+1]: pairs = pairs+1 i = i+2 else: i = i+1 pairs = 0 if pairs == 3: return True return False if __name__ == '__main__': # Question 1 example1 = 'aabbcc' return_value = trifeca(example1) print("Question 1 solution example1: " + example1 + ", result: " + str(return_value)) example2 = 'abccddee0123' return_value = trifeca(example2) print("Question 1 solution example2: " + example2 + ", result: " + str(return_value)) example3 = 'llkkbmm' return_value = trifeca(example3) print("Question 1 solution example3: " + example3 + ", result: " + str(return_value))
true
279e4dbd3476f1134b841c663cdecc6700ff1076
chikoungoun/OpenIntro
/Chapter 7/Annexes/Linear_Regression_Function.py
1,320
4.3125
4
import pandas as pd import math """ Function to compute the Linear Regression from a Pandas Dataframe """ d = pd.DataFrame({'A':[1,2,3,4,5,6],'B':[6,5,4,3,2,1]}) def linear_regression(x,y): #Small control to test the nature of the parameters (Should be dataFrame columns) if type(x) and type(y) is pd.Series: print('Series') df = pd.DataFrame() df['X'] = x df['Y'] = y df['XY'] = df['X']*df['Y'] df['X_squared'] = df['X']*df['X'] df['Y_squared'] = df['Y']*df['Y'] #Let's make this more readable by putting each of the Numerator and Denominator A = (df['Y'].sum() * df['X_squared'].sum()) - (df['X'].sum() * df['XY'].sum()) B = df.shape[0]*df['X_squared'].sum() -(df['X'].sum())**2 #We calculate the Y-intercept y_intercept = A/B #We know calculate the slope C = df.shape[0]*df['XY'].sum() - df['X'].sum()*df['Y'].sum() D = df.shape[0]*df['X_squared'].sum() - (df['X'].sum())**2 #separating the Numerator and Denominator makes it more readable slope = C/D #Gives the whole table #print(df) return (slope,y_intercept) else: print('Type should should be Series (a dataframe column)') print(linear_regression(d['A'],d['B']))
true
d8ec5615b1c76c41981c87cc3bbc34ca2c88f3af
saylerb/exercism
/python/guidos-gorgeous-lasagna/lasagna.py
1,284
4.3125
4
"""Functions used in preparing Guido's gorgeous lasagna. Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum """ EXPECTED_BAKE_TIME = 40 PREPARATION_TIME = 2 def bake_time_remaining(elasped_bake_time) -> int: """Calculate the bake time remaining. :param elapsed_bake_time: int - baking time already elapsed. :return: int - remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME'. Function that takes the actual minutes the lasagna has been in the oven as an argument and returns how many minutes the lasagna still needs to bake based on the `EXPECTED_BAKE_TIME`. """ return EXPECTED_BAKE_TIME - elasped_bake_time def preparation_time_in_minutes(number_of_layers) -> int: """Calculate the preparation time in minutes :param number_of_layers: int - the number of lasagna layers :return: int - total preparation time """ return PREPARATION_TIME * number_of_layers def elapsed_time_in_minutes(number_of_layers, elasped_bake_time): """Calculate the total elapsed time :param number_of_layers: int :param elasped_bake_time: int :return: int - total elapsed time """ return preparation_time_in_minutes(number_of_layers) + elasped_bake_time
true
8d82fcaa863e45ff6c0731db9388fe6b82934b40
pyhawaii/talks
/puzzles/checkio/electronic_station/longest_palindromic.soln.py
1,657
4.25
4
# The following puzzle comes from the checkio website and is used as the # basis for a group problem-solving session during one of our PyHawaii sessions # https://py.checkio.org/mission/the-longest-palindromic/ # Your task is to write a function that finds the longest palindromic substring # of a given string. # If you find more than one substring you should return the one which is closer # to the beginning. # VERSION 1 ------------------------------------- def longest_palindromic(text): '''Parse through the palindrome examining each substring (sub) spanning from first character to the last character. Then shift to examine the next substring spanning from the second character to the last character. Continue shifting across text to make ever shorter substrings. ''' pal_list = [] for x, _ in enumerate(text): for y in range(x+1, len(text)+1): # snip text from x up to but not including y # compare the reversed version to the forward version sub = text[x:y] if sub[::-1] == sub: pal_list.append(sub) return max(pal_list, key=len) # VERSION 2 ------------------------------------- ''' from itertools import combinations as C ​ def longest_palindromic(text): subs = (text[start: end] for start, end in C(range(len(text) + 1), 2)) return max((s for s in subs if s == s[::-1]), key=len) ''' if __name__ == '__main__': assert longest_palindromic("artrartrt") == "rtrartr" assert longest_palindromic("abacada") == "aba" assert longest_palindromic("aaaa") == "aaaa" print('All tests passed successfully')
true
630f6ece4c41629788ee5bc0c5b23d10a6f0a78e
eliumoraes/treinamentos_online
/05_Staircase.py
399
4.21875
4
''' Problema que resolvi no site hackerrank.com ''' #!/bin/python3 import math import os import random import re import sys # Complete the staircase function below. def staircase(n): spaces = ' ' * (n-1) step = '#' for i in range(n): print(spaces + step) spaces = spaces[:-1] step = step + '#' if __name__ == '__main__': n = int(input()) staircase(n)
true
b40209814bb93475f9ab256cd301fe39fb4cd6cd
chimnanishankar4/aws_practise
/2.py
202
4.375
4
#2. Write a Python program to find the most common elements and their counts of a specified text. from collections import Counter list=[1,2,3,4,1,2,6,7,3,8,1] cnt=Counter(list) print(cnt.most_common())
true
6c99847af32330965e4d5ad5f5dc0e927a58e0a1
SoyamDarshan/Python-Codes
/vowels.py
350
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 4 16:54:17 2018 @author: ThinkPad """ import scrabble vowels = "aeiou" def has_all_vowels(word): for vowel in vowels: if vowel not in word: return False return True for word in scrabble.wordlist: if has_all_vowels(word): print(word)
true
79aed13401935e9f27dbb96b32e741754e1fb1f5
FlyingMedusa/PythonCourse
/04_lekcja5Funkcje/poradnik_ogrodnika.py
1,348
4.125
4
# Ogrodnik. Utwórz program - udający poradnik ogrodnika. # Powinen zawierać dowolny słownik przypominający o obowiązkach ogrodniczych w zależności od miesiąca: # np. styczeń - bielenie pni drzew, październik - czas posadzić wiosenne krzewy. # Użytkownik może podać skróconą, 3 literową nazwę miesiąca i otrzymać poradę. # Użytkownik kończy korzystanie z programu naciśnięciem przycisku - Q. def get_month(): while True: miesiac = input("Podaj nazwę miesiąca jako 3 litery: ") if len(miesiac) != 3 or not miesiac.isalpha(): input("Nie pykło - ") else: break return miesiac.capitalize() seasonal_dict = { "Sty": "bielenie pni drzew", "Lut": "sypanie solą bo ślisko", "Mar": "Dbanie o przebiśniegi", "Kwi": "Zrywanie tulipanów", "Maj": "Zrywanie konwalii", "Cze": "Wysadzamy petunie", "Lip": "Skracanie pędów", "Sie": "zjadamy maliny", "Wrz": "Zbieramy kasztany", "Paź": "Zrywamy dynie", "Lis": "Grabimy liście", "Gru": "Dokarmiamy sikorki" } while True: month = get_month() if month in seasonal_dict: print(seasonal_dict[month]) else: print("Nie znam tego miesiaca") user_input = input("Czy chcesz kolejna porade: Y / N: ") if user_input.upper() == 'N': break
false
856ec2104c024d56fcd0a73893efd5bcf7505d8a
UniBond/210CT
/JackBond10.py
1,388
4.3125
4
#function for sub-sequence extraction def sequence(listVar): #variable declaration finalList = [] tempList = [] num = 0 #This for loop is to loop over all elements of the function argument #It compares each element to it's previous, which allows it to work #out when the end of that sub-sequence is for i in range(len(listVar)-1): if i == 0: tempList.append(listVar[i]) else: if listVar[i] >= listVar[i-1]: tempList.append(listVar[i]) if listVar[i] < listVar[i-1]: finalList.append(tempList) tempList = [] tempList.append(listVar[i]) finalList.append(tempList) #This for loop is to work out which sub-sequence is of greatest length #This loop works very similiarly to the one previously for i in range(len(finalList)): if i == 0: num = len(finalList[i]) listVar = finalList[i] else: if len(finalList[i]) > num: num = len(finalList[i]) listVar = finalList[i] return("The list with the largest length is " + str(listVar) + " which contains " + str(num) + " numbers.") #Below allows program to work. Test list, alongside function run and print listVar = [1,2,3,4,1,5,1,6,7] print(sequence(listVar))
true
df5f702b6010d5c29c11cd8deda832a98bf15f7a
lovejojoo/tip-calculator
/main.py
767
4.25
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Format the result to 2 decimal places = 33.60 #Print welcome title print("Welcome to the tip calculator!") #Ask user the cost of the total bill bill = float(input("What was the total bill? $" )) #Ask user how much percentage tip tip = int(input("What percentage tip would you like to give? 10, 12, 15? ")) #Ask user how many people are splitting the bil people = int(input("How many people to split the bill?")) tip_as_percent = tip / 100 total_tip_amount = bill * tip_as_percent total_bill = bill + total_tip_amount bill_per_person = total_bill / people final_amount = round(bill_per_person, 2) print(f"Each person should pay: ${final_amount}")
true
6feed912a123296074a8191503ece14f822c6f3a
dolphinxzhang/Converter
/Converter-1.py
1,848
4.46875
4
#Converter.py #Cindy Zhang, Crystal Zhu, Joyce Yuan #January 21st 2019 def DecimalToBinary(decimal): """ Converts a decimal number entered by user into the corresponding binary number. decimal: type string return: type string """ result_list= [ ] #binary list remainder= int(number) % 2 #the remainder is what we want result_list. append(remainder) #shifts the result list the right way quotient = int(number) / 2 while quotient != 0: remainder = quotient % 2 quotient = quotient / 2 result_list. append(remainder) #reads the list backwards print result_list result= ' ' for i in result_list: result=str(i) + result #gives the binary number return result def BinaryToDecimal(binary): """ Converts a binary number entered by user into the corresponding decimal number. binary: type string return: type string """ sum=0 for i in range(len(number)): #iterates through every position of the string if number[i] =='1': #if "1" is found on this position power= len(number)-1-i sum = sum + 2**(power) #let 2 take the power of that "1"'s position and add up all the powers of 2 according to the postiion of "1" in the string else: #if "0" is found pass #add nothing results=str(sum) #return results in the form of a string return results if __name__ == '__main__': number = raw_input("Enter a decimal number to convert to Binary: ") binary = DecimalToBinary(number) print print 'Entered Decimal: %s' % number print 'Binary: %s' % binary print number = raw_input("Enter a binary number to convert to Decimal: ") decimal = BinaryToDecimal(number) print print 'Entered Binary: %s' % number print 'Decimal: %s' % decimal print
true
1d69a828acb5273a45b791be4d962911dfa9723a
CesarRomeroDev/curso_basico_python
/ejercicios.py
2,090
4.25
4
#ejercicio 1 # Escribir un programa que pregunte el nombre del usuario en la consola y un número entero e imprima por pantalla en líneas distintas el nombre del usuario tantas veces como el número introducido. #print('Hola Mundo') #ejercicio 2 # Escribir un programa que pregunte el nombre completo del usuario en la consola y después muestre por pantalla el nombre completo del usuario tres veces, una con todas las letras minúsculas, otra con todas las letras mayúsculas y otra solo con la primera letra del nombre y de los apellidos en mayúscula. El usuario puede introducir su nombre combinando mayúsculas y minúsculas como quiera. # saludar = 'Hola Mundo' # print(saludar) #ejercicio 3 # nombre = input('escribe tu nombre: ') # print('!!hola ' + nombre + '¡¡') # suma = int(3 + 2) #ejercicio 4 # multiplicacion = int(2 * 5) # print(((suma) / (multiplicacion)) ** 2) # horas_trabajadas = int(input('Horas Trabajadas: ')) #ejercicio 5 # if horas_trabajadas == 1: # print('Tu pago corresponde a $100.00 pesos por una hora laborada') # elif horas_trabajadas == 2: # print('Tu pago corresponde a $200.00 pesos por dos hora laborada') # else: # print('Introduce el numero de horas trabajadas correctamente') # horas = float(input('Horas trabajadas: ')) #ejercicio 5 # coste = float(input('paga por hora: ')) # pago = horas * coste # print('tu pago es: ' + str(pago)) # n = int(input("Introduce un número entero: ")) #ejercicio 6 # suma = n * (n + 1) / 2 # print("La suma de los primeros números enteros desde 1 hasta " + str(n) + " es " + str(suma)) # kg = float(input('Tu peso en kg es: ')) #ejercicio 7 # mts = float(input('Tu altura en mts es: ')) # imc = round((kg) / (mts) **2,2) # print('Tu indice de masa corporal es: imc ' + str((imc))) # n = int(input('Introduce un numero entero: ')) #ejercicio 8 # m = int(input('Introduce otro numero entero: ')) # divicion = n // m # print(str(divicion) + ' es el cociente y un resto ' + str(n % m))
false
6a72ee5de3c1234063e233cc80c9611b0aaa63d4
spencerbertsch1/Full-Stack-Development
/OOP - Python Background/Inheritance/inheritance.py
941
4.75
5
# Create parent class class Parent(): """ We define the Parent class to identify the benifits of inheritance in OOP! """ def __init__(self, last_name, eye_color): print("Parent constructor has been called!") self.last_name = last_name self.eye_color = eye_color def show_info(self): print("Last name: " + self.last_name) print("Eye color: " + self.eye_color) #Inherits instance variables from parent - we can even inherit the __init__ method from the parent class class Child(Parent): def __init__(self, last_name, eye_color, number_of_toys): print("Child's constructor has been called!") Parent.__init__(self, last_name, eye_color) self.number_of_toys = number_of_toys def show_info(self): print("Last name: " + self.last_name) print("Eye color: " + self.eye_color) print("Number of toys: " + str(self.number_of_toys))
true
2b4b978c797b6bb8be2b502d8e04f6d7367fdf67
shmurygin-roman/geekbrains_lessons
/video_course/lesson_14_1.py
549
4.21875
4
# Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. # Примечание: Списки фруктов создайте вручную в начале файла. fruit_1 = ['яблоко', 'киви', 'виноград', 'банан', 'абрикос'] fruit_2 = ['клубника', 'персик', 'киви', 'абрикос', 'черешня'] fruits = [fruit for fruit in fruit_1 if fruit in fruit_2] print(fruits)
false
bc208bf7ea2b0b29bfcc857c50d65ee705051d1f
shmurygin-roman/geekbrains_lessons
/video_course/lesson_14_2.py
796
4.21875
4
# Дан список, заполненный произвольными числами. # Получить список из элементов исходного, удовлетворяющих следующим условиям: # Элемент кратен 3, # Элемент положительный, # Элемент не кратен 4. # Примечание: Список с целыми числами создайте вручную в начале файла. # Не забудьте включить туда отрицательные числа. 10-20 чисел в списке вполне достаточно. numbers = [20, 9, 13, -13, -9, 7, 8, 10, 15, -5, 18] numbers = [num for num in numbers if num % 3 == 0 and num > 0 and num % 4 != 0] print(numbers)
false
bec87ddd4d36727c307d642654209bc012d9ca63
shmurygin-roman/geekbrains_lessons
/course_1/lesson_1_6.py
1,494
4.3125
4
# Урок 1. Задание 6. # Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. a = int(input('Введите результат спортсмена в км в первый день: ')) b = float(input('Введите результат спортсмена в км который нужно достигнуть: ')) day = 1 if a >= b: print('Результат в первый день не может быть равен или превышать результат который нужно достигнуть!') else: while a < b: print(f'{day} день: {a}') day += 1 a = round(a * 1.1, 2) else: print(f'{day} день: {a}') print(f'Ответ: на {day} день спортсмен достигнет результата — не менее {b} км.')
false
9f555f443490fef8a4dcf1c5ef20b87504a3fcf4
shmurygin-roman/geekbrains_lessons
/course_1/lesson_2_4.py
622
4.125
4
# Урок 2. Задание 4 # Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. # Строки необходимо пронумеровать. # Если слово длинное, выводить только первые 10 букв в слове. my_str = input('Введите строку из нескольких слов через пробел: ') my_list = list(my_str.split()) for i, el in enumerate(my_list, 1): print(f'{i}: {el[:10]}')
false
453cacd903d01eb25f907b4cb42943128e679197
Higgins2718/DS-Unit-3-Sprint-2-SQL-and-Databases
/demo_data.py
973
4.21875
4
import sqlite3 conn = sqlite3.connect('demo_data.sqlite3') curs = conn.cursor() print(curs) """ Create table mytable """ command = "CREATE TABLE IF NOT EXISTS mytable (" \ "s text PRIMARY KEY NOT NULL, x INTEGER NOT NULL, y INTEGER NOT NULL);" result = curs.execute(command) """ Populate table mytable """ command2 = "INSERT INTO mytable (s, x, y)" \ "VALUES ('g', 3, 9)," \ "('v', 5, 7)," \ "('f', 8, 7);" result2 = curs.execute(command2) conn.commit() def select_all_tasks(conn): """ Query all rows in the tasks table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM mytable") rows = cur.fetchall() for row in rows: print(row) command = cur.execute("SELECT COUNT(*) FROM mytable") print(command.fetchall()) command = cur.execute("SELECT COUNT(DISTINCT y) FROM mytable") print(command.fetchall()) select_all_tasks(conn)
true
2f50b7bd3ed3947615e9428e6d53306c4cc07443
ctechhindi/Python-App
/app.py
897
4.46875
4
""" Get Started With Python ------------------------- Python Demo App """ ''' Import Another Class File from FILENAME import CLASS_NAME FUNCTION_NAME ''' from functions import Functions root = Functions() # Variable in Python a = 18 b = "Google.com"; c = 45.90 d = {1:'value','key':2} # Assigning multiple values to multiple variables root.info("Assigning multiple values to multiple variables") a, b, c = 5, 3.2, "Hello" print(a, b, c) # Multi-line statement a = 1 + 2 + 3 + \ 4 + 5 + 6 + \ 7 + 8 + 9 # Data types in Python root.info("Data types in Python") print(a, "is of type", type(a)) print(b, "is of type", type(b)) print(c, "is of type", type(c)) print(d, "is of type", type(d)) # Conversion between data types root.info("Conversion between data types") float(5) int(10.6) int(-10.6) str(25) set([1,2,3]) tuple({5,6,7}) list('hello') dict([[1,2],[3,4]]) dict([(3,26),(4,44)])
true
cca998f4853b89d9fcdbd2698dbdbc1eb637506f
anistamboli/test-case-assignment
/Book_Mngmt_Dict.py
1,701
4.3125
4
#Create, Add, remove and search book in a basic book records system... rec={'1':"Naruto - Masashi Kishimoto ",'2':"Shingeki no Kyojin - Hajime Isayama",'3':"DB series - Akira Toriyama",'4':"Berserk - Miura",'5':"Vinland Saga - Makoto Yukimura", '6':"Kimi no nawa - Makoto Shinkai"} def createBk(): rec.clear() print("new book system created...") print(rec) def addBk(): bookId= input("Enter book id to add : ") if bookId in rec: print("Book already exists") else: bookName= input("Enter book name to add : ") rec[bookId]=bookName print("Book added successfully...") def removeBk(): bookId=input("Enter book id to remove book : ") if bookId in rec: rec.pop(bookId) print("book removed successfully...") else: print("Book not found!!!") def search(): bookId= input("Enter id of book to search: ") if bookId in rec: print(bookId," is a book naming : ", rec[bookId]) else: print("Book not found!!!") def bk_management_system(): response = input('Enter choice : ') while(True): if response=='1': createBk() elif response=='2': addBk() elif response=='3': removeBk() elif response=='4': search() elif response=='5': print(rec) else: print("ok confirm exit... ") exit() bk_management_system() print("All books: ",rec) print("\ntype: 1.create new Book system 2.add book 3.remove book 4.search book 5.show all books .anythyng to exit : \n") bk_management_system()
false
8c0af22fee67437421deccc7644ca95cdbf45e84
anistamboli/test-case-assignment
/letter_count_test.py
1,225
4.1875
4
#test code to show maximum occured character (multiple characters if tied...) def max_letter_test(str): dict={} #str=input("Enter String : ") if(len(str)==0): return ("Empty String") else : for i in str: if i in dict: dict[i]+=1 else: dict[i]=1 maxm=0 for count in dict.values(): if count>maxm: maxm=count return (dict) print("Maximum occured letter and its count: ") for key,value in dict.items(): if(value==maxm): print(key," : ",value) #max_letter_test('jhbdsbjhd') # Test code for maximum letter count... import unittest class TestLetterCount(unittest.TestCase): def test_letter_count(self): #test for any string result = max_letter_test(1281) self.assertEqual(result,{'j': 2, 'h': 2, 'b': 2, 'd': 2, 's': 1}) def test_letter_count(self): #test for empty string result = max_letter_test("") self.assertEqual(result,"Empty String") if __name__ == '__main__': unittest.main()
true
f66808031f972877cb6e711e235e6bcdae03aae8
CodingProgrammer/BinaryTree
/Traversing.py
1,662
4.15625
4
class Node(object): def __init__(self,elem=-1,lchild=None,rchild=None): self.elem = elem self.lchild = lchild self.rchild = rchild class Tree(object): def __init__(self,root=None): self.root = None def add(self,elem): node = Node(elem) if self.root == None: self.root = node else: queue = [] queue.append(self.root) while queue: cur = queue.pop(0) if cur.lchild == None: cur.lchild = node return elif cur.rchild == None: cur.rchild = node return else: queue.append(cur.lchild) queue.append(cur.rchild) def preorder(self,root): '''先序''' if root == None: return print(root.elem,end=' ') self.preorder(root.lchild) self.preorder(root.rchild) def inorder(self,root): '''中序''' if root == None: return self.inorder(root.lchild) print(root.elem,end=' ') self.inorder(root.rchild) def postorder(self,root): '''后序''' if root == None: return self.postorder(root.lchild) self.postorder(root.rchild) print(root.elem,end=' ') def breadth_travel(self,root): '''层次''' if root == None: return queue = [] queue.append(root) while queue: node = queue.pop(0) print(node.elem,end=' ') if node.lchild != None: queue.append(node.lchild) if node.rchild != None: queue.append(node.rchild) if __name__ == "__main__": tree = Tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) tree.preorder(tree.root) print() tree.inorder(tree.root) print() tree.postorder(tree.root) print() tree.breadth_travel(tree.root)
false
728a91be483f5ad67276366ac28d087e91a1b62c
cetacealin/bpe
/exercise6.py
293
4.5
4
'''Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)''' def palindrome(user_str): return user_str == user_str [::-1] get_word = input("Enter a word: ") print(palindrome(get_word))
true
229ea10987cf005ac07711b152befd4bf3867cf1
cetacealin/bpe
/exercise7.py
430
4.125
4
'''Let's say I give you a list saved in a variable: : a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. ''' def select_even(list): new_list = [] for num in list: if num % 2 == 0: new_list.append(num) return new_list a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print(select_even(a))
true
6f2ef60e34fe371be32716258dfa37d3774480ca
harikishangrandhe/FST-M1
/Python/Activities/Activity10.py
228
4.21875
4
tuple1=tuple(input("Enter numbers seperated by comma ").split(",")) print("Numbers entered by the user are ", tuple1) print("Numbers divisible by 5 are below ") for t in tuple1 : if int(t) % 5 ==0: print (t)
true
c3eb6393559082ef5405b9a71e6dcb7d16e15d9d
harikishangrandhe/FST-M1
/Python/Activities/Activity12.py
206
4.1875
4
def recsum(n): if n<=1: return n else: return n+recsum(n-1) number=int(input("Enter the number you want to perform recursive addition ")) result=recsum(number) print(result)
true
7d0c691b2ac12c4a212b553a79b5304bc2ed5132
alexDx12/gb_python
/lesson_8/exercise_2.py
1,093
4.40625
4
""" 2) Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. Проверьте его работу на данных, вводимых пользователем. При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class CustomException(Exception): def __init__(self): self.txt = "На ноль делить нельзя, т.к. результат будет равен бесконечности." def division(self, divided, divisor): try: quotient = divided / divisor except ZeroDivisionError: print(self.txt) else: print(f'Результат деления {divided} на {divisor} равен {quotient}.') finally: print('Программа завершена.') CustomException().division(5, 0) CustomException().division(5, 2)
false
3a9fbc9cb64d80ee0b62de07b13d76294ebf2c56
PoonamGhutukade/Machine-learning
/Week2/Tuple_Creation.py
1,665
4.71875
5
""" 1. Write a Python program to create a tuple. 2. Write a Python program to create a tuple with different data types. """ # tuple created with same data types def tuplecreate(): try: arrr = list() size = input("Enter the size of an tuple for same Dt:") # we have to typecast num to compare with length of string num2 = int(size) # checking enter value is only digit or not if size.isdigit(): print("Enter the elements: ") for ele in range(num2): res = int(input()) arrr.append(res) # typecast to tuple w = tuple(arrr) # print("Set Elements:", set(arrr)) return w else: raise ValueError except ValueError: print("Enter valid number: ") res = tuplecreate() print("Tuple: ", res) # tuple created with diff data types def tuplecreatediffdatatypes(): try: arrr = list() size = input("Enter the size of an tuple for Diff Dt:") # we have to typecast num to compare with length of string num2 = int(size) # checking enter value is only digit or not if size.isdigit(): print("Enter the elements: ") for ele in range(num2): res = input() arrr.append(res) # typecast to tuple w = tuple(arrr) # print("Set Elements:", set(arrr)) return w else: raise ValueError except ValueError: print("Enter valid number: ") res = tuplecreatediffdatatypes() print("Tuple: ", res)
true
47fcceaf4cf28e9081da34f005b8f10371d2dd64
PoonamGhutukade/Machine-learning
/Week4/NumPy/Checkerboard_pattern.py
2,017
4.28125
4
""" 7. Write a Python program to create a 8x8 matrix and fill it with a checkerboard pattern. Checkerboard pattern:""" from Week4.Utility.Util import UtilClass import re class Checkerboard: # class constructor def __init__(self): # utility class objected created here self.obj1 = UtilClass() def calling(self): print("\nPut values from 1 to 64 ") # It display number from 1 to 64 input1 = input("\nEnter the matrix start value:") input2 = input("Enter the matrix end value:") array_created = self.obj1.matrix_creation(input1, input2) str1 = str(array_created) # check output correct or not if re.match(str1, 'None'): print("Output will not display") else: # print("\nNew Matrix:\n", array_created) print("\n 8 * 8 Dimension matrix") # whole matrix fill with zeroes matrix_of_one = self.obj1.null_vector_creation(array_created) num1 = input("Enter the 1st dimension:") num2 = input("Enter the 2nd dimension:") result = self.obj1.reshape_matrix(matrix_of_one, num1, num2) str2 = str(result) if re.match(str2, 'None'): print("Output will not display") else: print("Reshape given matrix into 8*8 or given format: \n", result) """ x[1::2, ::2] = 1 : Slice from 1st index row till 1+2+2… (repeated for 2nd iteration)and fill all columns with 1 starting from 0th to 0+2+2… and so on. x[::2, 1::2] = 1 : Slice from 0th row till 0+2+2… and fill all columns with 1 starting from 1 to 1+2+2+….. """ result[::2, 1::2] = 1 result[1::2, ::2] = 1 print("Checkerboard pattern:\n", result) # class object created to call its methods obj = Checkerboard() obj.calling()
true
19bc7270acb7004d11a25fa6e79a84d7aef92331
PoonamGhutukade/Machine-learning
/week1/ColorList_3.py
696
4.3125
4
"""Write a Python program to display the first and last colors from the following list. color_list = ["Red","Green","White" ,"Black"] """ color_list = ["Red","Green","White" ,"Black"] print(color_list) print("\nFirst Color: ",color_list[0],"--- Last Color: ",color_list[3]) print("-----------------------------------------------------------------------") # Some extra functions. print("\nFrom right to left 2nd element is: ",color_list[-2]) print("\nCut first two items") print(color_list[0:2]) print("\nRemove Green") color_list.remove("Green") print(color_list) print("\nUse pop():") color_list.pop() print(color_list) print("\nUse del keyword:") del color_list[0] print(color_list)
true
504f6cf19b993409c244bae3a3ff74917da94f64
jmayclin/File-Scraper
/download_script.py
2,705
4.15625
4
''' download_script.py Script to download hyperlinks from a url. Python3 James Mayclin ''' import requests import os ''' Handles user input and returns it as a tuple. ''' def inputs(): url = input("Enter the url of the webpage that contains the links to download:") print("Enter desired download path.") path = input("\"./subdirectory\" or press enter for current:") if path == '': path = '.' print("Would you like to restrict the downloaded link to a certain word? e.g. pdf") query_word = input("Enter query word or press enter:") return url, path, query_word ''' Creates user specified subdirectory to download files to ''' def create_subdirectory(path): if path == '.': return if not os.path.exists(path): os.makedirs(path) ''' Parses HTML text for hyperlinks and returns them in a list ''' def find_hrefs(request): string = request.text.lower() begin = 0 markers = [] while string.find('a href=', begin) != -1: start = string.find('a href', begin) + len('a href=') end = string.find('>', start) markers.append((start, end)) begin = end contained = [string[index[0]:index[1]].replace('\"', '') for index in markers] return contained ''' Removes hyperlinks that don't contain 'query_word' ''' def constrain_hrefs(contained, query_word): print(query_word) formats = [s for s in contained if (s.lower().find(query_word.lower()) != -1)] return formats ''' Handles downloading of hyperlinks contained in 'links' at 'url' and downloads them to 'path' ''' def download(links, path, url): print("Found {} links matching criteria".format(len(links))) for link in links: print(link) option = input('\n(D)ownload all,(A)gree to each download, or (Q)uit? ') if option.lower() == 'q': return check = False if option.lower() == 'd' else True url = url[:url.rfind('/')] for link in links: if check: continueResponse = input("Download " + link + "? (Y) or (N):") if continueResponse.lower() == 'n': break print('Requesting ', link) full_url = url + '/' + link r = requests.get(full_url) print('Downloading ', link) if link.find('/') != -1: link = link[link.find('/'):] full_path = path + '/' + link with open(full_path, 'wb') as f: f.write(r.content) ''' Run method - calls methods required for program to function ''' url, path, query_word = inputs() r = requests.get(url) print(r.text) all_links = find_hrefs(r) to_download = constrain_hrefs(all_links, query_word) create_subdirectory(path) download(to_download, path, url)
true
7c4124031fce9030da6bb17182480c5a1b9e6d2e
theotzitzoglakis/coding_bootcamp
/Python/Python Day 2/exercise6.py
683
4.15625
4
numbers = [] for i in range(1, 10): if i%3!=0: print("Enter a number with", i%3,"digits: ", end='') a = input() if len(a)!= i%3: print("The number does not have", i%3,"digits") break numbers.append(a) else: a = input("Enter a number with 3 digits: ") if len(a)!= 3: print("The number does not have 3 digits") break numbers.append(a) print(" ",numbers[0], end='|') print(" ",numbers[3], end='|') print(" ",numbers[6]) print("",numbers[1], end='|') print("",numbers[4], end='|') print("",numbers[7]) print(numbers[2], end='|') print(numbers[5], end='|') print(numbers[8])
false
2bcb10487691954e68f35a7d2322cbd0153820c2
William-Hill/UVI_Teaching_2018
/turtle_lessons/racer_turtle.py
1,611
4.34375
4
import turtle import random STAMP_SIZE = 20 SQUARE_SIZE = 20 FINISH_LINE = 200 COLOR_LIST = ["maroon", "aquamarine", "purple", "deepPink", "blueViolet", "gold"] STARTING_LINE_X = -350 STARTING_LINE_Y = 280 TURTLE_DISTANCE = 90 def draw_starting_line(): turtle.speed("fastest") turtle.penup() turtle.setpos(-350, 300) turtle.pendown() turtle.right(90) turtle.forward(520) def draw_finish_line(): turtle.shape("square") turtle.shapesize(SQUARE_SIZE/STAMP_SIZE) turtle.penup() for i in range(18): turtle.setpos(FINISH_LINE, (300 -(i * SQUARE_SIZE * 2))) turtle.stamp() for j in range(18): turtle.setpos(FINISH_LINE + SQUARE_SIZE, ((300 - SQUARE_SIZE) - (j * SQUARE_SIZE * 2))) turtle.stamp() turtle.hideturtle() def move_turtle(turtle_racer): turtle_racer.forward(random.randint(1,10)) if turtle_racer.xcor() < FINISH_LINE: turtle.ontimer(lambda turtle_racer=turtle_racer: move_turtle(turtle_racer), 50) print "Welcome to Turtle Racing!" number_of_turtles = int(raw_input("How many turtles (between 3 and 6):")) draw_starting_line() draw_finish_line() turtle_list = [] for index in range(number_of_turtles): racer = turtle.Turtle("turtle", visible=False) racer.speed("fastest") racer.penup() racer.setpos(STARTING_LINE_X - STAMP_SIZE, STARTING_LINE_Y - index * TURTLE_DISTANCE) racer.color(COLOR_LIST[index]) racer.showturtle() turtle_list.append(racer) for racer in turtle_list: turtle.ontimer(lambda turtle_racer=racer: move_turtle(turtle_racer), 100) turtle.mainloop()
false
20309cd03ebbab0a522ac90d0e84166e65a54d9e
nyp-sit/python
/practical6/GradeGroup.py
1,210
4.21875
4
total_grade_point = 0 total_credit = 0 num = 0 while True : code = input('Enter the module code (type end to finish) : ') if code == 'end' : print('Your cumulative GPA for %d modules are %.2f' % (num, total_grade_point/total_credit)) break elif code != 'IT1111' and code != 'IT1213' and code != 'IT1101' and code != 'ITP111' and code != 'IT1110' : print('You have entered an invalid module code') continue credit = int(input('Enter the credit for module ' + code + " : ")) grade = input('Enter your grade for ' + code + " : ") if grade == 'A' : gpa = 4.0 elif grade == 'B+' : gpa = 3.5 elif grade == 'B' : gpa = 3.0 elif grade == 'C+' : gpa = 2.5 elif grade == 'C' : gpa = 2.0 elif grade == 'D+' : gpa = 1.5 elif grade == 'D' : gpa = 1.0 elif grade == 'F': gpa = 0 else : print('You have entered an invalid grade!') continue print('Your GPA is %.1f for module %s that has %d credit point. You earned %.1f grade points' % (gpa, code, credit, gpa * credit)) num += 1 total_grade_point += gpa * credit total_credit += credit
true
7be38513b3f0bdf5de684e1685f360e1b095f1b5
nyp-sit/python
/practical5/BMI2.py
573
4.21875
4
weight = input("Enter weight in kg: ") try: weight = float(weight) except ValueError: print('You have entered an invalid weight, please try again') quit() height = input("Enter height in m: ") try: height = float(height) except ValueError: print('You have entered an invalid height, please try again') quit() bmi = weight / (height * height) if bmi <18.5: print("You are underweight!") elif bmi >= 18.5 and bmi <23: print("You are in normal weight!") elif bmi >=23 and bmi <27.5: print("You are overweight!") else: print("You are obese!")
true
b05542785f4f6cb1f9c60f1f205989910682fa56
sanjitroy1992/code_snippets
/Python-Tips-and-Tricks/OppsConcepts/2-Polymorphism.py
2,585
4.34375
4
""" What is Polymorphism : The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types. """ #1. Python program to demonstrate in-built poly- morphic functions # len() being used for a string print(len("geeks")) # len() being used for a list print(len([10, 20, 30])) #2. Examples of used defined polymorphic functions : # A simple Python function to demonstrate # Polymorphism def add(x, y, z = 0): return x + y+z # Driver code print(add(2, 3)) print(add(2, 3, 4)) """ 3. Polymorphism with class methods: Below code shows how python can use two different class types, in the same way. We create a for loop that iterates through a tuple of objects. Then call the methods without being concerned about which class type each object is. We assume that these methods actually exist in each class. """ class India(): def capital(self): print("New Delhi is the capital of India.") def language(self): print("Hindi is the most widely spoken language of India.") def type(self): print("India is a developing country.") class USA(): def capital(self): print("Washington, D.C. is the capital of USA.") def language(self): print("English is the primary language of USA.") def type(self): print("USA is a developed country.") obj_ind = India() obj_usa = USA() for country in (obj_ind, obj_usa): country.capital() country.language() country.type() """ 4. Method Overriding In Python, Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. However, it is possible to modify a method in a child class that it has inherited from the parent class. This is particularly useful in cases where the method inherited from the parent class dose not quite fit the child class. In such cases, we re-implement the method in the child class. This process of re-implementing a method in the child class is known as Method Overriding. """ class Bird: def intro(self): print("There are many types of birds.") def flight(self): print("Most of the birds can fly but some cannot.") class sparrow(Bird): def flight(self): print("Sparrows can fly.") class ostrich(Bird): def flight(self): print("Ostriches cannot fly.") obj_bird = Bird() obj_spr = sparrow() obj_ost = ostrich() obj_bird.intro() obj_bird.flight() obj_spr.intro() obj_spr.flight() obj_ost.intro() obj_ost.flight()
true
fa97935150e1aef2216d5bf99e5af63f81085214
EthanShapiro/PythonCompleteCourse
/Object Oriented Programming/oop_method_3.py
788
4.1875
4
class Circle(object): # Class object attributes pi = 3.14 def __init__(self, radius=1): self.radius = radius self.perimeter = Circle.pi * (radius * 2) def area(self): # pi multiplied by radius**2 return Circle.pi * (self.radius**2) def setRadius(self, newRadius): """ This method takes in a radius, and sets the current radius of the Circle :param newRadius: :return: """ self.radius = newRadius def getRadius(self): return self.radius def getPerimeter(self): """ Returns the perimeter of the current Circle :return: """ return Circle.pi * (self.radius * 2) c = Circle(20) print(c.area()) c.setRadius(4) print(c.getRadius())
true
0d4a324ace92dd4e7de8704cda124440c7f4aabd
EthanShapiro/PythonCompleteCourse
/Built-in Functions/enumerate.py
327
4.125
4
# enumerate allows you to keep a count as you iterate through an object # it does this by returning a tuple in the form (count, element) l = ['a', 'b', 'c'] count = 0 for item in l: print(count) print(item) count += 1 for count, item in enumerate(l): if count >= 2: break else: print(item)
true
cba53bc31319af951cfdb60a542ae90ccd9e706d
EthanShapiro/PythonCompleteCourse
/Object Oriented Programming/oop_inheritance_4.py
707
4.3125
4
# Inheritance is a way to form new classes from classes already defined # Newly formed classes are called derived classes, and the classes derived from are called base classes class Animal(object): def __init__(self): print("Animal Created") def whoAmI(self): print("Animal") def eat(self): print("Eating") class Dog(Animal): def __init__(self): Animal.__init__(self); print("Dog created") def whoAmI(self): print("Dog") def bark(self): print("Woof") a = Animal() d = Dog() d.whoAmI() # Overrides the base classes method whoAmI d.eat() # can call methods in the base class d.bark() # Can have it's own classes
true
3647e84843bb606ea2548baf24d78e735af2ef1d
EthanShapiro/PythonCompleteCourse
/Milestone 1/Comparison_Operators_9.py
336
4.28125
4
a = 1 b = 1 print(a == b) # check if two things are equal print(a != b) # Check if two things aren't equal NOTE Can also use <> print(a < b) # Checks if a is less than b print(a > b) # Check is a greater than b print(a <= b) # Checks if a is less than or equal to b print(a >= b) # Check if a is greater than or equal to b
true
1f62bd1b18743efbe32c5d5af676d47cc52d92cf
DavidM-wood/Y10Design-PythonDW
/project 1/elif_program_1.py
905
4.375
4
# Here is a program to show how to use "if - elif - else" # The hash-tag is used to show that these are comments # This means that the computer will not look at these lines # Author: Davi Wood # Upper Canada College # Put down some options for the user to choose from... # This program is a modification to allow users to request usful information from me print("What do you want to know?") print("1. Classes") print("2. Weather") print("3. After school activities") print(" ") print("Choose one of the options above") myrequest = int(input("What do you want? \n")) # newline character if myrequest == 1: print("coding, french, gym, geo") elif myrequest == 2: print ("Its fine") elif myrequest == 3: print ("You got some puck and stick after school") else: print ("This is not a valid choice") # This is a way to gracefuuly exit the program input("Press ENTER to quit the program")
true
66d083b41d2eed69b336e99ec00df7be6685527b
vins-stha/hy-data-analysis-with-python
/part02-e06_file_count/src/file_count.py
1,907
4.125
4
#!/usr/bin/env python3 """ Create a function file_count that gets a filename as parameter and returns a triple of numbers. The function should read the file, count the number of lines, words, and characters in the file, and return a triple with these count in this order. You get division into words by splitting at whitespace. You don’t have to remove punctuation. Part 2. Create a main function that in a loop calls file_count using each filename in the list of command line parameters sys.argv[1:] as a parameter, in turn. For call python3 src/file_count file1 file2 ... the output should be ? ? ? file1 ? ? ? file2 ... The fields are separated by tabs (\t). The fields are in order: linecount, wordcount, charactercount, filename. """ import sys def file_count(filename): filename = "src/test.txt" # test = "Create a main function that in a loop calls file_count using each filename in the list of command line parameters " charsList,wordsList = [],[] wordCount = 0 with open(filename,"r") as file: lines = file.readlines() for line in lines: line = line.split("\n") linesCount = len(lines) for i in range(linesCount): words = lines[i].split() wordCount += len(words) #wordsInLine=(lines[i].split()) #wordsList.append(wordsInLine) for chars in lines[i]: chars = chars.split() charsList.append(chars) charsCount = len(charsList) #print(linesCount, charsCount, wordCount) return (linesCount, wordCount,charsCount) def main(): filename = sys.argv[1:] results = [] for i in range(len(filename)): results = file_count(filename) print("{}\t{}\t{}\t{}\t".format(results[0],results[1],results[2],filename[i])) pass if __name__ == "__main__": main()
true
a5dcb9e24f801196211f1f7226bb246c657dd490
vins-stha/hy-data-analysis-with-python
/part01-e13_reverse_dictionary/src/reverse_dictionary.py
411
4.28125
4
def reverse_dictionary(d): reverse={} for key,values in d.items(): for value in values: reverse.setdefault(value,[]).append(key) #print(reverse) #print(reverse) return (reverse) def main(): d={'move': ['liikuttaa'], 'hide': ['piilottaa','salata'], 'six': ['kuusi'], 'fire': ['kuusi']} print(reverse_dictionary(d))
false
93f7dbef4c070ee90f9ff5f75cb3eba31c7b60e1
raquelmcoelho/python
/Class and Object/1-Retangulo.py
2,300
4.28125
4
""" 1. Criar uma classe que modele retângulos. 1. Atributos: LadoA, LadoB (ou Comprimento e Largura, ou Base e Altura, a escolher) 2. Métodos: Mudar valor dos lados, Retornar valor dos lados, calcular Área e calcular Perímetro; 3. Crie um programa que utilize esta classe. Ele deve pedir ao usuário que informe as medidas de um cômodo. Depois, deve criar um objeto com as medidas e calcular a quantidade de pisos e de rodapés necessárias para o local. """ # criação da classe retãngulo class Retangulo: def __init__(self, a, b): self.a = float(a) self.b = float(b) def mudarlado(self, a1, b1): self.a = float(a1) self.b = float(b1) def lados(self): return self.a, self.b def area(self): return self.a * self.b def perimetro(self): return 2*(self.a + self.b) L1, L2 = input("insira os lados do seu cômodo separados com espaço: \n").split(" ") l1, l2 = input("insira os lados do seu piso separados com espaço: \n").split(" ") # instanciação dos objetos comodo e piso comodo = Retangulo(L1, L2) piso = Retangulo(l1, l2) # opções resposta = 0 while resposta != 6: resposta = int(input(""" ------------------------------------------------ Opções: 1 - Mudar Lados 2 - Acessar Lados 3 - Área 4 - Perímetro 5 - Quantos pisos e rodapés serão precisos 6 - sair ------------------------------------------------ Inserir resposta: """)) if resposta == 1: l, ll = input("insira as novas medidas: ").split(" ") opc = int(input("1-Redefinir lados do cômodo\n2-Redefinir lados do Piso\nResposta: ")) if opc == 1: comodo.mudarlado(l, ll) elif opc == 2: piso.mudarlado(l, ll) elif resposta == 2: print("\nLados do cômodo e piso: ", comodo.lados(), piso.lados()) elif resposta == 3: print("\nÁrea do cômodo e piso: ", comodo.area(), piso.area()) elif resposta == 4: print("\nPerímetro do cômodo e piso: ", comodo.perimetro(), piso.perimetro()) elif resposta == 5: rodape = comodo.perimetro() / piso.area() QTDpisos = comodo.area() / piso.area() print("Serão precisos %.2f pisos para completar seu cômodo e %.2f para fazer o rodapé" % (QTDpisos, rodape))
false
59fda526a08c8d74ac402d263b3c577653af18d6
benbai123/Python
/Practice/Basic/flow_control/input_loop_condition_error-handling.py
724
4.34375
4
# display message and wait for input # input is always a string # ref http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number-given-that-input-always-returns-stri x = input("Please enter an integer, or q to stop: ") sum = 0 # while input is not 'q' while x != 'q': try: # try to convert x to integer x = int(x) if x < 0: x = 0 print('Negative changed to zero') elif x == 0: # keyword 'elif' is short for 'else if' print('Zero') else: print('positive') sum += x print('sum = ' + str(sum)) x = input() # wait for next input except ValueError: # error happened when convert x to integer x = input("Please enter an integer, or q to stop: ")
true
6f4f5df95a909af2fe8474eaea42a14066812f02
titoco3000/AP_Lab10
/Progressao.py
368
4.125
4
numero = -1 while numero < 1 : entrada = input("Digite a posição máxima: ") try: numero = int(entrada) except ValueError: numero = -1 if numero < 1: print("Entrada inválida.") resultado = 0 for i in range(0,numero): resultado += ((i+1)*2 -1)/(i+1) print("A soma dessa sequencia é",resultado)
false
bbcb0459e38cdd94da5097c2f7137c6139bfde78
JordanNeely2/Final-Project
/cobrafactorial.py
314
4.1875
4
#ad- compilable task #factorial in python mini assignment def rfactorial(n): if n == 1: return n else: return n*rfactorial(n-1) num = input("What number do you want to take the factorial of? ") if num < 0: print("Invalid because negative number") elif num == 0: print("1") else: print(rfactorial(num))
true
e56548b908db7e5c597da8249c1dee589f26cc32
necaro55/Codewars
/String_subpattern_recognition.py
1,108
4.34375
4
#In this kata you need to build a function to return either true/True or false/False if a string can be seen as the repetition of a simpler/shorter subpattern or not. #For example: #has_subpattern("a") == False #no repeated pattern #has_subpattern("aaaa") == True #created repeating "a" #has_subpattern("abcd") == False #no repeated pattern #has_subpattern("abababab") == True #created repeating "ab" #has_subpattern("ababababa") == False #cannot be entirely reproduced repeating a pattern #Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!). import re def has_subpattern(string): for x in range(1, len(string)): if string[0] == string[x]: if len(string) % len(string[0:x]) == 0: patternRepetition = re.findall(string[0:x], string) if (len(string) / len(string[0:x])) == len(patternRepetition): return True if x > len(string)/2: return False return False
true
f61f878f00f72fcad5e0b073b38d2611f913dfd4
rupakrokade/python-practice
/classess.py
1,183
4.125
4
class MyClass: "This is doc string for MyClass" version=1.1 def __init__(self,num): self.num=num print "You entered %d and this is Version %f" % (self.num,MyClass.version) #o=MyClass(3) class Calculator: "This class performs addition and subtraction" version=1.1 def __init__(self,num1,num2): self.num1=num1 self.num2=num2 print "Welcome to my calculator, version %f" % Calculator.version def addition(self,num3): self.num3=num3 print self.num3+Calculator.version #obj=Calculator(23,43) #obj.num1=100 #obj.version=2000 #obj.addition(13) #print hasattr(obj,'num1') #print getattr(obj,'num2') class Subtractor(Calculator): "This class inherits from Calculator" def __init__(self): print "This is child classes's init" def subtract(self): print self.num1-self.num2 def addition(self,num4,num5): self.num4=num4 self.num5=num5 print self.num4+self.num5 obj=Subtractor()# Here i created child's object setattr(obj,'num1',343)# But here i edited parent's attribute setattr(obj,'num2',32) print getattr(obj,'num1') print getattr(obj,'num2') obj.addition(45,66)# Here i have override the parent method
true
078816465730b0dc48f1904c657ef2a3b90c0c5b
thomblr/seance_4_loops
/ex8_university.py
1,664
4.46875
4
""" Première année à l'univsersité, vous êtes bien décidé à vous organiser et à ne pas vous laisser dépasser... Quoi de mieux pour planifier votre travail qu'un calendrier. Ecrivez une fonction affichant un calendrier (chiffré uniquement) pour un mois en particulier ou pour l'année entière. Attention au nombre de jours variables par mois et aux années bissextiles. Rappel : Les années multiples de 4 sont bissextiles, sauf les années multiples de 100 qui ne le sont pas, sauf les années multiples de 400 qui le sont. Ainsi, 2200 n'est pas bissextiles, mais 2400 oui. """ def show_calender(year, month): """ Show the calender for the month chosen :param year: the year you chose (int) :param month: the month you chose (int) """ for i in range(1, nbr_days_in_month(year, month) + 1): print(i, end=" ") # Attribut 'end' pas obligatoire # Il permet d'éviter de retourner à la ligne à chaque print def nbr_days_in_month(year, month): """ Returns the number of days in the chosen month :param year: the year you chose (int) :param month: the month you chose (int) :return: number of days in month 'month' (int) """ if month == 2: if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return 29 else: return 28 else: return 29 else: return 28 elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: return 31 else: return 30 show_calender(2018, 5)
false
9854d8c125d36b7bcbd8cf8409f660c3d73bbfaf
janerleonardo/Python3CodigoFacilito
/funciones/funcion_map.py
341
4.28125
4
""" La funcion map, permite aplicar una funcion sobe los items de un objeto iterable(Lista, tuplas, Diccionario) """ def cuadrado(numero): return numero * numero lista = [1,2,3,4,5,6] resultado = list(map(cuadrado, lista)) print(resultado) resultado1 = list(map(lambda numero : numero * numero,lista)) print(resultado1)
false
6bc7127423c1131548d84e1997d80df22bfa7ece
janerleonardo/Python3CodigoFacilito
/Basic/operaciones_lista.py
599
4.46875
4
""" Utilizacion del metodo de ordenamiento sort() y los metodos min y max """ lista = [8,17,90,1,5,44,1.32] #Impresiones. print(lista[:]) #Ordenar con sort lista.sort() print("Ordenado\n", lista) #Ordenamiento descendente lista.sort(reverse=True) print("Ordenamiento desc\n", lista) #Max print("numero Maximo\n", max(lista)) #Min print("Minimo\n",min(lista)) #Buscar en la lista print("Esta el numero 8?\n", 8 in lista) #cual es el indice en la lista print("Indice", lista.index(44)) #Metodo count print("Cuanos 5 hay en la lista\n", lista.count(5))
false
9b31463ff0f168ecf26ae2439f901c9b154aac7a
janerleonardo/Python3CodigoFacilito
/JuegoPy/ahorcado.py
2,222
4.125
4
""" Juego de Ahorcado Autor: Jan3r Date: 20-06-24 """ import random IMAGES = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | | | | =========''', ''' +---+ | | O | /|\ | | | / | =========''', ''' +---+ | | O | /|\ | | | / \ | =========''', ''' '''] WORDS = [ 'LAVADORA', 'SECADORA', 'SOFA', 'IMPRESORA', 'ESTUDIANTE', 'MATEMATICAS', ] def random_word(): index = random.randint(0,len(WORDS)-1) return WORDS[index] def display_board(hidden_word,tries): print(IMAGES[tries]) print('') print(hidden_word) print(('---------------------------------')) def run(): word = random_word() hidden_word = ['-']* len(word) tries = 0 while True: display_board(hidden_word,tries) current_letter = input('Ingrese un letra: ') letter_indexes = [] for i in range(len(word)): if word[i] == current_letter.upper(): letter_indexes.append(i) if len(letter_indexes) == 0: tries += 1 if tries == 7: display_board(hidden_word,tries) print('GameOvers') print('Palabra Correcta era {}'.format(word)) break else: for idx in letter_indexes: hidden_word[idx] = current_letter letter_indexes = [] try: hidden_word.index('-') except ValueError: print('Ganaste') print('la Palabra es {}'.format(hidden_word)) break if __name__ == '__main__': run()
false
b9bc0618a07530e8e7d14371eef7443e299b680d
janerleonardo/Python3CodigoFacilito
/POO/metodos_clase.py
383
4.125
4
""" Los metodos de clase son aquellos que se decoran con @classmethod, por convencion se utiliza la pabla cls que vendia a ser como el self en los metodos de instacion, comumente se utilizza cuando queremos utilizar variables de Clase """ class Circulo: PI=3.14159265 @classmethod def area(cls,radio): return cls.PI * radio**2 print(Circulo.area(10))
false
3596ab792d9dbe6aa509ee5c8c381e6721685e68
YaqianQi/Algorithm-and-Data-Structure
/Python/Leetcode Daily Practice/unclassified/521. Longest Uncommon Subsequence I.py
927
4.125
4
""" Given two strings, you need to find the longest uncommon subsequence of this two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other string. A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1. """ class Solution(object): def findLUSlength(self, a, b): """ """ if a == b: return -1 return max(len(a), max(len(b))) # Input: a = "aaa" b = "aaa" print(Solution().findLUSlength(a, b))
true
0623d6035b618f7ac2eca8c4427b50089f3533c2
GladysCopaga/QETraining_BDT_python
/GladysCopaga/TaskOperators/performOperation.py
1,538
4.34375
4
# First version to perform operations def performOperation (operator,number1,number2): number3 = 0 if (operator == "+"): number3 = (number1 + number2) elif (operator == "-"): number3 = (number1 - number2) elif (operator == "*"): number3 = (number1 * number2) elif (operator == "/"): number3 = (number1 / number2) elif (operator == "%"): number3 = (number1 % number2) elif (operator == "**"): number3 = (number1 ** number2) elif (operator == "//"): number3 = (number1 // number2) print("(' %s" %(operator), "' , '", (number1), "' , '", (number2), "') The result is: ", (number3)) performOperation("+",1,2) # Second version to perform operations with input def ArithmeticOperations(): num1 = eval(input("Introduzca un numero1: ")) num2 = eval(input("Introduzca un numero2: ")) oper = input("Introduzca un operador: ") num3 = 0 if (oper == "+"): num3 = (num1 + num2) elif (oper == "-"): num3 = (num1 - num2) elif (oper == "*"): num3 = (num1 * num2) elif (oper == "/"): num3 = (num2 / num1) elif (oper == "%"): num3 = (num2 % num1) elif (oper == "**"): num3 = (num1 ** num2) elif (oper == "//"): num3 = (num1 // num2) else: print("introduzca un operador aritmetico como: +, -, *, /, %, ** o //") exit() print ("Operador:", oper, ", numero1:", num2, ", numero2:", num2) print ("La suma es: ", num3) ArithmeticOperations()
false
52356a41234de9ad976669f829d37b5cf7fe80ef
mayankkumarsingh/Deep-Learning
/tools/basic_functions/normalizeRows.py
417
4.25
4
import numpy as np def normalizeRows(x): """ Implement a function that normalizes each row of the matrix x (to have unit length). Argument: x -- A numpy matrix of shape (n, m) Returns: x -- The normalized (by row) numpy matrix. You are allowed to modify x. """ # Compute x_norm as the norm 2 of x. x_norm = np.linalg.norm(x,axis=1,keepdims=True) x = x/x_norm return x
true
cda4dee47b2113df8a9c47d8125fb61a35933956
SP-18-Data-Analysis/work-with-matrices-alexespinal1
/assignment2.py
461
4.1875
4
#------------------------------------- #Alex Espinal programming assignment 2 #------------------------------------- # import numpy import numpy as nump #create the array list and filled it with numbers b = nump.array([[1,2,3,4],[2,4,6,8],[3,6,9,12],[10,20,30,40],[5,10,15,20]]) #prints out the array list print(b) #using your hint by uing a loop for column in b: print(column) #prints out columns print (b[:,0]) print (b[:,1]) print (b[:,2]) print (b[:,3])
true
cd4fca7720fed367bf77d11b2a102598f4a72dfc
chikarl/the-Box-ii-Assignment
/The Box II – Practice Exercises [27-03-2021]/Ex1.py
258
4.34375
4
print('Please enter ur height in feet and inches for example 5feet and 9inches') feet = float(input('Feet: ')) inches = float(input('Inches: ')) def cm(x,y): cm = (30.48*feet)+(2.54*inches) return cm print(f"Your height is {cm(feet, inches)} in cm")
true
ec5ea7dec8141ca05ebbadd457f492cd30e45cdb
hoonest/PythonStudy
/src/chap08/05_super.py
869
4.25
4
# super() : 부모 클래스의 객체 역할을 하는 프록시(proxy)를 반환하는 내장 함수 class A: def __init__(self): print('A.__init__()') self.message = 'hello' class B(A): def __init__(self): print('B.__init__()') super().__init__() print('self.message is ' + self.message) if __name__ == '__main__': b = B() # 참조 : 자식 클래스의 인스턴스를 생성할 때 부모클래스 class Base: def __init__(self): self.message = 'hello2' print('Base') class Derived(Base): pass d = Derived() print(d.message) print('===================') class Base2: def __init__(self): self.message = 'hello2' print('Base') class Derived2(Base2): def __init__(self): Base2.__init__(self) print('Derived') d = Derived2() print(d.message)
false
2c785a4e09050b3fd22783cac2fde78599cc50c6
yosinovo1/CoronaTime
/Programming Languages/Python/Design Patterns/duck_typing.py
941
4.15625
4
""" (From wikipedia) Duck typing is an application of the duck test ("If it walks like a duck and it quacks like a duck, then it must be a duck")- to determine if an object can be used for a particular purpose. With normal typing, suitability is determined by an object's type. In duck typing, an object's suitability is determined by the presence of certain methods and properties, rather than the type of the object itself. """ class Duck: def fly(self): print("Duck flying") class Sparrow: def fly(self): print("Sparrow flying") class Whale: def swim(self): print("Whale swimming") def main(): for animal in Duck(), Sparrow(), Whale(): try: animal.fly() except AttributeError: print(f"Animal '{type(animal).__name__}' cannot fly") if __name__ == "__main__": main() """ output: ------- Duck flying Sparrow flying Animal 'Whale' cannot fly """
true
c495a6bf4b019a7e6d87f1afdcf0af98e3846fd7
ChrisCraddock/PythonSchoolWork
/PaintCostCalc.py
1,762
4.34375
4
#250 sq ft coverage = 1 gal and 8 hr labor #Price = $35/hr #Ask the user to enter: # -the square feet of wall space to be painted # -the price per gallon of paint #Display: # -number of gal required # -hours of labor required # -total paint cost # -labor charges # -total project cost #-----MAIN LOOP---# def main(): user_wall = int(input("Please enter the sq feet of wall"+ "needing to be covered: ")) user_paint = float(input("Please enter the price of paint"+ "per gallon: (nearest whole dollar) $")) gallons_need = paint_needed(user_wall) hours_needed = get_hours(user_wall) paint_cost = int(user_paint * gallons_need) labor_cost = int(gallons_need * 35) total_cost = int(paint_cost + labor_cost) print("The total cost of paint is: $",paint_cost, sep='') print("The total cost for labor at $35/hour is: $",labor_cost, sep='') print('The total project cost is: $',total_cost, sep='') #-----FUNCTIONS FOR MAIN LOOP---# def paint_needed(gallons): paint = gallons / 250 more_paint = gallons % 250 if more_paint > 0: print("The number of gallons of paint required are: ", int(paint + 1), "gallons") return paint + 1 else: print("The number of gallons of paint required are: ",paint, "gallons") return paint def get_hours(user_wall): hours = (user_wall / 250) * 8 more_hours = (user_wall % 250) * 8 if more_hours > 0: print("The total hours of labor required are: ", int(hours + 1),"hours") return hours + 1 else: print("The total hours of labor required are: ", hours, "hours") return hours main()
true
0a5f402629e6a89fefd45c8aca7223cc83171068
ChrisCraddock/PythonSchoolWork
/RandomNumGen.py
845
4.21875
4
''' Lets user specify how many numbers should randomly be generated ''' import random def main(): #Local Variables filename = '' numberOfRandoms = 0 randomNumber = 0 #Get file name as input from the user filename = input("Enter the name and type of the file to which results should be saved: ") numberOfRandoms = int(input("Enter the amount of random numbers: ")) #--- Lab requests the output file have a certain name so this overwrites the users name filename = "randomNumber.txt" outputFile = open(filename,'w') for counter in range (numberOfRandoms): randomNumber = random.randint(1,500) outputFile.write(str(randomNumber) + '\n') outputFile.close() print("Your numbers have been written and saved") main()
true
e463ea75823078e8c450216a922e3c155763cbbc
ChrisCraddock/PythonSchoolWork
/TurtleSquareLoops.py
785
4.3125
4
''' This program will do the following: 1. Ask for input of the number of squares to draw 2. Use a nested loop to draw requested number of squares ''' import turtle #===Constants num_squares = 1 t = turtle.Turtle() t.pendown() side = side_unit = 30 #===Input while True: try: num_squares = int(input('input the number of squares: ')) except ValueError: print("please enter an integer") if num_squares > 1: break #===Process for sq in range(1, num_squares + 1): t.left(90) t.forward(side) t.left(90) t.forward(side) t.left(90) t.forward(side) t.left(90) side = side_unit + 3 * sq # increase the size of the side t.goto(0,0) # return to base turtle.done()
true
2d4cf2d686623a808d34120b041d310c23831dc6
renatogusani/rgus19411076_CA---TEST-2
/BMI.py
1,397
4.59375
5
''' nci programme: BSHDS program: bmi calculator with features as shown in assignment question table author: Renato Gusani studentID: x19411076 date: 29/02/2020 ''' height = float(input("Input height in meters (Example; 1.70): ")) # gets height and assigns it to user input weight = float(input("Input weight in kg: (Example; 75) ")) # gets weight and assigns it to user input # this calculates the bmi (as given from the question) bmi = weight/(height**2) print("Your BMI is: {0} and you are: ".format(bmi), end='') # prints bmi according to format #features of BMI as per the assignment table if ( bmi < 15): print(" Very severely underweight") elif ( bmi >= 15 and bmi < 16): print("Severely underweight") elif ( bmi >= 16 and bmi < 18.5): print("Underweight") elif ( bmi >= 18.5 and bmi < 25): print("Normal(healthy weight)") elif ( bmi >= 25 and bmi < 30): print("Overweight") elif ( bmi >= 30 and bmi < 35): print("Obese class I(Moderately obese)") elif ( bmi >= 35 and bmi < 40): print("Obese class II(Severely obese)") elif ( bmi >= 40 and bmi < 45): print("Obese class III(Very severely obese)") elif ( bmi >= 45 and bmi < 50): print("Obese class IV(Morbidly obese)") elif ( bmi >= 50 and bmi < 60): print("Obese class V(Super obese)") elif ( bmi >=60): print("Obese class VI(Hyper obese)")
true
b827f9de4f46034277ac3659530643b20dfca61f
aschiedermeier/Programming-Essentials-in-Python
/Module_3/3_1_3_6_Logic.py
463
4.1875
4
# Logic and bit operations in Python # Bitwise operators # Bit shifting x = 4 y = 1 print (bin(x)) print (bin(y)) a = x & y b = x | y c = ~x # -x-1 d = x ^ 5 e = x >> 2 f = x << 2 print(a, b, c, d, e, f) x = 1 y = 0 z = ((x == y) and (x == y)) or not(x == y) print("x == y: ", x == y) print("(x == y) and (x == y): ", (x == y) and (x == y)) print("not(x == y): ", not(x == y)) print("False or True: ", False or True) print("z: ",z) print("not(z): ",not(z))
false
4360841d91bc196729f1f407bdd8b6c34795d5e5
aschiedermeier/Programming-Essentials-in-Python
/Module_6/6.1.5.1.InheritanceMethods.py
2,502
4.25
4
# 6.1.5.1 OOP Fundamentals: Inheritance # default __str__() method / string method class Star: def __init__(self, name, galaxy): self.name = name self.galaxy = galaxy sun = Star("Sun", "Milky Way") # print like this does not look good, as it invokes the default __str__() method print(sun) # "<__main__.Star object at 0x7f1074cc7c50>" object identifier ### # defining new __str__() method print() class Star: def __init__(self, name, galaxy): self.name = name self.galaxy = galaxy def __str__(self): return self.name + ' in ' + self.galaxy sun = Star("Sun", "Milky Way") print(sun) # returns: "Sun in Milky Way" # 6.1.5.4 OOP Fundamentals: Inheritance # Inheritance: issubclass() # check all possible ordered pairs of classes, # and to print the results of the check to determine # whether the pair matches the subclass-superclass relationship. # each class is considered to be a subclass of itself. print() class Vehicle: pass class LandVehicle(Vehicle): pass class TrackedVehicle(LandVehicle): pass for cls1 in [Vehicle, LandVehicle, TrackedVehicle]: for cls2 in [Vehicle, LandVehicle, TrackedVehicle]: print(issubclass(cls1, cls2), end="\t") print() ## # 6.1.5.5 OOP Fundamentals: Inheritance # Inheritance: isinstance() print() class Vehicle: pass class LandVehicle(Vehicle): pass class TrackedVehicle(LandVehicle): pass myVehicle = Vehicle() myLandVehicle = LandVehicle() myTrackedVehicle = TrackedVehicle() for obj in [myVehicle, myLandVehicle, myTrackedVehicle]: for cls in [Vehicle, LandVehicle, TrackedVehicle]: print(isinstance(obj, cls), end="\t") print() ## # 6.1.5.6 OOP Fundamentals: Inheritance # Inheritance: the is operator # The is operator checks whether two variables # (objectOne and objectTwo here) refer to the same object. # Don't forget that variables don't store the objects themselves, # but only the handles pointing to the internal Python memory. print() class SampleClass: def __init__(self, val): self.val = val ob1 = SampleClass(0) ob2 = SampleClass(2) ob3 = ob1 ob3.val += 1 print(ob1 is ob2) #False print(ob2 is ob3) #False print(ob3 is ob1) #True print(ob1.val, ob2.val, ob3.val) #1 2 1 str1 = "Mary had a little " str2 = "Mary had a little lamb" str1 += "lamb" print(str1 == str2, str1 is str2) # True False
true
4217bbe8e2877d51aaff0bf74d034da73d744378
aschiedermeier/Programming-Essentials-in-Python
/Module_6/6.1.4.1.Methods.py
825
4.3125
4
# 6.1.4.1 OOP: Methods class Classy: def method(self, par): print("method:", par) obj = Classy() obj.method(1) obj.method(2) obj.method(3) # 6.1.4.2 OOP: Methods # The self parameter is used to obtain access to the object's instance and class variables. class Classy: varia = 2 def method(self): print(self.varia, self.var) # 2 3 obj = Classy() obj.var = 3 obj.method() # The self parameter is also used to invoke other object/class methods from inside the class. class Classy: def other(self): print("other") def method(self): print("method") self.other() obj = Classy() # class has no constructor, only methods. so nothing visible happens during instantiation obj.method() # calls method "method", which calls methods "other" # output: method other
true
9b13972890ce97d904fb9c9b98ac87dc1c12a9d5
aschiedermeier/Programming-Essentials-in-Python
/Module_5/5_1_8_6_StringIndexing.py
1,094
4.125
4
# 5.1.8.6 The nature of strings in Python # Indexing strings exampleString = 'silly walks' for ix in range(len(exampleString)): print(exampleString[ix], end=' ') print() # Iterating through a string exampleString = 'silly walks' for ch in exampleString: print(ch, end=' ') print() # Slices alpha = "abcdef" print(alpha[1:3]) print(alpha[3:]) print(alpha[:3]) print(alpha[3:-2]) print(alpha[-3:4]) print(alpha[::2]) # every second one - start 0 print(alpha[1::2])# every second one - start 1 # in and not in operators alphabet = "abcdefghijklmnopqrstuvwxyz" print("f" in alphabet) print("F" in alphabet) print("1" in alphabet) print("ghi" in alphabet) print("Xyz" in alphabet) print("f" not in alphabet) print("F" not in alphabet) print("1" not in alphabet) print("ghi" not in alphabet) print("Xyz" not in alphabet) # del method: only remove string as a whole ch = "abc" # del ch[0] # not ok del ch # ok # append strings by creating new string using concatenate operator alphabet = "bcdefghijklmnopqrstuvwxy" alphabet = "a" + alphabet alphabet = alphabet + "z" print(alphabet)
true
b73ec94cae7e629ca758d4379fe9a6f2bf1881c0
aschiedermeier/Programming-Essentials-in-Python
/Module_5/5_1_11_11_SudoKu.py
2,333
4.21875
4
# 5.1.11.11 LAB: Sudoku # LAB # reads 9 rows of the Sudoku, each containing 9 digits (check carefully if the data entered are valid) # each row of the board must contain all digits from 0 to 9 (the order doesn't matter) # each column of the board must contain all digits from 0 to 9 (again, the order doesn't matter) # each of the nine 3x3 "tiles" (we will name them "sub-squares") of the table must contain all digits from 0 to 9. # function to check, if 1-9 is in a 9-digit string def numsInString (strng): '''1-9 in string ''' nums = "123456789" isin = True # is every digit in string? default yes, unless proven wrong for num in nums: pos = strng.find(num) # find digit in string in position pos if pos == -1: # if digit not in string, proven wrong, break loop isin = False return isin return isin ### ok sdk=[ "295743861", "431865927", "876192543", "387459216", "612387495", "549216738", "763524189", "928671354", "154938672"] # ### not ok # sdk=[ # "195743862", # "431865927", # "876192543", # "387459216", # "612387495", # "549216738", # "763524189", # "928671354", # "254938671"] isok = True # check rows for num in sdk: # checks each element in list, representing the rows if numsInString(num) == False: isok = False break # breaks for loop, no need to check the other rows print (isok) # check columns for i in range (9): # loop through all 9 columns col = "" # empty string for columns for num in sdk:# loop though all 9 rows col = col + num[i] # concatenate only the ith value in each row if numsInString(col) == False: isok = False break # breaks upper for i loop, no need to check other columns print (isok) # check squares for i in range (0,7,3): # i = 0,3,6: defining the ranges for the squares for j in range (0,7,3): # j = 0,3,6: defining the ranges for the squares if isok == False: break # need break command here, to stop checking other squares squ ="" # empty string for squares for a in range(0+i,3+i): # 3 to bottom for b in range (0+j,3+j): # 3 to right squ += sdk[a][b] # concatenate values from square if numsInString(squ) == False: isok = False print (isok)
true
72753a3e005ab84bd4593bb5be4bfd3708d6292e
wangyan841331749/SortAlgorithmPython
/bubble_sort.py
522
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author:Wang Yan @ide:PyCharm @time:2019/2/17 19:25 """ list_order = [7, 4, 3, 67, 34, 1, 8] def bubble_sort(arr): """ sort the data with bubble sort algorithm. :param arr: :return: """ n = len(arr) for i in range(0, n - 1): for j in range(0, n - 1 - i): if arr[j] > arr[j + 1]: temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp bubble_sort(list_order) print(list_order)
false
f4f6c9e0d6893f1b90c7e41d377685b1913abdb3
flyin01/nnfs
/src/0.basics/p5.py
2,839
4.125
4
# Now we go from a single sample of input to a batch of inputs # Go from single layer of neurons to model two layers of neurons # We will go to object oriented programming, creating our layer object # why batch? # batch allow us to calculate in parallel, this is why we tend to do neural # network computations on gpu´s rather than cpu´s. A cpu may hae 4-8 cores # while gpu typically can have hundreds of cores. We do typically Matrix # multiplication which can be done on gpus. # alos it helps with generalization to use batches. # one single sample of four features inputs = [1, 2, 3, 2.5] # current status, we want to pass a batch of these # samples instead. It helps generalize instead of showing our machine once # at the time # Take a sample batch of 512, ask one neuron to fit to that sample (line) # We are fitting one sample at the time to a neuron, bouncing around up n down # one sample at the time draw the fitted line. If we use multiple samples # it can probably do a better job at fitting the samples. # batch size: 4, fitted line will still move but less than with size 1. # batch size: 15, even more stabile. # batch size 32 at the time is easier than 1 sample, but it can also create # overfitting. We should not show all samples at once either. import numpy as np # batch of inputs inputs = [[1, 2, 3, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] # Do we need to change weights and biases now? No weights = [[0.2, 0.8, -0.5, 1.0], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]] biases = [2, 3, 0.5] # Both our weights and inputs will be a matrix # Matrix product. We take first input matrix row vector and we do then # dot product of every column vector of the second matrix. # [row1 value1, value2, value3 * [col1 value1, value2, value3] = scalar value1_1 # [row1 value1, value2, value3 * [col2 value1, value2, value3] = scalar value1_2 # [row1 value1, value2, value3 * [col3 value1, value2, value3] = scalar value1_3 # row 2, same thing column wise, etc untill we have an entire output matrix # with the dot products of the row and column vectors # Now inputs and weights are currently the same shape, unlike before in readme # We want to swap rows and columns of weights matrix, since rows in input are 4 # while cols in weights are 3. We get a shape error now when we try dot product # T swaps row and makes it a col #output = np.dot(weights, inputs) + Biasesprint(output) # gives shape error # To transpose is that we need to convert the weights to arrays output = np.dot(inputs, np.array(weights).T) + biases print(output) # a batch of outputs in a 3x3 matrix # transposed weights # [0.2, 0.5, -0.26] # [0.8, -0.91, -0.27] # [-0.5, 0.26, 0.17] # [1.0, -0.5, 0.87] # Then we add the biases vector to each of the rows of the matrix product outputs
true