blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
09fb28996aa732c01df70d674a369fafa05e0939
mcampo2/python-exercises
/chapter_01/exercise_18.py
410
4.5
4
#/usr/bin/env python3 # (Turtle: draw a star) Write a program that draws a star, as shown in Figure 1.19c. # (Hint: The inner angle of each point in the star is 36 degrees.) import turtle turtle.right(36+36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle.done()
true
b39fc4b4543d890072f04ce215d29dc50827c3ff
mcampo2/python-exercises
/chapter_03/exercise_16.py
2,135
4.53125
5
#!/usr/bin/env python3 # (Turtle: draw shapes) Write a program that draws a triangle, square, pentagon, # hexagon, and octagon, as shown in Figure 3.6b. Note that the bottom edges of # these shapes are parallel to the x-axis. (Hint: For a triangle with a bottom line # parallel to the x-axis, set the turtle's heading to 60 degrees.) import turtle # triangle turtle.penup() turtle.goto(-400, 0) turtle.pendown() turtle.begin_fill() turtle.forward(100) turtle.right(360 - 360/3) turtle.forward(100) turtle.right(360 - 360/3) turtle.forward(100) turtle.right(360 - 360/3) turtle.end_fill() # square turtle.penup() turtle.goto(-280, 0) turtle.pendown() turtle.begin_fill() turtle.forward(100) turtle.right(360 - 360/4) turtle.forward(100) turtle.right(360 - 360/4) turtle.forward(100) turtle.right(360 - 360/4) turtle.forward(100) turtle.right(360 - 360/4) turtle.end_fill() # pentagon turtle.penup() turtle.goto(-120, 0) turtle.pendown() turtle.begin_fill() turtle.forward(100) turtle.right(360 - 360/5) turtle.forward(100) turtle.right(360 - 360/5) turtle.forward(100) turtle.right(360 - 360/5) turtle.forward(100) turtle.right(360 - 360/5) turtle.forward(100) turtle.right(360 - 360/5) turtle.end_fill() # hexagon turtle.penup() turtle.goto(80, 0) turtle.pendown() turtle.begin_fill() turtle.forward(100) turtle.right(360 - 360/6) turtle.forward(100) turtle.right(360 - 360/6) turtle.forward(100) turtle.right(360 - 360/6) turtle.forward(100) turtle.right(360 - 360/6) turtle.forward(100) turtle.right(360 - 360/6) turtle.forward(100) turtle.right(360 - 360/6) turtle.end_fill() # octagon turtle.penup() turtle.goto(320, 0) turtle.pendown() turtle.begin_fill() turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.forward(100) turtle.right(360 - 360/8) turtle.end_fill() turtle.penup() turtle.goto(-50, 200) turtle.pendown() turtle.write("Cool Colorful Shapes") turtle.hideturtle() turtle.done()
false
b0c6434539536ee3c7db23fb6977ca940037d147
mcampo2/python-exercises
/chapter_03/exercise_02.py
1,594
4.53125
5
#!/usr/bin/env python3 # (Geometry: great circle distance) The great circle distance is the distance between # two points on the surface of a sphere. Let (x1, y2) and (x2, y2) be the geographical # latitude and longitude of two points. The great circle distance between the two # points can be computed using the following formula: # d = radius X arccos(sin(x₁) X sin(x₂) + cos(x₁) X cos(x₂) X cos(y₁ - y₂)) # Write a program that prompts the user to enter the latitude and longitude of two # points on the earth in degrees and displays its great circle distance. The average # earth radius is 6,371.01 km. Note that you need to convert the degrees into radians # using the math.radians function since the Python trigonometric functions use # radians. The latitude and longitude degrees in the formula are for north and west. # Use negative to indicate south and east degrees. Here is a sample run: # Enter point 1 (latitude and longitude) in degrees: # 39.55, -116.25 [Enter] # Enter point 2 (latitude and longitude) in degrees: # 41.5, 87.37 [Enter] # The distance between the two points is 10691.79183231593 km import math RADIUS = 6371.01 x1, y1 = eval(input("Enter point 1 (latitude and longitude) in degrees: ")) x2, y2 = eval(input("Enter point 2 (latitude and longitude) in degrees: ")) x1 = math.radians(x1) y1 = math.radians(y1) x2 = math.radians(x2) y2 = math.radians(y2) distance = RADIUS * math.acos(math.sin(x1) * math.sin(x2) \ + math.cos(x1) * math.cos(x2) * math.cos(y1 - y2)) print("The distance between the two points is", distance, "km")
true
e4c59a6991788b320fdfd4aeea0e8c894d403d39
mcampo2/python-exercises
/chapter_02/exercise_06.py
680
4.46875
4
#!/usr/bin/env python3 # (Sum the digits in an integer) Write a program that reads an integer between 0 and # 1000 and adds all the digits in the integer. For example, if an integer is 932, the # sum of all it's digits is 14. (Hint: Use the % operator to extract digits, and use the //) # operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 // # 10 = 93.) Here is a sample run: # Enter a number between 0 and 1000: 999 [Enter] # The sum of the digits is 27 number = eval(input("Enter a number between 0 and 1000: ")) sum = number // 1000 sum += number % 1000 // 100 sum += number % 100 // 10 sum += number % 10 print("The sum of the digits is", sum)
true
ebb74354b22feb3d6d6a27b546111115d4ae8964
praisethedeviI/1-course-python
/fourth/pin_checker.py
788
4.125
4
def check_pin(pin): nums = list(map(int, pin.split("-"))) if is_prime_num(nums[0]) and is_palindrome_num(nums[1]) and is_a_power_of_two(nums[2]): message = "Корректен" else: message = "Некорректен" return message def is_prime_num(num): tmp = 2 while num % tmp != 0: tmp += 1 if tmp == num: return True else: return False def is_palindrome_num(num): if str(num) == str(num)[::-1]: return True else: return False def is_a_power_of_two(num): checker = True while num != 1: if num % 2: checker = False break num /= 2 return checker pin_code = input() print(check_pin(pin_code))
true
65378f3f4696073f33c1708935fc45f8deb2e5d1
ishaansathaye/APCSP
/programs/guessingGame.py
1,677
4.125
4
# from tkinter import * # # root = Tk() # root.title("Computer Guessing Game") # root.geometry("500x500") # lowVar = StringVar() # highVar = StringVar() # labelVar = StringVar() # guessVar = StringVar() # # def range(): # lowLabel = Label(root, textvariable=lowVar) # lowVar.set("What is the lower bound of the range?: ") # lowLabel.place(x=0, y=10) # text1 = Text(root, height=1.05, width=10) # text1.place(x=250, y=10) # # highLabel = Label(root, textvariable=highVar) # highVar.set("What is the higher bound of the range?: ") # highLabel.place(x=0, y=40) # text2 = Text(root, height=1.05, width=10) # text2.place(x=250, y=40) # # # # lBound, hBound = range() # # lowBound = str(lBound-1) # # highBound = str(hBound) # # randomLabel = Label(root, textvariable=labelVar) # labelVar.set("Computer Guess: ") # randomLabel.place(x=150, y=250) # # randomLabel = Label(root, textvariable=guessVar) # guessVar.set("None") # randomLabel.place(x=260, y=250) # # def math() # # # newMatch = True # while newMatch: # guessVar.set(text1.get) # root.mainloop() low = input("What is the lower bound of the range?: ") high = input("What is the higher bound of the range?: ") print() print() intLow = int(low)-1 intHigh = int(high) match = True while match: guess = round((intLow + intHigh) / 2) print("Computer's Guess: ", guess) correct = input("Is the matching number? (low, correct, high): ") print() if correct == "low": intLow = guess elif correct == "high": intHigh = guess elif correct == "correct": print() print("I guessed your number:", guess) match = False
true
920ed667628f9fbb5783d72dd234a372c1f0ab87
Asish-Kumar/Python_Continued
/CountingValleys.py
743
4.25
4
""" A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. example input : UDDDUDUU """ def countingValleys(n, s): result = 0 k = 0 start = False for i in range(n): if k < 0: start = True else: start = False if s[i] == 'D': k -= 1 else: k += 1 print(start, k) if start and k==0: result += 1 return result s = input("Enter U and D combinations: ") print(countingValleys(len(s), s))
true
5e36170af1209383fed6749d2c7302971cd6c354
dhalimon/Turtle
/race.py
1,883
4.25
4
import turtle import random player_one = turtle.Turtle() player_one.color("green") player_one.shape("turtle") player_one.penup() player_one.goto(-200,100) player_two = player_one.clone() player_two.color("blue") player_two.penup() player_two.goto(-200,100) player_one.goto(300,60) player_one.pendown() player_one.circle(40) player_one.penup() player_one.goto(-200,100) player_two.goto(300,-140) player_two.pendown() player_two.circle(40) player_two.penup() player_two.goto(-200,-100) #Developing the Game # Step 1: You’ll start by telling your program to check if either turtle has reached its home. # Step 2: If they haven’t, then you’ll tell your program to allow the players to continue trying. # Step 3: In each loop, you tell your program to roll the die by randomly picking a number from the list. # Step 4: You then tell it to move the respective turtle accordingly, with the number of steps based on the outcome of this random selection. #Creating the Die die = [1,2,3,4,5,6] for i in range(20): if player_one.pos() >= (300,100): print("Player One Wins!") break elif player_two.pos() >= (300,-100): print("Player Two Wins!") break else: player_one_turn = input("Press 'Enter' to roll the die ") die_outcome = random.choice(die) print("The result of the die roll is: ") print(die_outcome) print("The number of steps will be: ") print(20*die_outcome) player_one.fd(20*die_outcome) player_two_turn = input("Press 'Enter' to roll the die ") d = random.choice(die) print("The result of the die roll is: ") print(die_outcome) print("The number of steps will be: ") print(20*die_outcome) player_two.fd(20*die_outcome)
true
e346adc9388fadbb152c9c5698b5425a8f78afd1
hungnv21292/Machine-Learning-on-Coursera
/exe1/gradientDescent.py
1,511
4.125
4
import numpy as np from computeCost import computeCost def gradientDescent(X, y, theta, alpha, num_iters): #GRADIENTDESCENT Performs gradient descent to learn theta # theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by # taking num_iters gradient steps with learning rate alpha # Initialize some useful values m = y.size # number of training examples J_history = np.zeros(shape=(num_iters, 1)) #temp = np.zeros(shape=(2, 1)) temp = np.zeros(shape=(3, 1)) print X for i in range(num_iters): # ====================== YOUR CODE HERE ====================== # Instructions: Perform a single gradient step on the parameter vector # theta. # # Hint: While debugging, it can be useful to print out the values # of the cost function (computeCost) and gradient here. # predictions = X.dot(theta).flatten() errors_x1 = (predictions - y) * X[:, 0] errors_x2 = (predictions - y) * X[:, 1] errors_x3 = (predictions - y) * X[:, 2] temp[0] = theta[0] - alpha * (1.0 / m)*errors_x1.sum() temp[1] = theta[1] - alpha * (1.0 / m)*errors_x2.sum() temp[2] = theta[2] - alpha * (1.0 / m)*errors_x3.sum() theta = temp # ============================================================ # Save the cost J in every iteration #J_history[i, 0] = computeCost(X, y, theta) return theta, J_history
true
5cce1caf8666c82ea5f180d45188272a82e290d3
Anupam-dagar/Work-with-Python
/Very Basic/remove_vowel.py
435
4.5625
5
#remove vowel from the string. def anti_vowel(text): result = "" for char in text: if char == "A" or char == "a" or char == "E" or char == "e" or char == "I" or char == "i" or char == "O" or char == "o" or char == "U" or char == "u": result = result else: result = result + char return result string = raw_input("enter your word:") answer = anti_vowel(string) print answer
true
0fb68f202520e3370e544f8b7d53a2ad0ad69c42
Anupam-dagar/Work-with-Python
/Very Basic/factorial.py
228
4.1875
4
#calculate factoial of a number def factorial(x): result = 1 for i in range(1,x+1): result = result * i return result number = int(raw_input("enter a number:")) answer = factorial(number) print answer
true
fb067a66d72ae73131adf2dc34c0ce568ab87cad
kushagraagarwal19/PythonHomeworks
/HW2/5.py
876
4.15625
4
johnDays = int(input("Please enter the number of days John has worked")) johnHours = int(input("Please enter the number of hours John has worked")) johnMinutes = int(input("Please enter the number of minutes John has worked")) billDays = int(input("Please enter the number of days bill has worked")) billHours = int(input("Please enter the number of hours bill has worked")) billMinutes = int(input("Please enter the number of minutes bill has worked")) totalMinutes = johnMinutes + billMinutes carryForwardHours = totalMinutes//60 totalMinutes = totalMinutes%60 totalHours = johnHours+billHours+carryForwardHours carryForwardDays = totalHours//24 totalHours = totalHours%24 totalDays = carryForwardDays+johnDays+billDays print("The total time both of them worked together is: {} days, {} hours and {} minutes.".format(str(totalDays), str(totalHours), str(totalMinutes)))
true
200e529f8f5c8d35758263c382cb995d8e467399
alaminbhuyan/Python-solve
/problem/Map&Lambda.py
459
4.125
4
# # n = int(input()) # # def fibonacci(num): # lis = [0,1] # for i in range(2,num): # lis.append(lis[i-2]+lis[i-1]) # return (lis[0:num]) # x = fibonacci(n) # print(list(map(lambda x: pow(x,3),x))) def fibonacci(num): lis = [0,1] for i in range(2,num): lis.append(lis[i-2]+lis[i-1]) return (lis[0:num]) cube = lambda x: pow(x,3) if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
false
df23c42f672c812f81c6f10ee3558bce3f51946c
BarnaTB/Level-Up
/user_model.py
2,023
4.28125
4
import re class User: """ This class creates a user instance upon sign up of a user, validates their email and password, combines their first and last names then returns the appropriate message for each case. """ def __init__(self, first_name, last_name, phone_number, email, password): self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.email = email self.password = password def validate_email(self): """ Method checks that a user's email follows semantics for a valid email; first characters must be letters followed by a fullstop, then the '@' symbol followed by letters, a fullstop and then finally letters. Returns the valid email. """ # source: https://docs.python.org/2/howto/regex.html if not re.match(r"[^@.]+@[A-Za-z]+\.[a-z]+", self.email): return 'Invalid email address!' return self.email def combine_name(self): """ Method checks that the entered values for names are strings. If so it returns both names combined, else it requests the user to enter string values. """ if self.first_name.isalpha() and self.last_name.isalpha(): username = self.first_name + " " + self.last_name return username return 'Names must be alphabets' def validate_password(self): """ Method checks that a user's password follows specific criteria such as at least one uppercase character, one lowercase, one number and one spceial character. Password should also be atleast six characters long. """ # source: https://docs.python.org/2/howto/regex.html if not re.match(r"[A-Za-z0-9@#]", self.password): return 'Oops!, invalid password' elif len(self.password) < 6: return 'Password should be at least six characters long' return 'Valid password!'
true
d5a2414bc8d3e3fb711cc0c43fac1122173d4388
mitchellroe/exercises-for-programmers
/python/02-counting-the-number-of-characters/count.py
381
4.3125
4
#!/usr/bin/env python3 """ Prompt for an input string and print the number of characters """ def main(): """ Prompt for an input string and print the number of characters """ my_string = input("What is the input string? ") num_of_chars = len(my_string) print(my_string + " has " + str(num_of_chars) + " characters.") if __name__ == '__main__': main()
true
59af2128b9e6d314ca90fa7cd770f0f1f4278030
siraiwaqarali/Python-Learning
/Chapter-02/UserInput.py
297
4.15625
4
# To take input from user we use input() function name = input("Enter your name: ") print("Hello "+name) # input(Always takes input as a string) age=input("Enter your age: ") # This age is in String print("Your age is "+age) # Agr age int mn huta tou ye concatenate ni huta
false
5d9192fb3a7f91af57e796ab3325891af0c2cabe
siraiwaqarali/Python-Learning
/Chapter-05/10. More About Lists.py
582
4.15625
4
# generate list with range function # index method generated_list = list(range(1, 11)) print(generated_list) # output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3] print(numbers.index(3)) # gives the index of the provided element print(numbers.index(3, 3)) # gives the index of the provided element and second argument is from which index to start searching print(numbers.index(7, 4, 8)) # gives the index of the provided element, 2nd arg=start searching index & 3rd arg=stop searching
true
9e0d8659be7a01bfaccc5d978b4b495e571491a1
siraiwaqarali/Python-Learning
/Chapter-03/ForLoopExample1.py
405
4.125
4
# sum of first ten natural numbers total=0 for i in range(1,11): # for sum of 20 numbers range(1,21) total+=i print(f"Sum of first ten natural numbers is {total}") # Sum of n natural numbers n=input("Enter the number: ") n=int(n) total=0 for i in range(1,n+1): # Second argument is excluded so to reach n we give n+1 total+=i print(f"Sum of first {n} natural numbers is {total}")
true
bf1c0a0d7e98d1d89ff053e71fdd374152848ae6
siraiwaqarali/Python-Learning
/Chapter-01/PythonCalculations.py
758
4.375
4
print(2+3) print(2-3) print(2*3) print(2/4) # This gives answer in fraction print(4/2) # This gives 2.0 print(4//2) # This gives 2 beacuse it is integer division print(2//4) # This gives 0 beacuse it is integer division print(11//3) # This gives 3 beacuse it is integer division print(6%2) # This gives 0 print(11%3) # This gives 2 print(2**3) # This gives 8 2 power 3 = 8 print(4**2) # This gives 16 4 power 2 = 16 #agr square root nikalna hu tou power 1/2 huti hai yani 0.5 tou exponent mn 0.5 dedo square root ajyega #for square root of 2 we write print(2**0.5) #This gives square root of 2 # there is another function for rounding the value which is round(value,digits) print(round(2**0.5,4))
true
9ebdd87c5067140b6e3d5af41a58569552b85a11
siraiwaqarali/Python-Learning
/Chapter-16/Exercise3.py
652
4.15625
4
''' Exercise#03: Create any class and count no. of objects created for that class ''' class Person: count_instance = 0 def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age # Increment count_instance each time the object/instance is created Person.count_instance +=1 person1 = Person('Waqar Ali', 'Siyal', 21) person2 = Person('Ahmed Ali', 'Siyal', 24) person3 = Person('Usama', 'Shaikh', 20) person4 = Person('Imtiaz', 'Buriro', 14) person5 = Person('Uzair', 'Abro', 19) print(f'No. of Objects: {Person.count_instance}')
true
01fa9082ef45132e18e8db69a9e00b278d4f0167
siraiwaqarali/Python-Learning
/Chapter-16/14. Special magic(dunder) method, operator overloading, polymorphism.py
1,858
4.21875
4
# Special magic/dunder methods # operator overloading # polymorphism - kisi cheez ki ek se zyada forms - one example is method overriding class Phone: def __init__(self, brand, model, price): self.brand = brand self.model = model self.price = price def phone_name(self): return f'{self.brand} {self.model}' # str, repr - ye tb call huty hain ja hum apne object ko print krte hain # developers str mn we formatted string return krte hain or repr mn object ki representation ko show krte hain def __str__(self): return f'{self.brand} {self.model}' def __repr__(self): return f'Phone(\'{self.brand}\', \'{self.model}\', {self.price})' # len - jab bhi len function ke andr humari class ka object pass krenge tou ye call huga def __len__(self): return len(self.phone_name()) # operator overloading # add - ye tab call huga jab hum apni class ke do objects ko add krengy def __add__(self, other): return self.price + other.price class SmartPhone(Phone): def __init__(self, brand, model, price, camera): super().__init__(brand, model, price) self.camera = camera def phone_name(self): return f'{self.brand} {self.model} and price is {self.price}' my_phone = Phone('Nokia', '1100', 1000) my_phone2 = Phone('Nokia', '1600', 1200) # print(my_phone) # agr dono __str__ or __repr__ define kiye hue hain tou str wala call huga lekin hum dono ko alg alg bhi call kr skte hain print(str(my_phone)) print(repr(my_phone)) print(len(my_phone)) print(my_phone + my_phone2) my_smartphone = SmartPhone('onePlus', '5t', 33000, '16 MP') print(my_phone.phone_name()) print(my_smartphone.phone_name()) # Here phone_name() has more than one forms which is a example of polymorphism
false
d1ecd5f71b352f254142854248f00f9188a11718
siraiwaqarali/Python-Learning
/Chapter-05/6. is vs equals.py
392
4.15625
4
# compare lists # ==, is # == check values inside list # is checks address inside memory fruits1 = ['orange', 'apple', 'pear'] fruits2 = ['banana', 'kiwi', 'apple'] fruits3 = ['orange', 'apple', 'pear'] print(fruits1==fruits2) # False print(fruits1==fruits3) # True print(fruits1 is fruits3) # False
true
d351fdf978fde1ea7045c7681b8afe871e25d6d4
siraiwaqarali/Python-Learning
/Chapter-09/4. Nested List Comprehension.py
388
4.4375
4
example = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] # Create a list same as above using nested list comprehension # new_list = [] # for j in range(3): # new_list.append([1, 2, 3]) # print(new_list) # nested_comp = [ [1, 2, 3] for i in range(3)] # but also generate nested list using list comprehension nested_comp = [ [i for i in range(1,4)] for j in range(3)] print(nested_comp)
true
34b5bbfbf050c3d35eb2e35c005a836091f49b07
siraiwaqarali/Python-Learning
/Chapter-02/StringConcatenation.py
545
4.21875
4
first_name="Waqar" last_name="Siyal" full_name=first_name+last_name print(full_name) first_name="Waqar" last_name="Siyal" full_name=first_name + " " +last_name print(full_name) #String ke sath kisi number ko add ni kr skte string mn srf string ko add kr skte hain #print(first_name+3) This will give error print(first_name+"3") print(first_name+str(3)) #str() function converts the float r int to string #Lekin string ko kisi number se multiply kr skty hain like first_name*3 tou first_name 3 br print huga print(first_name*3)
false
e4ca3edda19ce73a875e890dcfdb832e3b9ae62f
siraiwaqarali/Python-Learning
/Chapter-02/StepArgument.py
585
4.21875
4
#Syntax: [start argument:stop argument:step argument] print("Waqar"[1:3]) #Step argument yani jitna step dengy utna step agy lekr chlega print("Waqar"[0:5:1]) #ek ka step lega koi frk ni prega q wese bi next word he ayega print("Waqar"[0:5:2]) #ab do ka step lega print("Computer"[0::2]) print("Waqar"[0::3]) #ab back ane k liye print("language"[5::-1]) #back se ayega index 5 se r ek step se yani frk ni prega bs back se ayega print("Waqar"[-1::-1]) #poori string reverse print hugi print("Waqar"[::-1]+" \"Reverse of String by trick\"") # reverse string ki trick
false
e13a6a3c3047813a8f6aeff7232b8efb65855cf8
JSNavas/CursoPython2.7
/7.listas.py
1,401
4.75
5
# Listas = arreglos o vectores # Acceder a listas dentro de otra lista # Se accede a traves del indice de donde se encuentra la lista # que esta dentro de la lista principal y al lado se coloca el # indice al que queramos acceder de la lista que esta adentro. # En este caso la lista que esta adentro se encuentra en el # indice [5] y el indice al que quiero acceder de esa lista # es el numero [1] lista = [1,2,3,4,5,[6,7,8,9]] acceso = lista[5][1] # Si solo se quiere mostrar lo que contiene la lista de adentro # se coloca solo el indice en donde se encuentra la lista acceso2 = lista[5] print "LISTA CON UNA LISTA ADENTRO" print "lista principal" print lista print " 0 1 2 3 4 5[0 1 2 3] <- INDICE DE LA LISTA\n" print acceso print print "Lista de adentro" print acceso2 # Para acceder directamente a las lista de forma inversa se utiliza # los indice -1,-2,-3 etc... Comenzando por el 1, es decir, si # si queremos acceder al ultimo numero de un arreglo, se coloca el -1 #en este caso mostraria la lista que esta adentro, ya que la lista es la ultima print print "ACCEDER DE FORMA INVERSA AL ULTIMO ELEMENTO DE LA LISTA" acceso3 = lista[-1] print acceso3 # Si se quiere acceder al ultimo elemento de la lista que esta adentro print print """ACCEDER AL ULTIMO ELEMENTO DE LA LISTA QUE SE ENCUENTRA DENTRO DE LA LISTA PRINCIPAL""" acceso4 = lista[-1][-1] print print acceso4
false
03347c9073840ac9da09d62c75e217d0db49e849
advinstai/python
/solucoes/Duan-Python/Lista1-Python/problem02.py
314
4.375
4
# iteracao manual print("hello, world!") print("hello, world!") print("hello, world!") print("hello, world!") print("--------------") # iteracao com FOR for i in range(1,5): print("hello, world!") print("==============") # iteracao com WHILE j=1 while j<=4: print("hello, world!") j+=1 print("..............")
false
3789bb48da7c905c0414e30904e3b7af05473316
advinstai/python
/solucoes/Duan-Python/Lista3-Python/p29.py
205
4.1875
4
def enumerate(lista): return [(lista.index(i),i) for i in lista] ''' Testando a funcao lista = ["a","b","c"] print(enumerate(lista)) [print(index,value) for index, value in enumerate(["a","b","c"])] '''
false
d6c33d2dc1ca4b5913aaa65fbc33f4c9622ec43d
EEsparaquia/Python_project
/script2.py
420
4.25
4
#! Python3 # Print functions and String print('This is an example of print function') #Everything in single quots is an String print("\n") print("This is an example of 'Single quots' " ) print("\n") print('We\'re going to store') print("\n") print('Hi'+'There') #Plus sign concatenate both strings print('Hi','There') #Comma add an space print("\n") print('Hi',5) print('Hi '+str(5)) print("\n") print(float('8.5')+5)
true
5e1d7603eec9b98a94386628eed855ce39e05199
EEsparaquia/Python_project
/script25.py
911
4.40625
4
#! Python3 # Programming tutorial: # Reading from a CSV spreadsheet ## Example of the content of the file ## called example.csv: # 1/2/2014,5,8,red # 1/3/2014,5,2,green # 1/4/2014,9,1,blue import csv with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: print(row) print(row[0]) print(row[0],row[1]) print('\n') ## Passing the data into separates string: with open('example.csv') as csvfile: readCSV2 = csv.reader(csvfile, delimiter=',') dates = [] colors = [] for row in readCSV2: color = row[3] date = row[0] dates.append(date) colors.append(color) print(dates) print(colors) WhatColor = input('What color do you wish to know the date of?') coldex = colors.index(WhatColor.lower()) #lower() for make all in lowercases print(coldex) theDate = dates[coldex] print(theDate) print('the date of the color',WhatColor,'is',theDate)
true
f8202c0b6613dbf791d2e0f02dbe7896cd0cf166
cmgc/moocology-python-assignments
/week_1/fizz_buzz.py
341
4.125
4
#!/usr/bin/env python user_input = raw_input("Enter number:") def fizz_buzz(user_input): length = int(user_input) + 1 for i in range(1, length): if i % 3 == 0 and i % 5 == 0: print("%i FizzBuzz") % (i) elif i % 5 == 0: print("%i Buzz") % (i) elif i % 3 == 0: print("%i Fizz") % (i) fizz_buzz(user_input)
false
07ecbbc1a8bf0e46b6432dbea343063da6d55a7b
medisean/python-algorithm
/quick_sort.py
645
4.125
4
''' Quick sort in python. Quick sort is not stable. Time complexity: O(nlogn) Space complexity: O(log2n) ''' def quick_sort(lists, left, right): if left >= right: return lists first = left last = right key = lists[first] while first < last: while first < last and lists[last] >= key: last = last - 1 lists[first] = lists[last] while first < last and lists[first] <= key: first = first + 1 lists[last] = lists[first] lists[first] = key quick_sort(lists, left, first-1) quick_sort(lists, last+1, right) return lists if __name__ == '__main__': lists = [3, 2, 1, 5, 4] print(quick_sort(lists, 0, len(lists) - 1))
true
19adac4e6b7c3168a84b2d9875ac3771afc8fa4d
sat5297/hacktober-coding
/Mergesort.py
2,754
4.125
4
# Python program for implementation of MergeSort # Merges two subarrays of arr[]. # First subarray is arr[l..m] # Second subarray is arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0 , n1): L[i] = arr[l + i] for j in range(0 , n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2 : if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the # sub-array of arr to be sorted def mergeSort(arr,l,r): if l < r: # Same as (l+r)//2, but avoids overflow for # large l and h m = (l+(r-1))//2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) # Driver code to test above arr = [12, 11, 13, 5, 6, 7] n = len(arr) print ("Given array is") for i in range(n): print ("%d" %arr[i]), mergeSort(arr,0,n-1) print ("\n\nSorted array is") for i in range(n): print ("%d" %arr[i]), #update(alternate way) ## Python program for implementation of MergeSort """ def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+= 1 else: arr[k] = R[j] j+= 1 k+= 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+= 1 k+= 1 while j < len(R): arr[k] = R[j] j+= 1 k+= 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end =" ") print() # driver code to test the above code if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print ("Given array is", end ="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end ="\n") printList(arr) """
false
0d31b00864cf9ca4c43c1d683594399ad9480f5d
junhao69535/pycookbook
/chapter2/del_unneed_char_from_str.py
967
4.1875
4
#!coding=utf-8 """ 删除字符串中不需要的字符 """ # 想去掉文本字符串开头,结尾或者中间不想要的字符,比如空白 # strip()方法用于删除开始和结尾的字符。lstrip()和rstrip()分别从左和从右执行 # 删除操作。默认情况下,这下方法会删除空白字符,但也可以指定 s = ' hello world \n' print s.strip() # 'hello world' 会把换行符也删掉 print s.lstrip() # 'hello world \n' print s.rstrip() # ' hello world' t = '-----hello=====' print t.lstrip('-') print t.strip('-=') # 这些 strip() 方法在读取和清理数据以备后续处理的时候是经常会被用到的 # 但是需要注意的是去除操作不会对字符串的中间的文本产生任何影响。 # 如果你想处理中间的空格,那么你需要求助其他技术。比如使用 replace() 方法或者是用正则表达式替换。 # 对于更高阶的strip,你可能需要使用 translate() 方法。
false
5884711de2f5b7cadbbc4c2b317d4c388e4ae145
junhao69535/pycookbook
/chapter2/bytestr.py
1,140
4.15625
4
#!coding=utf-8 """ 字节字符串上的字符串操作 """ # 想在字节字符串上执行普通的文本操作(比如移除,搜索和替换)。 # 字节字符串同样支持大部分和文本字符串一样的内置操作。 data = 'Hello World' # 在python2,str就是字节字符串,不需要加b print data[0:5] print data.startswith('Hello') print data.split() print data.replace('Hello', 'Hello Cruel') # 这些操作同样也适用于字节数组 data = bytearray('Hello World') print data[0:5] print data.startswith('Hello') print data.split() print data.replace('Hello', 'Hello Cruel') # 如果使用正则表达式匹配字节字符串,但是正则表达式本身必须也是字节字符串 # 这个约束在python2中不适用 data = 'FOO:BAR,SPAM' import re print re.split('[:,]', data) # 字节字符串的索引操作返回整数而不是单独字符 # 但在python2中不适用于字节字符串,只适用于bytearray a = 'Hello World' print a[0] b = bytearray('Hello World') print b[0] # 默认ascii编码 # 注:处理文本字符串没有必要为了性能能改用字节字符串来操作。
false
882c2faa3ca3aed3faebdb2a261ef8c9a5411bac
junhao69535/pycookbook
/chapter4/permutation.py
1,171
4.1875
4
#!coding=utf-8 """ 排列组合的迭代 """ # 像迭代遍历一个集合中元素的所有可能的排列或组合 # itertools模块提供了三个函数来解决这类问题,其中一个是 itertools.permutations() , # 它接受一个集合并产生一个元组序列,每个元组由集合中所有元素的一个可能排列组成。 from itertools import permutations # 排列 items = ['a', 'b', 'c'] for p in permutations(items): # A33 print p # 如果想得到指定长度的所有排列,可以: for p in permutations(items, 2): # A32 print p from itertools import combinations # 组合 for c in combinations(items, 3): # C33 print c for c in combinations(items, 2): # C32 print c for c in combinations(items, 1): # C31 print c # 在计算组合的时候,一旦元素被选取就会从候选中剔除掉(比如如果元素’a’已经被选取了, # 那么接下来就不会再考虑它了)。 而函数 itertools.combinations_with_replacement() # 允许同一个元素被选择多次,比如: from itertools import combinations_with_replacement for c in combinations_with_replacement(items, 3): print c
false
4eec7dce66ee380c61c8e0c1b5b680a03b6fa4ad
ccaniano15/inClassWork
/text.py
338
4.25
4
shape = input("triangle or rectangle?") if shape == "triangle": width = int(input("what is the length?")) height = int(input("what is the height?")) print(width * height / 2) elif shape == "rectangle": width = int(input("what is the length?")) height = int(input("what is the height?")) print(width * height) else: print("error")
true
b6375a70de01303ae87311ff5d37816cd853742c
ArunKarthi-Git/pythonProject
/Program54.py
467
4.1875
4
if __name__=='__main__': a=input("Enter the character:") while a != '$': if ord(a) >=65 and ord(a)<=90: print("The given character is upper",a) elif ord(a)>=96 and ord(a)<=122: print("The given character is lower",a) elif ord(a)>=46 and ord(a)<=57: print("The given character is digit", a) else: print("The given character is special",a) a=input("Enter the character:")
false
d03b2a6a44cae8d7a5a2829f3d25040e47932f66
ArunKarthi-Git/pythonProject
/Program72.py
1,186
4.1875
4
if __name__=='__main__': matrix = [] print("Enter the entries rowwise:") i=0 while i<3: i+=1 a=[] j=0 while j<3: j+=1 a.append(int(input())) #print(a) matrix.append(a) matrix1 = [] print("Enter the entries rowwise:") i = 0 while i < 3: i += 1 b = [] j = 0 while j < 3: j += 1 b.append(int(input())) # print(a) matrix1.append(b) #print(matrix) i=0 while i<3: j=0 while j <3: #print(i,j) #print(matrix[i][j]) print(matrix[i][j], end=" ") j+=1 i+=1 print() print() i = 0 while i < 3: j = 0 while j < 3: # print(i,j) # print(matrix[i][j]) print(matrix1[i][j], end=" ") j += 1 i += 1 print() print() i = 0 while i < 3: j = 0 while j < 3: # print(i,j) # print(matrix[i][j]) print(matrix[i][j]+matrix1[i][j], end=" ") j += 1 i += 1 print()
false
953f98b68c708b40b32bdc581a3eaeaf74662549
Floreit/PRG105
/KyleLud4.1.py
994
4.15625
4
#Declare variables to be used in the while loop stop = 0 calories = 4.2 minutes = 0 time = 0 #while loop with if statements to count the intervals, increments by 1 minute every iteration, when it hits an interval it will display the calories burned while stop != 1: minutes = minutes + 1 if minutes == 10: print ("The calories burned in " , minutes, "minutes are: ", round(calories,2) * minutes) if minutes == 15: print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes) if minutes == 20: print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes) if minutes == 25: print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes) if minutes == 30: print ("The calories burned in ", minutes, "minutes are: ", round(calories,2) * minutes) stop = 1 # stopping the program at 30 so it doesnt run infinitely
true
1885b7c5930b016b448bff1741f70d7b2ab74941
Hank310/RockPaperScissors
/RPS1.py
2,028
4.1875
4
#Hank Warner, P1 #Rock, Paper Scissors game # break int0 pieces # Welcome screenm with name enterable thing # Score Screen, computer wins, player wins, and ties # gives options for r p s & q # Game will loop until q is pressed # Eack loop a random choice will be generated # a choice from thge player, compare, and update score # When game iis over, final score display # WELCOME PAGE # Name prompt # Welcome msg # Imports import random # Variables playerSC = 0 computerSC = 0 ties = 0 # make a list cChoice =["r", "p", "s"] print("Welcome to Rock Paper Scissors") name = input("Enter your name: ") # main loop while True: print(" Score: ") print("Computer: " + str(computerSC)) print(name + ": " + str(playerSC)) print("Ties:" + str(ties)) choice = input("Enter 'r' for Rock, 'p' for Paper, 's' for Scissors, or 'q' to Quit") compChoice = random.choice(cChoice) print( "Computer picked: " + compChoice) if choice == "q": break if choice == "r": print( name +" Picked Rock") if compChoice == "r": print("Computer picked Rock, it is a tie") ties = ties + 1 elif compChoice == "p": print("Computer picked Paper, Computer wins") computerSC = computerSC + 1 else: print("Computer picked Scissors, " + name + " wins") playerSC = playerSC + 1 elif choice == "p": if compChoice == "p": print("Computer picked Paper, it is a tie") ties = ties + 1 elif compChoice == "s": print("Computer picked Scissors, Computer wins") computerSC = computerSC + 1 else: print("Computer picked Rock, " + name + " wins") playerSC = playerSC + 1 elif choice == "s": if compChoice == "s": print("Computer picked Scissors, it is a tie") ties = ties + 1 elif compChoice == "r": print("Computer picked Rock, Computer wins") computerSC = computerSC + 1 else: print("Computer picked Paper, " + name + " wins") playerSC = playerSC + 1 else: print("That is not an option")
true
7d11564338a3b1f1add3d647eb7bf2fff00910fd
PranaKnight/Dominando-Python
/print.py
1,000
4.34375
4
#Formas de imprimir o número para o usuário em Python print("Este é o capítulo 2 do livro") A = 12 print(A) B = 19 print(B) print(A, B) print("Valor de A =", A) print("Valor de A = {0} e valor de B = {1}" .format(A, B)) print("=+"*40) print(A, B, sep="-") print(A, B, sep=";") #utilização de separadores print("Valor de A = {0:d} e valor de B = {1:d}" .format(A, B)) #d - número inteiro em base 10 print("A = {0:5d}".format(A)) #numero inteiro ocupando no mínimo 5 caracteres alinhado à direita print("A = {0:f}".format(A)) #numero real, exibindo o padrão de 6 casas após a vírgula print("A = {0:2f}".format(A)) #número real, 2 casas após a vírgula print("A = {0:6.3f}".format(A)) #numero real, ocupando no mínimo 6 caracteres e exibindo 1 casa após a vírgula print("qq{:7d}qq".format(A)) #número inteiro ocupando no minimo 7 caracteres à direita print("qq{:<7d}qq".format(A)) #alinhamento a esquerda print("qq{:^7d}qq".format(A)) #alinhamento centralizado #formatação
false
8098951d28b3ca5f954b63e74ab6d887b0664e9f
lyndsiWilliams/cs-module-project-iterative-sorting
/src/searching/searching.py
1,337
4.25
4
def linear_search(arr, target): # Your code here # Loop through the length of the array for i in range(len(arr)): # If this iteration matches the target value if arr[i] == target: # Return the value return i return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here # Set the lowest value to 0 low = 0 # Set the highest value (boundary) to the length of the array - 1 # -1 because when only 1 item is left, it doesn't need to be sorted high = len(arr) - 1 # While the low value is <= the high value (boundary) while low <= high: # Find the midpoint mid = (high + low) // 2 # Begin comparing the target to the midpoint if target == arr[mid]: return mid # If the target is < the midpoint if target < arr[mid]: # Cut out the right half of the array (greater than) and # Reassign the high value to the midpoint - 1 high = mid - 1 # If the target is > the midpoint if target > arr[mid]: # Cut out the left half of the array (less than) and # Reassign the low value to the midpoint + 1 low = mid + 1 return -1 # not found
true
f04167639ad0509853dc1c01fa872b250fc95863
mraguilar-mahs/AP_CSP_Into_to_Python
/10_23_Lesson.py
429
4.1875
4
#Lesson 1.3 Python - Class 10/23 #Obj: #Standard: #Modulus - Reminder in a division: # Ex 1: 9/2 = 4 r 1 # Ex 2: 4/10 = 0 r 4 # modulus: % --> 9 mod 2 print(9%2) print(234%1000) print(10%2) print(9%2) # <- with mod 2, check for even/odd # Mod can check for divisibility, if equal to 0 #User Input: user_name = str(input("Please enter your name:")) print(user_name) # Name is storing the value inputed by the user from above
true
d8c4c9b73b5537685496a2216616a341bc10ac05
krishnagrover1000/My-Python-Work
/Lists Refrence.py
470
4.25
4
#%% # List == Collection Of Data Types a = [1, 2, 3, 9, 8, 6, 12, 456] b = [1, "String", 'icji', 0.765, True] c = ["Aryan", "Vardaan", "Niya"] x = ["Aryan", "Vardaan", "Ajay"] y = ["Cool", "Is", "Cool"] z = ["Niya", "Is", "Smart"] #%% # Printing Out Index's From [] print(x[0], y[1], z[2]) #%% # This Reverseses The List print(y) y.reverse() print(y) #%% # This Function Sorts the Integers In Accsending Order print(a) a.sort() print(a)
false
064717582f1799c539e0df68005379819f932491
cristianoxavier/Campinas-Tech-Talents
/Exercicios/15.py
779
4.1875
4
# Fazer um sistema de Feira Livre(Deve imprimir uma lista com as frutas e pedir para o solicitante colocar o nome e selecionar a fruta e depois deve imprimir o nome do solicitante e a fruta). frutas = { "Banana" ,"Maça" ,"Tomate" ,"Melancia" ,"Uva" ,"Ameixa" ,"Pera" ,"Goiaba" ,"Acerola" ,"Melão" } print("Bem vindo a nossa feira! \n Por favor informe o seu nome: ") nome = input() print(f"Ola {nome}, seja bem vindo! \n Hoje temos essas frutas disponiveis {frutas} \n Qual fruta deseja comprar: ") reserva = input() if reserva in frutas: print(f"{nome} a fruta selecionada foi {reserva}, desejamos uma otima alimentação! \n Volte Sempre") else: print(f"{nome}, Infelizmente a fruta {reserva}, não esta mais disponivel")
false
e6a292d99dae34dd81c792d81910d0f2095663ec
cristianoxavier/Campinas-Tech-Talents
/Aula_004/dicionarios.py
802
4.21875
4
''' Dicionario é mais proximo do JSON. Dicionarios recebem valores sensiveis, devem se respeitar os tipos de dados(string, int, float, boolean...) São definidas chaves e valores. Ex: dict = {'Keys': 'value', key: value, key: true or false} ''' dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print(dict['one']) # Prints value for 'one' key print(dict[2]) # Prints value for 2 key print(tinydict) # Prints complete dictionary print(tinydict.keys()) # Prints all the keys print(tinydict.values()) # Prints all the values parametros = {'nome': 'Cristiano', 'codigo':6734, 'departamento': 'Tecnologia', 'ativo': True } print(parametros)
false
a4bd5e100a710fb1e8efdd0132324795da4f64af
cristianoxavier/Campinas-Tech-Talents
/Exercicios/3.py
648
4.21875
4
#Algoritmo para trocar o pneu do carro (Imprimir a sequência para trocar o pneu do carro). print("Bem vindo, você gostaria de trocar o pneu do carro?") trocar = input("Sim? ou Não?: ") if trocar == "Sim" or "sim": print("Qual dos pneus quer trocar?") escolha1 = input("Os da frente? ou os de tras?: ") if escolha1 == "frente" or escolha1 == "tras": print("O da esquerda ou da direita?: ") escolha2 = input("Esquerda ou Direita?: ") if escolha2 == "esquerda" or escolha2 == "direita": print(f"Pneu da {escolha2} trocado com sucesso!") else: print("Obrigado! Operação Finalizada.")
false
a1f4cc9a7b531b3bcbd01ac5eb1285ee44d1e51f
abhishekk26/NashVentures
/Random number Generation.py
2,066
4.1875
4
import math, time class MyRNG: # MyRNG class. This is the class declaration for the random number # generator. The constructor initializes data members "m_min" and # "m_max" which stores the minimum and maximum range of values in which # the random numbers will generate. There is another variable named "m_seed" # which is initialized using the method Seed(), and stores the value of the # current seed within the class. Using the obtained values from above, the # "Next()" method returns a random number to the caller using an algorithm # based on the Park & Miller paper. def __init__(self, low = 0, high = 0): # The constructor initializes data members "m_min" and "m_max" if(low < 2): low = 2 if(high < 2): high = 9223372036854775807 self.m_min = low self.m_max = high self.m_seed = time.time() def Seed(self, seed): # Seed the generator with 'seed' self.m_seed = seed def Next(self): # Return the next random number using an algorithm based on the # Park & Miller paper. a = self.m_min m = self.m_max q = math.trunc(m / a) r = m % a hi = self.m_seed / q lo = self.m_seed % q x = (a * lo) - (r * hi) if(x < a): x += a self.m_seed = x self.m_seed %= m # ensure that the random number is not less # than the minimum number within the user specified range if(self.m_seed < a): self.m_seed += a return int(self.m_seed) def test(): # Simple test function to see if the functionality of my class # is there and works random = MyRNG(6, 10) random.Seed(806189064) per = (73*100)/100 for x in range(per): print("%d, " %(random.Next())) random = MyRNG(1, 5) for x in range(per,100): print("%d, " %(random.Next())) if __name__ == '__main__': test()
true
c95c502184424b7d7f56da51ec7df1bd24c11499
rosexw/LearningPython
/Exercise Files/Ch2/loops_start.py
843
4.25
4
# # Example file for working with loops # def main(): x = 0 # define a while loop # while (x < 5): # print(x) # x = x+1 # define a for loop # for x in range(5,10): # print (x) # use a for loop over a collection # days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] # for d in days: # print (d) # use the break and continue statements # for x in range(5,10): # if (x == 7): break # BREAK if condition is met, the for loop will terminate and fall to next block of code (end of function, prints 5 and 6) # if (x % 2 == 0): continue # CONTINUE skips for that iteration # skips 6, 8 # print (x) #using the enumerate() function to get index days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] for i, d in enumerate(days): print (i, d) if __name__ == "__main__": main()
true
914544f42b91b5d6b7c17378a310add1ea9a67a6
Adarsh2412/python-
/python11.py
663
4.21875
4
def calculator(number_1, number_2, operation): if(operation=='addition'): result=number_1+number_2 return result elif(operation=='subtract'): result=number_1-number_2 return result elif(operation=='multiply'): result=number_1*number_2 return result elif(operation=='divide'): result=number_1/number_2 return result else: print('wrong input') number_1=int(input('Enter the first number')) number_2=int(input('Enter the second number')) operation=str(input('Enter the operation')) a=calculator(number_1, number_2, operation) print(a) s
true
d9de8d029ec05b744ce3e349f7043d6c4a9ff332
irobbwu/Python-3.7-Study-Note
/basic Grammar/10. 函数:python的乐高积木.py
1,471
4.125
4
# 10.7 作业 # 函数:python的乐高积木 # 1.编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值。 def power(x, y): return (x ** y) # 参考答案: def power(x,y): result = x**y return result print(power(2, 8)) # 2.编写一个函数,利用欧几里得算法求最大公约数,例如gcd(x, y)返回值为参数x和参数y的最大公约数 def gcd(x,y): c = 1 while c != 0: c = x % y x = y y = c return x # 参考答案 def gcd(x,y): while y: t = x % y x = y y = t return x print(gcd(18,9)) # 3.编写一个将十进制转换为二进制的函数,要求采用“除2取余”的方式,结果与调用bin()一样返回字符串形式。 def transfer(x): temp = [] num = '' while x > 1: # 应该修改为>0 y = x % 2 x = x // 2 temp = temp.append(y) # 数组的修改temp = temp.append(y)则返回空值 while x != []: num = num + str(temp.pop()) return num # 参考答案: def DectoBin(num): temp = [] result = '' while num: x = num % 2 # 取余数,当做个位...十位...百位...以此类推 num = num // 2 #取整数当做下一次的被除数 temp.append(x) while temp: result += str(temp.pop()) return result print(DectoBin(444))
false
dbe00f7712f950e33b36e69e05d56d7465609c04
StevenM42/Sandbox
/password_check.py
389
4.3125
4
"""Password check program that returns asterisks of password length""" Minimum_character_limit = 6 password = input("Please enter password at least {} characters long: ".format(Minimum_character_limit)) while len(password) < Minimum_character_limit: password = input("Please enter password at least {} characters long: ".format(Minimum_character_limit)) print('*' * len(password))
true
ffac4f7a078c8221458dbba66af1ee4f95ad374c
shreesha-bhat/Python
/reverseofanumber.py
309
4.28125
4
#program to accept a number from the user and find the reverse of the entered number number = int(input("Enter any number : ")) rev = 0 while (number > 0): remainder = number % 10 rev = (rev * 10) + remainder number //= 10 print("Reverse of the entered number is ",rev)
true
45d3281927b36d539619554889b92fac37af3460
shreesha-bhat/Python
/Series1.py
339
4.15625
4
#Program to accept a number “n” from the user; then display the sum of the series 1+1/2+1/3+……….+1/n num = int(input("Enter the value of N : ")) for i in range(1,num+1): if i == 1: print(i,end='+') if i != 1 and i != num: print(f"1/{i}",end='+') if i == num: print(f"1/{i}",end='')
true
3c23bc4b31be19db9439b1b1e8e96b5069c3bd35
shreesha-bhat/Python
/Swapnumbers.py
376
4.1875
4
#Program to swap numbers Number1 = int(input("Enter the First number : ")) Number2 = int(input("Enter the Second number : ")) print(f"Before swap, the values of num1 = {Number1} and num2 = {Number2}") Number1 = Number1 + Number2 Number2 = Number1 - Number2 Number1 = Number1 - Number2 print(f"After swap, the values of num1 = {Number1} and num2 = {Number2}")
true
92a5b52e620fabf557ff30f4d1e471d783db4f2c
shreesha-bhat/Python
/series3.py
417
4.125
4
#Program to accept a number “n” from the user; find the sum of the series 1/23+1/33+1/43……..+1/n3 num = int(input("Enter the value of N : ")) sum = 0 for i in range(1,num+1): if i == 1: print(i,end='+') if i != 1 and i != num: print(f"1/{i}^3",end='+') if i == num: print(f"1/{i}^3") sum += 1/(i * i * i) print("Sum of the series is : ",round(sum,2))
true
e28735a52f2ad739072e8d781353efe1e52badcf
lufeng0614/leetcode
/leetcode-350.py
618
4.3125
4
给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。 ======================================================================= class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ return list(set(nums1) & set(nums2))
false
1cc2bade7b9c08be021593f117bed4971658184d
samdawes/iD-Emory-Python-Projects
/MAD.py
1,155
4.15625
4
print("Mad Libs is starting!") adjective1 = input("Enter an adjective: ") name = input("Enter a name:") verb1 = input("Enter a verb: ") place = input("Enter a place: ") animal = input("Enter a plural animal: ") thing = input("Enter a thing: ") verb2 = input("Enter a second verb: ") noun2 = input("Enter a noun: ") superhero_name = input("Enter a superhero_name:") adjective2 = input("Enter a second adjective: ") #optional vars that could spice the story up #food = input("Enter a food: ") #fruit = input("Enter a fruit: ") #number = input("Enter a number: ") #country = input("Enter a country:") #dessert = input("Enter a dessert:") #year = input("Enter a year:") #The template for the story story = """This morning I woke up and felt '{0}' because '{1}'was going to finally '{2}' over the big '{3}'. On the other side of the '{3}' were many '{4}'s protesting to keep '{5}' in stores. The crowd began to '{6}' to the rythym of the '{7}', which made '{8}' very '{10}'.""".format(adjective1, name, verb1, place, place, animal, thing, verb2, noun2, superhero_name, adjective2) print(story)
false
a452c61845d7ec8f285b3aec32bbb707b8ac38e8
rcmhunt71/hackerrank
/DLLs/insert_into_dllist.py
2,038
4.15625
4
#!/bin/python3 class DoublyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = DoublyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node node.prev = self.tail self.tail = node def print_doubly_linked_list(node, sep): while node: print(str(node.data), end='') node = node.next if node: print(sep, end='') print() # # For your reference: # # DoublyLinkedListNode: # int data # DoublyLinkedListNode next # DoublyLinkedListNode prev # # def sorted_insert(head, data): node = head insert_node = DoublyLinkedListNode(data) while node is not None: if node.next is None or data < node.data or node.data <= data <= node.next.data: break node = node.next if node is None: return insert_node if node.next is None: node.next = insert_node insert_node.prev = node elif data < node.data: insert_node.next = node node.prev = insert_node head = insert_node else: next_node = node.next node.next = insert_node insert_node.prev = node insert_node.next = next_node next_node.prev = insert_node return head if __name__ == '__main__': test_data = [ ([1, 3, 4, 10], 5), ([1, 3, 4, 10], 0), ([1, 3, 4, 10], 20), ([1, 3, 4, 10], 3), ([], 3), ([3, 3, 3], 3), ([1, 3, 3, 4, 10], 3), ] for test_case in test_data: llist = DoublyLinkedList() for llist_item in test_case[0]: llist.insert_node(llist_item) llist1_head = sorted_insert(llist.head, test_case[1]) print_doubly_linked_list(llist1_head, ' ')
true
d9b437283616b1d92f2881a77c4505c421a7f10b
mariasilviamorlino/python-programming-morlino
/PB_implementations/backward_hmm.py
2,510
4.21875
4
""" Backward algorithm implementation for hmms ########### INPUT: model parameters sequence to evaluate OUTPUT: probability of sequence given model ########### Setup Read list of states Read transition probabilities Read emission probabilities Read sequence rows = n. of states cols = length of sequence Create a rows x cols matrix Initialization Start from last column of matrix Store in each cell of the column the corresponding transition from that state to the end state Iteration For each column (proceeding backwards): For each cell in column: sum over the probabilities of the following column, times the transition probabilities to that column, times the emission probabilities of the "following" symbol Termination Compute total score by summing over the probabilities in the first column, times the transition probabilities to the first column, times the emission probabilities of the 1st symbol in each state Generate output: print probability """ def prettymatrix(listoflists): """Human-readable display of lists of lists""" for lyst in listoflists: print(lyst) # set of states state = ["B", "Y", "N", "E"] # transition probabilities -> dictionary of dictionaries t = {"B": {"B": 0, "Y": 0.2, "N": 0.8, "E": 0}, "Y": {"B": 0, "Y": 0.7, "N": 0.2, "E": 0.1}, "N": {"B": 0, "N": 0.8, "Y": 0.1, "E": 0.1}, "E": {"B": 0, "N": 0, "Y": 0, "E": 0}} # transitions are used as follows: first key is starting state, second key is ending state # starting and ending probabilities begin = {"Y": 0.2, "N": 0.8} end = {"Y": 0.1, "N": 0.1} # usage ex.: end["Y"] is the trans probability from Yes to End # emission probabilities -> dictionary of dictionaries e = {"Y": {"A": 0.1, "C": 0.4, "G": 0.4, "T": 0.1}, "N": {"A": 0.25, "C": 0.25, "G": 0.25, "T": 0.25}} # input sequence sequence = "ATGCG" # matrix setup rows = len(state) cols = len(sequence) backward = [[0 for col in range(cols)] for row in range(rows)] # initialization for i in range(1, rows-1): backward[i][cols-1] = end[state[i]] # iteration for j in range(cols-2, -1, -1): for i in range(1, rows-1): for h in range(1, rows-1): increment = backward[h][j+1] * t[state[i]][state[h]] * e[state[h]][sequence[j+1]] backward[i][j] += increment # termination score = 0 for h in range(1, rows-1): increment = backward[h][0] * begin[state[h]] score += increment prettymatrix(backward) print(score) # output: 0.00035011440000000003
true
4fc95e4391dddac7a54da9841cdac8b62b2f8072
barseghyanmher/HTI-1-Practical-Group-1-Mher-Barseghyan
/Classwork_1/triangl.py
361
4.1875
4
a = int(input("Enter a number :")) b = int(input("Enter a number :")) c = int(input("Enter a number :")) if a >= b and a >= c: c,a = a,c elif b >= a and b >= c: b,c = c,b if c>= a + b: print("Not a triangle") elif c*c == a*a + b*b: print("Right triangle") elif c*c < a*a + b*b: print("Acure triangle") else: print("Obtuse triangle")
false
7dab3037afa1f2cf84dd957060a094840efe7308
gibbs-shih/stanCode_Projects
/stanCode_Projects/Weather Master/quadratic_solver.py
1,207
4.5
4
""" File: quadratic_solver.py ----------------------- This program should implement a console program that asks 3 inputs (a, b, and c) from users to compute the roots of equation ax^2 + bx + c = 0 Output format should match what is shown in the sample run in the Assignment 2 Handout. """ import math def main(): """ This function will compute the roots of equation: ax^2+bx+c=0. """ print('stanCode Quadratic Solver!') compute_the_roots_of_equation() def compute_the_roots_of_equation(): """ Use the three given numbers(a,b,and c), and discriminant(b^2-4ac) to get the roots of equation. discriminant>0, two roots. discriminant=0, one root. discriminant<0, no real roots. """ a = int(input('Enter a : ')) if a != 0: b = int(input('Enter b : ')) c = int(input('Enter c : ')) discriminant = b**2-4*a*c if discriminant > 0: y = math.sqrt(discriminant) x1 = (-b+y)/(2*a) x2 = (-b-y)/(2*a) print('Two roots: ' + str(x1) + ' , ' + str(x2)) elif discriminant == 0: x = -b/(2*a) print('One root: ' + str(x)) else: print('No real roots.') else: print("'a' can not be zero!") ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
9139e03d276b2d33323343e59a2bf01ad9600911
gibbs-shih/stanCode_Projects
/stanCode_Projects/Hangman Game/similarity.py
1,801
4.34375
4
""" Name: Gibbs File: similarity.py ---------------------------- This program compares short dna sequence, s2, with sub sequences of a long dna sequence, s1 The way of approaching this task is the same as what people are doing in the bio industry. """ def main(): """ This function is used to find the most similar part between s1(long DNA sequence) and s2(short DNA sequence). """ long = give_long() short = give_short() similarity1 = find_similarity(long, short) print('The best match is '+similarity1+'.') def give_long(): """ Users give a long DNA sequence to search. :return: long DNA sequence """ long = input('Please give me a DNA sequence to search: ') long = long.upper() return long def give_short(): """ Users give a short DNA sequence to match. :return: short DNA sequence """ short = input('What DNA sequence would you like to match? ') short = short.upper() return short def find_similarity(long, short): """ This function will find out the most similar part in long DNA sequence when compared to short DNA sequence. :param long: long DNA sequence :param short: short DNA sequence :return: the most similar part between long and short DNA sequence """ similarity1 = 0 similarity2 = 0 for i in range(len(long)-len(short)+1): a = 0 part = long[i:i+len(short)] for j in range(len(part)): if part[j] == short[j]: a += 1 if a == len(short): similarity1 = part return similarity1 elif a > similarity2: similarity2 = a similarity1 = part return similarity1 ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == '__main__': main()
true
0619ec96483920be456730016ece7f7ef5b3ed57
takisforgit/Projects-2017-2018
/hash-example1.py
2,939
4.1875
4
import hashlib print(hashlib.algorithms_available) print(hashlib.algorithms_guaranteed) ## MD5 example ## ''' It is important to note the "b" preceding the string literal, this converts the string to bytes, because the hashing function only takes a sequence of bytes as a parameter ''' hash_object = hashlib.md5(b"Hello World") print("MD5 :",hash_object.hexdigest()) ''' So, if you need to take some input from the console, and hash this input, do not forget to encode the string in a sequence of bytes ''' ##mystring = input('Enter String to hash: ') ### Assumes the default UTF-8 ##hash_object = hashlib.md5(mystring.encode()) ##print(hash_object.hexdigest()) ## SHA1 example ## hash_object = hashlib.sha1(b'Hello World') hex_dig = hash_object.hexdigest() print("SHA1 :",hex_dig) ## SHA224 example ## hash_object = hashlib.sha224(b'Hello World') hex_dig = hash_object.hexdigest() print("SHA224:",hex_dig) ## SHA256 example ## hash_object = hashlib.sha256(b'Hello World') hex_dig = hash_object.hexdigest() print("SHA256:",hex_dig) ## SHA384 example ## hash_object = hashlib.sha384(b'Hello World') hex_dig = hash_object.hexdigest() print("SHA384:",hex_dig) ## SHA512 example ## hash_object = hashlib.sha512(b'Hello World') hex_dig = hash_object.hexdigest() print("SHA512:",hex_dig) ## DSA example ## hash_object = hashlib.new('DSA') hash_object.update(b'Hello World') print("DSA :",hash_object.hexdigest()) ################################################### ''' In the following example we are hashing a password in order to store it in a database. In this example we are using a salt. A salt is a random sequence added to the password string before using the hash function. The salt is used in order to prevent dictionary attacks and rainbow tables attacks. However, if you are making real world applications and working with users' passwords, make sure to be updated about the latest vulnerabilities in this field. If you want to find out more about secure passwords please refer to this article https://crackstation.net/hashing-security.htm ''' import uuid import hashlib def hash_password(password): # uuid is used to generate a random number salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt def check_password(hashed_password, user_password): password, salt = hashed_password.split(':') return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest() new_pass = input('Please enter a password: ') hashed_password = hash_password(new_pass) print('The string to store in the db is: ' + hashed_password) old_pass = input('Now please enter the password again to check: ') if check_password(hashed_password, old_pass): print('You entered the right password') else: print('ATTENTION ! The password does not match')
true
d64e446e9730ed833bb0dfd669d3c6aba98e6653
Deepti3006/InterviewPractise
/Amazon Interview/OccuranceOfElementInArray.py
370
4.15625
4
def numberOfOccurancesOfNumberinArray(): n = int(input("Enter number of Elements")) arr =[] for i in range(n): elem = input("enter the array number") arr.append(elem) print(arr) find_element = input("Enter the element to be found") Occurances = arr.count(find_element) print(Occurances) numberOfOccurancesOfNumberinArray()
true
2eb7016701c2f1b1d6368a1ba08994e89930be57
Jenell-M-Hogg/Codility-Lesson-Solutions
/Lesson1-FrogJmp.py
1,296
4.125
4
'''A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the small frog must perform to reach its target. Write a function: def solution(X, Y, D) that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 Assume that: X, Y and D are integers within the range [1..1,000,000,000]; X ≤ Y. Complexity: expected worst-case time complexity is O(1); expected worst-case space complexity is O(1).''' #100% solution import math def solution(X, Y, D): #The distance the frog has to go distance=Y-X #Convert to float to avoid integer division df=float(distance) jumps=df/D #Round up the number of jumps jumps=math.ceil(jumps) #must return an integer toInt=int(jumps) return toInt pass
true
74b87ea175e4c7ef7ac9802e865783101a87097d
JennSosa-lpsr/class-samples
/4-2WritingFiles/writeList.py
405
4.125
4
# open a file for writing # r is for reading # r + is for reading and writing(existing file) # w is writing (be careful! starts writing from the beginning.) # a is append - is for writing *from the end* myFile = open("numlist.txt", "w") # creat a list to write to my file nums = range(1, 501) # write each item to the file for n in nums: myFile.write(str(n) + '\n' ) # close the file myFile.close()
true
715cfb565d350b68bf0d20367cedcde62562e66c
JennSosa-lpsr/class-samples
/remotecontrol.py
1,080
4.40625
4
import turtle from Tkinter import * # create the root Tkinter window and a Frame to go in it root = Tk() frame = Frame(root) # create our turtle shawn = turtle.Turtle() myTurtle = turtle.Turtle() def triangle(myTurtle): sidecount = 0 while sidecount < 3: myTurtle.forward(100) myTurtle.right(120) sidecount = sidecount + 1 # make some simple buttons fwd = Button(frame, text='fwd', command=lambda: shawn.forward(50)) left = Button(frame, text='left', command=lambda: shawn.left(90)) right = Button(frame, text='right', command=lambda: shawn.right(90)) penup = Button(frame, text='penup', command=lambda:shawn.penup()) pendown = Button(frame, text='pendown', command=lambda:shawn.pendown()) backward = Button(frame, text='backward', command=lambda:shawn.backward(50)) shape = Button(frame, text='shape', command=lambda:triangle.(shawn) # put it all together fwd.pack(side=LEFT) left.pack(side=LEFT) right.pack(side=LEFT) penup.pack(side=LEFT) pendown.pack(side=LEFT) backward.pack(side=LEFT) shape.pack(side=LEFT) frame.pack() turtle.exitonclick()
true
f623fbc9ad297294904cf231202e7e2ae1282524
AJoh96/BasicTrack_Alida_WS2021
/Week38/2.14_5.py
476
4.25
4
#solution from Lecture principal_amount = float(input("What is the principal amount?")) frequency = int(input("How many times per year is the interest compounded?")) interest_rate = float(input("What is the interest rate per year, as decimal?")) duration = int(input("For what number of years would like to calculate the compound interest?")) final_amount= principal_amount * (1 + (interest_rate/frequency))** (frequency*duration) print("The final amount is:", final_amount)
true
98d574a3e170f6bdf927c16d61e01eb9003c303b
andreyQq972/base_of_Python
/homework_1/task_2.py
525
4.125
4
time = int(input("Введите количество секунд и мы переведем их в формат чч:мм:сс: ")) time_hours = time // 3600 time_minutes = (time % 3600) // 60 time_seconds = ((time % 3600) % 60) # print(f"{time_hours}:{time_minutes}:{time_seconds}") if time < 360000: print ("%02i:%02i:%02i" % (time_hours, time_minutes, time_seconds)) else: print ("Для формата чч:мм:сс есть ограничение в 360 000 секунд. Попробуйте заново.")
false
92077bb80eda2fe5208c7b2eeeac3d53c4251ebc
PriyankaBangale/30Day-s_Code
/day_8_DictionaryMapping.py
1,381
4.34375
4
"""Objective Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video! Task Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. Note: Your phone book should be a Dictionary/Map/HashMap data structure.""" N = int(input()) d = dict{} for i in range(0, N): name, number = input().split() d[name] = number for i in range(0, N): name = input() if name in d: print("{}={}".format(name, d[name])) else: print("Not found") n=int(input().strip()) phone_book={} for i in range(n): x= input().strip() listx = list(x.split(' ')) phone_book[listx[0]] = listx[1] name=[] try: while True: inp = input().strip() if inp != "": name.append(inp) else: break except EOFError: pass for i in name: c=0 if i in phone_book: print(i+'='+phone_book[i]) else: print('Not found')
true
015cac95f4680a6fa0f62999caff7e8d500634b9
assuom7827/Hacktoberfest_DSA_2021
/Code/game_projects/word guessing game/word_guessing_game.py
1,088
4.28125
4
from random import choice # list of words(fruits and vegetables) words=["apple","banana","orange","kiwi","pine","melon","potato","carrot","tomato","chilly","pumpkin","brinjol","cucumber","olive","pea","corn","beet","cabbage","spinach"] c_word = choice(words) lives=3 unknown = ["_"]*len(c_word) while lives>0: guess=input("Please guess a letter or word: ") if guess == c_word: print('You won! The secret word was ' + c_word) break elif guess in c_word: unknown[c_word.index(guess)]=guess if "_" in unknown: print(unknown) print("Hurray!,you succeded in guessing a letter correct.go ahead!") print(f"chances left are {lives}") else: print(unknown) print("Congrats!\nyou won!") else: if lives==1: print(unknown) print("you are run out of lifes.\nBetter luck next time!") elif lives>0: print(unknown) print("you lost a life.try again!") print(f"chances left are {lives}") lives=lives-1
true
9c32992faf3335c9e0746ce48c6c25b1348e4dc3
assuom7827/Hacktoberfest_DSA_2021
/Code/matrix/matrix_multiplication/python.py
1,241
4.25
4
r1=int(input("Enter number of Rows of Matrix A: ")) c1=int(input("Enter number of Columns of Matrix A: ")) A=[[0 for i in range(c1)] for j in range(r1)] #initialize matrix A print("Enter Matrix Elements of A:") #input matrix A for i in range(r1): for j in range(c1): x=int(input()) A[i][j]=x r2=int(input("Enter number of Rows of Matrix B: ")) c2=int(input("Enter number of Columns of Matrix B: ")) B=[[0 for i in range(c2)] for j in range(r2)] #initialize matrix B print("Enter Matrix Elements of B:") #input matrix B for i in range(r2): for j in range(c2): x=int(input()) B[i][j]=x if(c1==r2): #if no. of columns of matrix A is equal to no. of rows of matrix B P=[[0 for i in range(c2)] for j in range(r1)] #initialize product matrix for i in range(len(A)): for j in range(c2): for k in range(len(B)): P[i][j]=P[i][j]+(A[i][k]*B[k][j]) #multiplication #print the product matrix print("Product of Matrices A and B: ") for i in range(r1): for j in range(c2): print(P[i][j],end=" ") print() else: #if no. of columns of matrix A isn't equal to no. of rows of matrix B print("Matrix Multiplication is not possible.")
false
fb278d9975471e74e188f621cc722444410ada76
Sarthak1503/Python-Assignments
/Assignment4.py
1,100
4.28125
4
#1.Find the length of tuple t=(2,4,6,9,1) print(len(t)) #2.Find the largest and smallest element of a tuple. t=(2,4,6,8,1) print(max(t)) print(min(t)) #3.Write a program to find the product os all elements of a tuple. def pro(t): r=1 for i in t: r=r*i return r t=(1,2,3,4) p=pro(t) print(p) #4.Calculate difference between two sets. s1=set([1,2,4,6,9]) s2=set([2,3,4,5,7]) print(s1-s2) #5.Print the result of intersection of two sets. s1=set([1,2,5]) s2=set([2,3,4]) print(s1 & s2) #6.Create a Dictionary to store names and marks of 10 students by user input. d={} for i in range(10): name=input('enter your name') marks=int(input('enter marks')) d[name]=marks print(d) #7.Sorting of Dictionary d={'a':60,'b':100,'c':80} print(d) value_list=list(d.values()) print(value_list) value_list.sort() print(value_list) #8.Count the number of occurence of each letter in word "MISSISSIPPI". Store count of every letter with the letter in a dictionary. l=list("MISSISSIPPI") d={} d['M']=l.count('M') d['I']=l.count('I') d['S']=l.count('S') d['P']=l.count('P') print(d)
true
9b7380e82a01b8a68bec953a32119f10b2f34ad1
Sarthak1503/Python-Assignments
/Assignment11.py
1,317
4.34375
4
import threading from threading import Thread import time #1. Create a threading process such that it sleeps for 5 seconds and # then prints out a message. def show(): time.sleep(5) print(threading.current_thread().getName(),"Electronics & Communication Engineering") t= Thread(target=show) t.setName("B.tech in:") t.start() print(threading.current_thread().getName()) #2. Make a thread that prints numbers from 1-10, waits for 1 sec between def number(): for x in range (1,11): print(threading.current_thread().getName(),":",x) time.sleep(1) t = Thread(target=number) t.setName("Number") t.start() # 3. Make a list that has 5 elements.Create a threading process that prints the 5 # elements of the list with a delay of multiple of 2 sec between each display. # Delay goes like 2sec-4sec-6sec-8sec-10sec l=[1,2,3,4,5] def delay(): n = 2 for x in l: if n%2==0: time.sleep(n) print(threading.current_thread().getName(), ":", x) n=n+2 t = Thread(target=delay) t.setName("Number") t.start() #4. Call factorial function using thread. def fact(): n=int(input("Enter the no")) f=1 while n>=1: f=f*n n=n-1 print(threading.current_thread().getName(),":",f) t= Thread(target=fact) t.setName("Factorial") t.start()
true
a1e326537c4cadefbae38f73356c33a3cb920f1c
ArnabC27/Hactoberfest2021
/rock-paper-scissor.py
1,678
4.125
4
''' Rock Paper Scissor Game in Python using Tkinter Code By : Arnab Chakraborty Github : https://github.com/ArnabC27 ''' import random import tkinter as tk stats = [] def getWinner(call): if random.random() <= (1/3): throw = 'Rock' elif (1/3) < random.random() <= (2/3): throw = 'Scissors' else: throw = 'Paper' if (throw == 'Rock' and call == 'Paper') or (throw == 'Paper' and call == 'Scissors') or (throw == 'Scissors' and call == 'Rock'): stats.append('W') result = "You Won!!!" elif throw == call: stats.append('D') result = "It Is A Draw!!!" else: stats.append('L') result = 'You Lost!!!' global output output.config(text = 'Computer Threw : ' + throw + '\n' + result) def sPass(): getWinner('Scissors') def rPass(): getWinner('Rock') def pPass(): getWinner('Paper') window = tk.Tk() scissors = tk.Button(window, text='Scissors', bg='#ff9999', padx=10, pady=5, command=sPass, width=20) rock = tk.Button(window, text='Rock', bg='#80ff80', padx=10, pady=5, command=rPass, width=20) paper = tk.Button(window, text='Paper', bg='#3399ff', padx=10, pady=5, command=rPass, width=20) output = tk.Label(window, width=20, fg='red', text="What's Your Call?") scissors.pack(side='left') rock.pack(side='left') paper.pack(side='left') output.pack(side='right') window.mainloop() for i in stats: print(i, end=' ') if stats.count('L') > stats.count('W'): result = 'You have Lost the series.' elif stats.count('L') == stats.count('W'): result = 'Series has ended in a Draw.' else: result = 'You have Won the series.' print('\n',result,'\n', end='')
true
c66911b7118dfe6ca6dde2d28c00b8eeaf0ace72
MacHu-GWU/pyclopedia-project
/pyclopedia/p01_beginner/p03_data_structure/p03_set/p01_constructor.py
1,219
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Set Constructor ============================================================================== """ import random import string def construct_a_set(): """Syntax: ``set(iterable)`` """ assert set([1, 2, 3]) == {1, 2, 3} assert set(range(3)) == {0, 1, 2} construct_a_set() def using_mutable_object_as_item_of_set(): """By default, only integer, string and other hashable immutable built-in object can be item of a set. Any user defined object are not behave correctly. You could define ``__hash__`` method to make sure your object is hashable. Usually returns a integer or a string. """ def random_text(): return "".join([random.choice(string.ascii_letters) for i in range(32)]) class Comment(object): def __init__(self, id, text): self.id = id self.text = text def __repr__(self): return "Comment(id=%r, text=%r)" % (self.id, self.text) def __hash__(self): return hash(self.id) l = [Comment(id=i, text=random_text()) for i in range(5)] s = set(l) for c in l: assert c in s using_mutable_object_as_item_of_set()
true
6c983ff6d1b91561c632b8f954aff02a09370b8b
MacHu-GWU/pyclopedia-project
/pyclopedia/p02_ref/p03_objective_oriented/p04_magic_method/p07__hash__.py
599
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ``__hash__(self)`` 定义了 hash(obj)的行为。 """ class MyClass(object): def __init__(self, a): self.a = a def __hash__(self): return hash(self.a) def __eq__(self, other): return self.a == other.a if __name__ == "__main__": m1 = MyClass("a") m2 = MyClass("a") s = set() s.add(m1) # set在添加一个元素时会判断是否定义了 __hash__ 方法, 以及有没有其他元素 # 与之相等。所以s.add(m2)不会将m2添加进去。 s.add(m2) assert len(s) == 1
false
7e37a1798223d3e1a75f8a329ca64b22ad088e6e
ichHowell/WHL_Python
/ex8.py
546
4.15625
4
formatter = "{} {} {} {}" #做好框,等待填进去,取代{} print(formatter.format(1,2,3,4)) #数值不用双引号 print(formatter.format("one","two","three","four")) #字符串需要双引号才能填进去 print(formatter.format(True,False,True,True)) #布尔字符页不需要双引号 print(formatter.format(formatter,formatter,formatter,formatter)) #我填我自己,12个{} print(formatter.format( "Try your", "Own text here", "Maybe a poem", "Or a song about fear" )) #和教材不一样,为什么这里输出显示不换行?
false
96290a7e696a0c6c70bcf234648877536d5c53e2
DiQuUCLA/python_59_skill
/3_python_bytes_str_unicode.py
1,180
4.1875
4
""" Two types that represent sequence of char: str and bytes(Python3), unicode and str(Python2) Python3: str: Unicode character bytes: 8 bits raw data Python2: unicode: Unicode character str: 8 bits raw data """ import sys version = sys.version_info[0] if version is 3: #encoding will take unicode str to bytes #where decoding will take bytes to unicode str def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value def to_bytes(bytes_or_str): if isinstance(bytes_or_str, str): value = bytes_or_str.encode('utf-8') else: value = bytes_or_str return value if version is 2: def to_str(str_or_unicode): if isinstance(bytes_or_str, unicode): value = bytes_or_str.encode('utf-8') else: value = bytes_or_str return value def to_unicode(bytes_or_str): if isinstance(bytes_or_str, str): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value
true
184b7da2b7085944213de2c86efe221bd29c8454
nekoTheShadow/my_answers_of_rosetta_code
/babbage_problem/main.py
862
4.125
4
""" Babbage problem: http://rosettacode.org/wiki/Babbage_problem 269,696で終わる自然数のうち、最小の平方数は何か? チャールズ・バベッジはこの問題の答えを9,947,269,696(=99,736^2)と予想した。 さてこの予想は正しいだろうか? 君の眼で確かめてみよう --というのが本問の趣旨。 === 端的に述べると、彼の予想は間違っている。答えは638269696=25264^2。 平方数判定はもう少しエレガントに書きたかった(´・ω・`) """ import math def is_square(x): sqrt = int(math.sqrt(x)) return x == sqrt * sqrt def main(): x = 269696 while not is_square(x): x += 1000000 print(x, math.sqrt(x)) #=> 638269696 25264.0 def test(): assert is_square(100) assert not is_square(99) if __name__ == '__main__': test() main()
false
9c30b847859dc19b8cdaa8c16f56f4e6d8651e89
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Análise de dados em uma tupla - 75.py
946
4.21875
4
#Exercício Python 075: Desenvolva um programa que leia quatro valores pelo teclado # guarde-os em uma tupla. No final, mostre: #A) Quantas vezes apareceu o valor 9. #B) Em que posição foi digitado o primeiro valor 3. #C) Quais foram os números pares. valores = (int(input("Primeiro valor: ")), int(input("Segundo valor: ")), int(input("Terceiro valor: ")), int(input("Quarto valor: "))) print("Valores digitados: {}".format(valores)) print("="*50) print(f"O número 9 apareceu {valores.count(9)} vezes") print("="*50) totpar = 0 if 3 in valores: print(f"o número 3 foi encontrado na {valores.index(3) + 1}º posição") else: print("O número 3 não foi digitado NENHUMA VEZ") print("="*50) print("O números pares digitados: ",end="") for cont in range(0,len(valores)): if valores[cont] % 2 == 0: print(valores[cont],end=" ") totpar +=1 print(f"\nTotal de pares foram: {totpar}")
false
b45e42273efc868dea8f4690154fa383bea5c1ab
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Melhorando a matriz - 87.py
1,399
4.15625
4
#Exercício Python 087: Aprimore o desafio anterior, mostrando no final: # A) A soma de todos os valores pares digitados. # B) A soma dos valores da terceira coluna. # C) O maior valor da segunda linha. matriz = [[0,0,0],[0,0,0],[0,0,0]] somapares = soma3coluna = maior2linha = 0 for linha in range(0,3): for coluna in range(0,3): matriz[linha][coluna] = int(input(f"Digite o valor [{linha},{coluna}]: ")) if matriz[linha][coluna] % 2 == 0: somapares += matriz[linha][coluna] if matriz[linha][2]: soma3coluna += matriz[linha][2] for cont in range(0,3): if cont == 0: maior2linha = matriz[1][cont] else: if matriz[1][cont] > maior2linha: maior2linha = matriz[1][cont] print("="*30) print("{:^30}".format("MATRIZ FORMADA")) print("="*30) for l in range(0,3): for c in range(0,3): print(f"[{matriz[l][c]:^5}]",end=" ") print() print("="*30) print("{:^30}".format("RESULTADOS")) print("="*30) print(f"Soma dos pares: {somapares}") print(f"Soma de todos da terceira coluna: {soma3coluna}") print(f"Maior da segunda coluna: {maior2linha}")
false
76d8f4bb927db5d23dec1970d05e0b86b51a130e
MatheusKlebson/Python-Course
/SECUNDO MUNDO - SECOND WORLD/Factorial - 60.py
462
4.21875
4
#Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. # Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120 from time import sleep from math import factorial num = int(input("Número: ")) cont = num f = factorial(num) print("Calculando factorial...") sleep(2) while cont > 0: print(" {} ".format(cont),end="") if cont > 1: print(" X ",end="") else: print(" = ",end="") cont -= 1 print(" {} ".format(f))
false
290e8ba810b59b20c4cd3a3ed33339649d3f011b
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Função de contador - 98.py
1,553
4.1875
4
''' Exercício Python 098: Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo. Seu programa tem que realizar três contagens através da função criada: a) de 1 até 10, de 1 em 1 b) de 10 até 0, de 2 em 2 c) uma contagem personalizada''' from time import sleep def mostraLinha(txt): print("="*30) print(txt) def contador(inicio,fim,passo): if passo == 0: print("Impossivel fazer 0 passo") if fim > 0 or fim > inicio: for c in range(inicio,fim + 1,passo): print(c,end=" ",flush=True) sleep(1) print("FIM") else: for c in range(inicio,fim - 1,passo): print(c,end=" ",flush=True) sleep(1) print("FIM") mostraLinha("CONTAGEM DE 1 A 10 DE 1 EM 1") contador(1,10,1) mostraLinha("CONTAGEM DE 10 A 0 DE 2 EM 2") contador(10,0,-2) print("="*30) print("Agora é sua vez de personalizar...") i = int(input("Inicio: ")) f = int(input("Fim: ")) p = int(input("Passo: ")) if i > f and p > 0: dobro = p dobro *= 2 p = p - dobro mostraLinha(f"CONTAGEM DE {i} A {f} DE {p + dobro} EM {p + dobro}") else: mostraLinha(f"CONTAGEM DE {i} A {f} DE {p} EM {p}") contador(i,f,p)
false
ae17752fa96c1a869fe80c2346f85508dbd48c01
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Organizando uma lista sem o sort() - 80.py
721
4.21875
4
#Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos #cadastre-os em uma lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela. numbers = [] for accountant in range(0,5): num = int(input(f"Write a number: ")) if accountant == 0 or num > numbers[-1]: numbers.append(num) print(f"The number placed in the last position in the list...") else: position = 0 while position < len(numbers): if num <= numbers[position]: numbers.insert(position,num) print(f"The number placed in the {position} position in the list...") break position += 1 print(f"List create: {numbers}")
false
072db63bb43c2d09bddf30bba01b8bb925a20ecc
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Analisando e gerando Dicionários - 105.py
1,950
4.21875
4
# Exercício Python 105: Faça um programa que tenha uma função notas() # que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: '''– Quantidade de notas – A maior nota – A menor nota – A média da turma – A situação (opcional)''' def notes(*num,situation=False): ''' FUNCTION FOR CALCULATING MANY NUMBERS: def(*num,situation=False) RECEIVES PARAMETERS (ACCEPT MANY NUMBERS) *n = numbers (OPTIONAL PARAMETER) situation = medium situation RETURN DICTIONARY ''' dictionary = dict() dictionary["NOTES_TOTAL"] = len(num) dictionary["MAXIMUM_NOTE"] = max(num) dictionary["MINIMUM_NOTE"] = min(num) dictionary["CLASS_AVERAGE"] = sum(num)/len(num) if situation == True: if dictionary["CLASS_AVERAGE"] >= 7 and dictionary["CLASS_AVERAGE"] <= 10: dictionary["SITUATION"] = "Very Good" elif dictionary["CLASS_AVERAGE"] >= 5 and dictionary["CLASS_AVERAGE"] < 7: dictionary["SITUATIOM"] = "Reasonable" elif dictionary["CLASS_AVERAGE"] >= 0 and dictionary["CLASS_AVERAGE"] < 5: dictionary["SITUATIOM"] = "Very Bad" else: dictionary["SITUATIOM"] = "Medium Invalid" return dictionary response = notes(10,10,10,10,situation=True) print(response)
false
05f0de12aa2a42cf35c87f7fff3b5f9306ad0ec6
MatheusKlebson/Python-Course
/TERCEIRO MUNDO - THIRD WORLD/Lista de preços com tupla - 76.py
645
4.15625
4
#Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos # seus respectivos preços, na sequência. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. produtos = ("COMPUTADOR",1220, "TABLET",355, "CELULAR",420, "GELADEIRA",380, "FONE DE OUVIDO",40, "CAIXA DE SOM",50) print("="*50) print("{:^50}".format("PRODUTOS E PREÇOS")) print("="*50) for tabela in range(0,len(produtos)): if tabela % 2 == 0: print(f"{produtos[tabela]:.<40}",end="") else: print(f"R${produtos[tabela]:>8.2f}") print("="*50)
false
8480108953305c02872b0655c56ff18c44afca8d
MatheusKlebson/Python-Course
/PRIMEIRO MUNDO - FIRST WORLD/Analisador de textos - 22.py
603
4.25
4
#Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre: #- O nome com todas as letras maiúsculas e minúsculas. #- Quantas letras ao total (sem considerar espaços). #- Quantas letras tem o primeiro nome from time import sleep nome = str(input("Nome completo: ")).strip() n = nome.split() print("Analisando nome...") sleep(2) print("Nome só com letras maiúsculas:",nome.upper()) print("Nome só com letras minúsculas:",nome.lower()) print("Ao todo tem",len(nome) - nome.count(" "),"Letras") print("O primeiro nome é",n[0],"E possui apenas",nome.find(" "),"Letras")
false
e5d3d5fcc86b340efb23b0cf99b4652daa6e3e4d
juanjosua/codewars
/find_the_odd_int.py
599
4.1875
4
""" Find the Odd Int LINK: https://www.codewars.com/kata/54da5a58ea159efa38000836/train/python Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times. """ def find_it(seq): numbers = set(seq) return[n for n in numbers if seq.count(n) % 2 ==1][0] # voted best practice 1 def find_it(seq): return [x for x in seq if seq.count(x) % 2][0] # voted best practice 2 def find_it(seq): for i in seq: if seq.count(i)%2!=0: return i # test code find_it([10]) #10 find_it([1,1,1,2,2]) #1
true
9555bd3ece66087b254256195488cdb03fe87f8d
kyletgithub/notes-or-something
/twod_lists.py
701
4.15625
4
a = [[1,2,3], [4,5,6]] ## one way to traverse a 2d list #for i in range(len(a)): # for j in range(len(a[i])): # print(a[i][j],end=' ') # print() ##another way #def print_2dlist(lst): #for row in a: # for element in lst: # print(element,end=' ') # print() #add all elements #sum = 0 #for i in range(len(a)): # for j in range(len(a[i])): # sum += a[i][j] #print(sum) #sum = 0 #for row in a: # for element in row: # sum += element #print(sum) #for i in range(len(a)): # for j in range(len(a[i])): # a[i][j] += 1 #print(a) #x = [[0] * 5]*8 DOES NOT WORK!!!! m = 5 n = 8 x = [[0]*n for i in range(m)] x[0][0] = 100 print(x)
false
6115fe58abcf4cedf25d90d87613590919ec494a
lisamryl/oo-melons
/melons.py
2,057
4.15625
4
"""Classes for melon orders.""" import random import datetime class AbstractMelonOrder(object): """Abstract for both domestic and international melon orders.""" def __init__(self, species, qty): """Initialize melon order attributes.""" self.species = species self.qty = qty self.shipped = False def get_base_price(self): """randomly get a base price between 5 and 9 and return it.""" # in progress # day = datetime.date.weekday() # print day # time = datetime.time() # print time base_price = random.randint(5, 9) return base_price def get_total(self): """Calculate price, including tax.""" base_price = self.get_base_price() if self.species == "Christmas": base_price *= 1.5 total = (1 + self.tax) * self.qty * base_price return total def mark_shipped(self): """Record the fact than an order has been shipped.""" self.shipped = True class DomesticMelonOrder(AbstractMelonOrder): """A melon order within the USA.""" tax = 0.08 order_type = "domestic" class InternationalMelonOrder(AbstractMelonOrder): """An international (non-US) melon order.""" tax = 0.17 order_type = "international" def __init__(self, species, qty, country_code): """Initialize melon order attributes.""" self.country_code = country_code return super(InternationalMelonOrder, self).__init__(species, qty) def get_country_code(self): """Return the country code.""" return self.country_code def get_total(self): total = super(InternationalMelonOrder, self).get_total() if self.qty < 10: total += 3 return total class GovernmentMelonOrder(AbstractMelonOrder): """Special orders from the Government.""" tax = 0 passed_inspection = False def mark_inspection(self, passed): """Updates inspection status.""" self.passed_inspection = passed
true
96a58d71f67b01d07897d83fca08c3beb5c718cd
loudsoda/CalebDemos
/Multiples_3_5/Multiples_3_5.py
1,228
4.125
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Note: If the number is a multiple of both 3 and 5, only count it once. Courtesy of ProjectEuler.net https://www.codewars.com/kata/514b92a657cdc65150000006/train/python Solution by Caleb Ellis Date: 5/27/2020 ''' def solution(number): # Create range for loop, mak it so the loop does not exceed x # number is simplified to x for the sake of irs x = number y = range(1, int(x)) # Create list to find sum number_list = [] # Loop though all iterations of the input number for i in y: multi_5 = i * 5 multi_3 = i * 3 # Check if digits exist in list or if digit is greater than x if multi_3 >= x or multi_3 in number_list: pass else: number_list.append(multi_3) if multi_5 >= x or multi_5 in number_list: pass else: number_list.append(multi_5) # Add contents of list together Sum = sum(number_list) return (Sum) print(solution(200))
true
ee7195c77b6de0b24df33b938058b4a2f45ec48e
sunnysunita/BinaryTree
/take_levelwise_input.py
1,353
4.25
4
from queue import Queue class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None def print_binary_tree(root): if root is None: return else: print(root.data, end=":") if root.left != None: print("L", root.left.data, end=", ") if root.right != None: print("R", root.right.data, end="") print() print_binary_tree(root.left) print_binary_tree(root.right) def take_level_input(): root_data = int(input("enter the root value: ")) if root_data is -1: return None root = BinaryTree(root_data) q = Queue() q.put(root) while q.empty() is False: curr = q.get() left_data = int(input("enter the left child of "+str(curr.data)+":")) if left_data is not -1: left_child = BinaryTree(left_data) curr.left = left_child q.put(left_child) right_data = int(input("enter the right child of "+str(curr.data)+":")) if right_data is not -1: right_child = BinaryTree(right_data) curr.right = right_child q.put(right_child) return root root = take_level_input() print_binary_tree(root) # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
true
c368badfeda0bd1f7079c807eb072dbbb6938641
weinbrek8115/CTI110
/P4HW2_RunningTotal_WeinbrennerKarla.py
628
4.15625
4
#CTI-110 #P4HW2 #Karla Weinbrenner #22 March 2018 #Write a program that asks the user to enter a series of numbers #It should loop, adding these numbers to a running total #Until a negative number is entered, the program should exit the loop #Print the total before exiting #accumulator variable runningTotal=0 count=0 userInput=int(input("Enter a number or negative number to exit: ")) print () while userInput >=0: runningTotal=runningTotal+userInput count=count+1 userInput=int(input("Enter a number or a negative number to exit: ")) print() print ("The running total is: ", runningTotal)
true
0f2ce0d0219274578f21b0e9ef8a5ddf99809d83
GuidoTorres/codigo8
/Seman4/Dia4-python/03-funcion-new.py
1,011
4.28125
4
#Metodos magicos class Empleado: def __new__(cls): print("El metodo magico_new_ ha sido invocado") instancia = object.__new__(cls) print(instancia) return instancia def __init__(self): print("El metodo magico __init__ ha sido invocado") def __str__(self): """Metodo magico que podemos subreescribir(Overridw) parar devovler lo que nosostro deseamos""" return "Yo soy la nueva definicion de la clase" empleado1 = Empleado() print(type(Empleado)) #Parar ver en que posicion de la memoria esta nuestro objeto print(id(empleado1)) print(empleado1) class Punto: def __init__(self, x= 0, y = 0): self.x = x self.y = y def __add__(self, otro): """MEtodo magico que sirve para incrementar el mismo objeto con otro""" x = self.x + otro.x y = self.y + otro.y return x,y punto1 = Punto(4,8) punto2 = Punto(-2,2) punto3 = punto1+ punto2 print(punto3)
false
d84cadab27615c30f1d12d7e9dff4237c97b5780
GuidoTorres/codigo8
/Seman4/Dia2-Python/ejer.py
1,437
4.1875
4
class Coordenadas(): def __init__(self, coordenadaX , coordenadaY): self.coordenadaX = coordenadaX self.coordenadaY = coordenadaY def valores(self): print("Los valores ingresados fueron:","(" , self.coordenadaX,",", self.coordenadaY ,")") def cuadrante(self): if(self.coordenadaX > 0 and self.coordenadaY>0 ): print("Pertenece al primer cuadrante") elif(self.coordenadaX <0 and self.coordenadaY >0 ): print("Pertenece al segundo cuadrante") elif (self.coordenadaX <0 and self.coordenadaY< 0): print("Pertence al tercer cuadrante") elif(self.coordenadaX>0 and self.coordenadaY<0): print("Pertenece al cuarto cuadrante") def vector_resultante(self): otroX= int(input("Ingrese nueva coordenada X: ")) otroY= int(input("Ingrese nueva coordenada Y: ")) self.VRX = otroX - self.coordenadaX self.VRY = otroY -self.coordenadaY print("El vector resultante es:","(" , self.VRX,",", self.VRY ,")") def distancia(self): d = ((self.VRX)**2 + (self.VRY)**2)**0.5 print("La distancia entre sus puntos es: ", d) def __resultante(self): coor.vector_resultante() coor = Coordenadas(coordenadaX = -2, coordenadaY=3) coor.valores() coor.cuadrante() coor.vector_resultante() coor.distancia()
false
8b89727db39b09e46e6378ea6718001951cc9f78
GuidoTorres/codigo8
/Seman4/Dia1/06-esxcepciones.py
969
4.15625
4
# excepciones => try ... except ... else ... finally # try: # #Todo lo que va a suceder dentro del try y si hay un error # #no va incidir con el funcionamiento de nuestro programa # n1 = int(input("Ingrese numero 1: ")) # n2 = int(input("Ingrese numero 2: ")) # division = n1 / n2 # print(division) # except ZeroDivisionError: # print("No puedes dividir entre 0 ") # except: # print(EnvironmentError)#Para ver el error que se tiene # print("Hubo un error al ingresar datos") # else: # print("La division funciono bien") # finally: # print("No importa si funciono la division o no") exito = 0 while (exito ==0): try: n1 = int(input("Ingrese numero 1: ")) n2 = int(input("Ingrese numero 2: ")) multiplicacion = n1 * n2 print(multiplicacion) exito = 1 except: print("No puede ingresar caracteres, vuelve a intentarlo") exito = 0
false
9af3ae57b8654e1d3ab98bbbb4df26e0b8aa4dd5
zubun/DZ_3
/hw3_3.py
636
4.125
4
def my_func (arg_1, arg_2, arg_3): '''adding two maximum numbers - сложение двух максимальных чисел''' list_1 = [arg_1, arg_2, arg_3] number_1 = max(list_1) list_1.pop(list_1.index(max(list_1))) number_2 = max(list_1) summ = number_1 + number_2 return summ arg_1 = float(input("Введите первое число:" )) arg_2 = float(input("Введите второе число:" )) arg_3 = float(input("Введите третье число:" )) result = my_func(arg_1, arg_2, arg_3) print(f"Сумма двух максимальных чисел равна: {result}")
false