blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8fddd760595d9044ec3295d25821015c49f12ad4 | NineOnez/Python_Language | /14_Maximum.py | 1,477 | 4.34375 | 4 | # max or min:
findValue = input("What Do you to find (max or min)? : ")
# input 3 Numbers for find max or equal
a = float(input("Enter your number1 :"))
b = float(input("Enter your number2 :"))
c = float(input("Enter your number3 :"))
print()
if findValue == "max":
# algorithm max Value
if a > b:
if a > c:
print(": A is max")
elif a == c:
print(": AC are max")
else:
print(": C is max")
elif a > c:
if b > a:
print(": B is max")
elif a == b:
print(": AB are max")
else:
print(": A is max")
elif b == c:
if b == a:
print(": ABC are equal")
else:
print(": BC are max")
elif a < c:
if c > b:
print(": C is max")
else:
print(" B is max")
if findValue == "min":
# algorithm for min value
if a < b:
if a < c:
print(": A is min")
elif a == c:
print(": AC are min")
else:
print(": C is min")
elif a < c:
if b < a:
print(": B is min")
elif a == b:
print(": AB are min")
else:
print(": A is min")
elif b == c:
if b == a:
print(": ABC are equal")
else:
print(": BC are min")
elif a > c:
if c < b:
print(": C is min")
else:
print(": B is min")
| false |
042a3d280453ed2110a9e5abeb4c03fe0b5f344a | tsclay/algos | /python/misc_problems/reverse_phrase.py | 968 | 4.25 | 4 | """
Reverse a phrase
- Take a string as input and ouput the reverse of it as a phrase
- Example: 'I have a dog' -> 'dog a have I'
- Note that spaces are included in the reversing
- Keep punctuation marks next to the words they immediately follow
Example: 'Zoinks! This place is scary, man!' -> 'man! scary, is place This Zoinks!'
"""
import re
def reverse_phrase(string: str) -> str:
parser = re.compile('[\w,!?¡¿\'\"\.]+|\s+')
string_list = parser.findall(string)
string_list.reverse()
return ''.join(string_list)
print(reverse_phrase('I have a dog.'))
# dog. a have I
print(reverse_phrase('I have a dog\'s tail.'))
# tail. dog's a have I
print(reverse_phrase('¡Tengo un pero!'))
# pero! un ¡Tengo
print(reverse_phrase('¿Dónde está el baño?'))
# baño? el está ¿Dónde
print(reverse_phrase('Zoinks! This place is scary, man!'))
# man! scary, is place This Zoinks!
print(reverse_phrase('A bcd def!a .asb!!'))
# .asb!! def!a bcd A
| true |
409204682da73dc27c86f52a025900aef5f2996f | sudikshyakoju/sudikshya | /program_class/recursive.py | 482 | 4.125 | 4 | '''def factorial(num):
print('factorial call with num' +str(num))
if num<0:
return 'number cannot be negative'
elif num==1 or num==0:
return 1
else:
result=num*factorial(num-1)
print('intermediate result for:num','*factorial(',num,'):',result)
return result
print(factorial(5))'''
'''l=[2,4,6,8]
def suml(l):
if len(l)==0:
return 0
else:
return l[0]+suml(l[1:])
print(sum(l))'''
for i in range(n):
| true |
50764fa979d81f7e9e913963f04b8d2f56d38f2e | sudikshyakoju/sudikshya | /pythonlab/bmi.py | 360 | 4.3125 | 4 | '''solve each of the following problems using python scripts. Make sure you use appropriate variable
names and comments. When there is a final answer have python print it to the screen. A person's body mass
index (BMI) is defined as:(mass/height**2)'''
mass=float(input('enter body mass:'))
height=float(input('enter height:'))
BMI=mass/(height**2)
print(BMI) | true |
320fb1e60fb77848434791071049fde133c2e47f | Paletimeena/Prac_data | /Monthly Test/Dec/Meena_Paleti_VT847.py | 608 | 4.125 | 4 | #!/usr/bin/pyhton
import math
from collections import Counter
num=input("enter the input : \n")
digit=1
flag=1
while(flag):
def get_fact(digit):
fact= math.factorial(digit)
print fact
return fact
def get_Trailing_Zeros(fact):
num_lst=list(str(fact))
for i in range(0,len(num_lst)+1):
new_lst=num_lst[i:num]
print new_lst
zeros=new_lst.count('0')
print "Zeros ",zeros
return zeros
fact=get_fact(digit)
num_zeros=get_Trailing_Zeros(fact)
if(num_zeros == num):
print "{}!={}".format(digit,fact)
flag=0
break;
else:
print "{}!".format(digit)
digit = digit + 1
| true |
4f499f6cfc9ba98e5b5352f385c0e8d7d7caee6c | dogan1612/Learning_Python | /Dersler/Day01/Membership_Operators.py | 377 | 4.25 | 4 | # IN : returns true if a value found
# NOT IN : returns true if a value not found
fruits = ["grapes", "berries"]
my_fruits = ["grapes", "berries"]
fav_fruits = fruits
print("berries" in fruits) # TRUE
print("apples" not in fruits) # TRUE
print(fav_fruits in fruits) # False
print(my_fruits in fruits) # False
print (fav_fruits is fruits) # True | true |
2f84f4a549386d2d6b9b34f0238ea36c55e7ec37 | dogan1612/Learning_Python | /Dersler/Day02/Boolean_Intro.py | 1,359 | 4.375 | 4 | #bool ya da boolean veri tipleri True ya da False alabilir.
print(4 < 5) # True
print(4 == 5) # False
print(4 != 5) # True
print(4 <= 5) # True
b = 3 > 5
print(type(b)) # <class 'bool'>
print(b) # false
string_false = "false"
print(type(string_false))
print(string_false)
print("-------------------------")
str1 = "a"
str2 = "a"
print(str1 == str2) # true
# logical operators: and, or, not
# True and True -> True
# True and False -> False
# False and False -> False
# True or True -> True
# True or False -> True
# False or False -> False
print(((5 == 5) or (4==6)) or (4<1)) # true
print(not (4 == 4)) # false
print(8 > 5 or 8 == 5) # true
print("-------------------------")
if (5 < 7 and (8 != 8)):
print("Bu satır yazılmaz")
print("Bu satır da yazılmaz")
print("Bu satır yazılır")
print("-------------------------")
if (5 < 7 and (8 == 8)):
print("Bu satır da yazılır")
pass
print("Bu satır yazılmaz")
print("-------------------------")
deger1 = "hayat"
deger2 = "güzeldir"
if (5 < 6 or (3==3) and ((4==4) or (5 != 3))):
print("İlk ifademiz doğru mu?")
if (deger1 == deger2):
print("Hayat güzeldir..")
else:
print("Hayat güzel değil mi?")
else:
print("Maalesef")
# print("Burası hep yazdırılır! Hayat devam eder gider..") xxx
| false |
ad25748eb964feb60788aa89ed8b6b3ebf8e1ea5 | hardy-pham/Design-Patterns | /decorator.py | 417 | 4.4375 | 4 | """
Implementation example of decorator design pattern in Python
"""
def math_wrapper(func):
def wrapper(x, y):
print func(x, y) + 1
return wrapper
# this is equivalent to add = math_wrapper(add(x, y))
@math_wrapper
def add(x, y):
return x + y
@math_wrapper
def multiply(x, y):
return x * y
add(1, 1) # should output 3 instead of 2
multiply(2, 2) # should output 5 instead of 4
| true |
15de83b40a2c092a447943bc0933ce7285910ef5 | rmpsc/DSA-Labs | /Lab 2/functions.py | 2,096 | 4.34375 | 4 | import math
# returns absolute value of a square rooted number w/o the sqrt function
def square_root():
# set a lower bound and higher bound to keep track of which integers the sqrt must be between
num = abs(int(input("Enter a number and I'll find the sqrt of it! ")))
lower_bound = 0
higher_bound = num
half = math.ceil((lower_bound + higher_bound) / 2)
if half == num | half == 1:
return num
while half != num:
if half**2 == num:
return half
elif (half - 1)**2 < num < half**2:
return half
elif half**2 > num:
higher_bound = half
# used math.ceil to avoid a float being returned
half = math.ceil((lower_bound + higher_bound) / 2)
elif half**2 < num:
lower_bound = half
half = math.ceil((lower_bound + higher_bound) / 2)
# takes arr and finds smallest missing number
def smallest_num(arr):
n = len(arr)
# makes sure m is larger than n
m = int(input("Enter a value for m "))
while m <= n:
m = int(input("Value must be greater than size of array! "))
left = 0
right = n - 1
# if first and last index match their value, there is no missing number
if (left == arr[left]) and (right == arr[right]):
return n
# checks to see if middle value matches its index
# if it does, remove value from right side
# if it doesn't, remove value from left side
while left <= right:
# mid = half of arr size
mid = int((left + right) / 2)
print("mid is " + str(mid) + "\n")
# first check if middle value is missing value
# will always reach this return if first if statement is not true
if (mid != arr[mid]) and (mid - 1 == arr[mid - 1]):
return "missing is " + str(mid)
# only keeps array up to mid value
elif mid != arr[mid]:
right = mid - 1
# only keeps mid value and after
else:
left = mid + 1
return 0
| true |
d74b8d0072695e857afe092e35ac3e4d1cb17470 | pranayknight/WorkedExamples | /FunAndImp/Tuples.py | 401 | 4.4375 | 4 | our_tuple1 = 1,2,3,"A","B","C"
print(type(our_tuple1))
our_tuple = (1,2,3,"A","B","C")
print(our_tuple[0:3])
# Tuples are not mutable after they are defined same as strings
# ex:- our_tuple[2] = 100 will throw an error
# converting other pieces of data into tuple
A = [1,2,3]
B = tuple(A)
# we can define multiple variable in one shot
(A,B,C) = 1,2,3
[d,e,f] = 4,5,6 #kewl
g,h,i = 7,8,9
| true |
affb2b28025275dbcd3b3473c88657d33195ac51 | pranayknight/WorkedExamples | /TopicsInBasicPython/functions/localandglobal.py | 665 | 4.34375 | 4 | x=123
def display():
y=678 #since it is defined inside the function it can be used within the function only and is local
print(x) #since x is defined before and outside the function it is global and can be used anywhere
print(y)
print(x)
#now lets see this example and try to analyse what's been done
def disp():
x=897
print(x)
print(globals()['x']) #this is the syntax to access global variable with same name as in function
print(x)
disp()
z=disp #here we can also assign a function to another function
z() #we can invoke the new function that is defined with old function and invoke the same eventually
| true |
b0f9b47e88eaf9bf880f1b08a8c7632a6aca8754 | pranayknight/WorkedExamples | /TopicsInBasicPython/inheritance/BMW1.py | 1,529 | 4.3125 | 4 | # Here we will also inherit the functionality from parent class
class BMW:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def stop(self):
print("Stopping the car")
def start(self): # defining methods in parent class to use in child class
print("Starting the car")
class ThreeSeries(BMW):
def __init__(self, cruiseControlEnabled, make, model, year):
BMW.__init__(self, make, model, year)
self.cruiseControlEnabled = cruiseControlEnabled
def display(self): #this display method is only available in this child class not in parent class nor in FiveSeries
print(self.cruiseControlEnabled)
def start(self): #we are overriding or shadowing the method in sub class to have diff functinality
print("Button Start")
class FiveSeries(BMW):
def __init__(self, parkingAssistEnabled, make, model, year):
BMW.__init__(self, make, model, year)
self.parkingAssistEnabled = parkingAssistEnabled
threeSeries=ThreeSeries(True, "BMW", "328i", 2018)
print(threeSeries.cruiseControlEnabled, threeSeries.make, threeSeries.model, threeSeries.year)
threeSeries.start()
threeSeries.stop()
threeSeries.display()
fiveSeries = FiveSeries(True, "BMW", "8i", 2019)
print(fiveSeries.parkingAssistEnabled, fiveSeries.make, fiveSeries.model, fiveSeries.year)
fiveSeries.start()
fiveSeries.stop() | true |
35325489b4507193e75ff906f86aec82ace94bf6 | edolfo/exercises | /crackingTheCodingInterview/dataStructures/uniqueChars.py | 1,165 | 4.21875 | 4 | #!/usr/bin/env python3
# Implement an algorithm to determine if a string has all unique characters.
# What if you can not use additional data structures?
def hasUnique(candidate: str):
"""
Memory use is <= sizeof(candidate), but runtime is O(n)
"""
found = []
for char in candidate:
if char in found:
return False
else:
found.append(char)
return True
def hasUniqueRestriction(candidate: str):
"""
O(n**2) runtime, but uses no additional memory beyond two indices
"""
for i in range(len(candidate)):
for j in range(len(candidate)):
if i == j:
continue
if candidate[i] == candidate[j]:
return False
return True
def main():
testWords = [
"abcdefghijklmnopqrstuvwxyz 1234567890",
"one tw r ;'789",
"helLo",
"hello"
]
for word in testWords:
try:
assert(hasUnique(word) == hasUniqueRestriction(word))
except AssertionError:
print("Results disagree for ", word)
print("Tests passed")
if __name__ == "__main__":
main()
| true |
5f60943a9988be30d9fad34766a1646e9212a607 | Upsurge-11/Python_Programming_Journey | /18_sets.py | 1,172 | 4.3125 | 4 | utensils = {"Spoon", "Fork", "Knife", "Knife", "Knife"}
utensils.add("napkin") # Adds the element in the set.
utensils.add("Kadhai")
utensils.remove("napkin") # Removes the element from the set.
for x in utensils:
print(x)
utensils.clear() # Removes all the element from the set.
for x in utensils:
print(x)
dishes = {"Bowl", "Plate", "Cup"}
utensils.update(dishes) # Adds multiple(all) elements in the set from another set.
print()
for i in utensils:
print(i)
dinner_table = utensils.union(dishes) # dinner_table = utensils + dishes
print()
for i in dinner_table:
print(i)
print()
z = {7, 8, 4, 3, 2, 69}
y = {3, 5 , 6, 2 , 402, 3, 7}
print(z.difference(y)) # Returns those elements which are not present in y but present in z.
print(y.difference(z)) # Returns those elements which are not present in z but present in y.
print(z.intersection(y)) # Returns those elements which are common between y and z.
print(y.intersection(z))
# Sets are unindexed thus printing it's elements gives different results varying in order everytime.
# No duplicates are allowed in sets. Duplicate elements are ignored. | true |
b34f8d434e6e4c75822fe3b70674e17794bec921 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/Drish-xD/Day-2/Question-1.py | 727 | 4.3125 | 4 | # Program to check the Number is Emirp Number or Not :)
n = int(input("Enter a Number : ")) # input the number u want to check
def prime(num): # Function to check the prime number
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
else:
return True
else:
return False
def emirp(num): # Function to check the number is emirp or not
if not prime(num):
return False
rev = 0
while num != 0:
a = num % 10
rev = rev * 10 + a # Reversing the number
num = int(num / 10)
return prime(rev)
if emirp(n):
print(n, "is a emirp number.")
else:
print(n, "is not a emirp number.")
| true |
8fa06a132399147aaac55d0c8530fd14a8340595 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day23/question1.py | 673 | 4.1875 | 4 | """ To reverse the string by considering each word of the string,
str as a single unit using stack
"""
def reverse_string(string):
stack_in = []
temp = ""
for i in range(0, len(string)):
if string[i] == " ":
stack_in.append(temp)
temp = ""
else:
temp += string[i]
stack_in.append(temp)
stack_out = []
for i in range(0, len(stack_in)):
stack_out.append(stack_in.pop())
out_string = ""
for el in stack_out:
out_string += el
out_string += " "
return out_string
if __name__ == "__main__":
string = "This is a string"
print(reverse_string(string)) | true |
72233e0978abfb08a414b261a0dcbb1bc31f3e03 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/Erif-0/Day 2/Question 2.py | 275 | 4.125 | 4 | x= int(input("Enter the Value to Check weather Its an Disarium Number or not: "))
num=x
temp=0
while x!=0:
k=num%10
temp+=k**len(str(num))
num//=10
if(temp==x):
print(x, 'is a Disarium Number')
else:
print(x,'is not Disarium Number') | true |
56cff3731459a19b12d82a128cbfe7eb02deee8f | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day13/question2.py | 439 | 4.28125 | 4 | """ to check if an array is a palindrom, without using recursion. """
def check_palindrome(array):
reversed_array = array[::-1]
if array == reversed_array:
return True
else:
return False
if __name__ == "__main__":
""" input_array = [1, 2, 3, 4, 5, 7] """
input_array = [3, 6, 0, 6, 3]
if check_palindrome(input_array):
print("PALINDROME : YES")
else:
print("PALINDROME : NO") | true |
985dbf34c5d239a8e1358a39ba041f87dfaf194b | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day3/question1.py | 670 | 4.28125 | 4 | ##To print the sum of the following series
## 1 + 12 + 123 + 1234 + ... + n
def series_generator(n):
end_point = n
series = [1]
for i in range(1, end_point):
next_in_series = (series[i - 1] * 10) + (i + 1)
series.append(next_in_series)
return series_sum_calculator(series)
def series_sum_calculator(series):
sum_of_series = 0
for element in series:
sum_of_series = sum_of_series + element
return sum_of_series
if __name__ == "__main__":
#print(series_generator(13))
number = int(input("Enter a number upto which you want to see the sum of the series : "))
print(series_generator(number))
| true |
9ec5437c6a04b81a95870fa7b04ce8bcdb48c4b2 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/Drish-xD/Day-4/Question-1.py | 573 | 4.46875 | 4 | # Program to print the prime factorization of a number :)
import math
n = int(input("Enter the number : ")) # Enter number for factorization
factor = [] # creating empty list to store factors
while n % 2 == 0:
factor.append(2) # Adding number of 2's in the factors
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
factor.append(i) # for Adding other factors in the list
n = n / i
if n > 2:
factor.append(int(n))
# printing the final list of factors in ascending order
print(sorted(factor))
| true |
03e4180721ea424d26738b45ed0a303e4db3d772 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day19/question2.py | 553 | 4.28125 | 4 | """
To find count of triplets with the sum smaller than the given sum value X
"""
def find_triplets_sums_smaller_than_X(array, X):
array.sort()
count = 0
for i in range(0, len(array) - 2):
j = i + 1
k = len(array) - 1
while j < k:
if array[i] + array[j] + array[k] >= X:
k -= 1
else:
count += k - j
j += 1
return count
if __name__ == "__main__":
arr = [-2, 0, 1, 3]
x = 2
print(find_triplets_sums_smaller_than_X(arr, x))
| false |
8afa2351afec30f516a710b054fb5b95776238fa | JamesTeachingAccount/PythonDemos | /selectiondemo.py | 1,976 | 4.46875 | 4 | import random
#I am an example of selection")
#The program will choose which statements to execute based on conditions
#A simple 'if' statement will do an instruction if a condition is met
firstRan = random.randint(1,10)
if (firstRan==10): #notice the colon at the end of this line and the indentation (one tab or four space, use the same each time) at the start of the next
print("I just picked a random number. You'll only see this line if it was a ten. If it wasn't, this line doesn't appear")
#Adding an 'else' clause tot he 'if' statement will allow us to one thing if the condition is met and a different thing if it isn't
secondRan = random.randint(1,10)
if (secondRan>5):
print("I picked another random number. You'l only see this message if it's above 5")
else: #again, colon, indentation. Else doesn't need a condition though - it's condition is basically "the first one isn't met
print("I picked another random number. You'l only see this message if it's 5 or below")
#If we have many options, we can add 'elif' blocks. These function the same as if blocks")
thirdRan=random.randint(1,10)
if (thirdRan==1):
print("I picked yet another number. You'll see this line if it was one")
elif (thirdRan==2):#colon, indentation
print("I picked yet another number. You'll see this line if it was two")
else:
print("I picked yet another number. You'll see this line if it neither one nor two")
#the line below is too long for my screen so I've split it into two. Each individual part is surrounded by "s but there's only one set of brackets
print("We can also have multiple lines inside an 'if', 'elif' or 'else'. This line is in the else block so "#why is there a space after so?
"will only appear if the number was neither one nor two, like the one above")
#So the order of instructions remains the same, like in sequence, but the computer makes a decision as to which line to use")
| true |
c4eb40de64ec8b82fc61a92714362951678c39fa | AndresDGuevara/platzi_intermedio | /excepciones.py | 670 | 4.125 | 4 | def palindrome(string): # Utilizando raise
try:
if len(string) == 0:
raise ValueError("No se puede ingresar una cadena vacia")
return string == string[::-1]
except ValueError as ve:
print(ve)
return False
try:
print(palindrome(**))
except TypeError:
print("Solo se pueden ingresas strings")
""" utilizando la palabra finally """
# se utiliza para cerrar un archivo dentro de python
# Cerrar una conexion a una base de datos
# Liberar recursos externos
# Generalmente no se usa pero hay tener el conocimiento
try:
f = open("archivo.txt") # Hacer cualquier cosa con nuestro archivo
finally:
f.close()
| false |
d3476fdff91c0d71b77eb3890426e9ae5d60905f | northDacoder/python_tic_tac_toe_terminal | /calc.py | 2,419 | 4.5625 | 5 | #building a calculator
"""
Make a calculator that has basic and advanced functionality. Let the user pick which one they want.
Basic calculator will have addition, subtraction, multiplication, and division
Advanced calculator will have exponents and square roots
"""
import math
# Basic Calculator
def basic_calc(response):
while (response != "q"):
if response == "add":
num_one = int(raw_input("Enter the first number to add"))
num_two = int(raw_input("Enter the second number to add"))
print "Addition: "
print num_one + num_two
elif response == "substract":
num_one = int(raw_input("Enter the first number to subtract"))
num_two = int(raw_input("Enter the second number to subtract"))
print "Subtraction: "
print num_one - num_two
elif response == "multiply":
num_one = int(raw_input("Enter the first number to multiply"))
num_two = int(raw_input("Enter the second number to multiply"))
print "Multiplication: "
print num_one * num_two
elif response == "divide":
num_one = int(raw_input("Enter the first number to divide"))
num_two = int(raw_input("Enter the second number to divide"))
print "Division: "
print num_one / num_two
# Advanced Calculator
def advanced_calc(response):
while (response != "q"):
if response == "exponents":
number = int(raw_input("Enter the number"))
exponent = int(raw_input("Please enter the exponent"))
print "Exponents: "
print math.pow(number, exponent)
elif response == "squareroots":
num_one = int(raw_input("Enter the number you would like to find the square root for"))
print "Square Root: "
print math.sqrt(num_one)
# Choose type of calculator to use ("basic" or "advanced")
def choose_calc(type):
if type == "basic":
response = raw_input("What operation would you like to perform? (Please add, subtract, multiply, or divide) ")
currentCalc = "basic"
print "Loading basic calculator"
basic_calc(response)
elif type == "advanced":
response = raw_input("What operation would you like to perform? (Please select exponents or squareroots) ")
currentCalc = "advanced"
print "Loading advanced calculator"
advanced_calc(response)
calcType = raw_input("Please select the type of calculator you would like to use (Please select basic or advanced) ")
choose_calc(calcType)
currentCalc = ""
if (response == "q"):
print "Thanks for using the calculator!"
| true |
10cdefa306cd251c3c12e6319d110ee7c44f44ee | Ishworkhadka99123/Fourpy | /main.py | 480 | 4.34375 | 4 | # 4.N Given the integer N - the number of minutes that is passed since midnight.
# How many hours and minutes are displayed on the 24h digital clock?
# The program should print two numbers:
# The number of hours(between 0 and 23) and the number of minutes (between 0 and 59)
N = int(input("Enter the number of minutes passed since midnight: "))
hours = N//60
minutes = N%60
print(f"The hours is {hours}")
print(f"The minutes is {minutes}")
print(f"It's {hours}:{minutes} now.")
| true |
14b17a8e2d1cede8b1ebedcce9a0174b9c64604c | fjimenez81/test_pyhton | /ejercicio3_leccion1.py | 266 | 4.15625 | 4 | print("Vamos a conseguir la media de tres numeros")
num1=int(input("Introduce el primer numero: "))
num2=int(input("Introduce el segundo numero: "))
num3=int(input("Introduce el tercer numero: "))
resutado=(num1+num2+num3)/3
print("El resutado es: ",resutado)
| false |
573b81d529ab8b184a1e0c192308415f6e723431 | vkp3012/Python | /collections_namedtuple.py | 1,122 | 4.3125 | 4 | """
collections.namedtuple()
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
"""
from collections import namedtuple
"""
-------------------------------------------------------------
point = namedtuple("point",'x,y')
pt1 = point(1,2)
pt2 = point(3,4)
dot_product = (pt1.x*pt2.x) + (pt1.y*pt2.y)
print(dot_product)
----------------------------------------------------------------
----------------------------------------------------------------
car = namedtuple("Car","Price Mileage Colour Class")
xyz = car(Price=10000,Mileage=30,Colour = 'Cyan' ,Class='Y')
#print(xyz)
print(xyz.Class)
--------------------------------
"""
N = int(input())
fields = input().split()
total = 0
for i in range(N):
students = namedtuple('student',fields)
field1,field2,field3,field4 = input().split()
student = students(field1,field2,field3,field4)
total += int(student.MARKS)
print('{:.2f}'.format(total/N))
| true |
824044548fc9d4a9c387d842c95cc67ad7d2b4d1 | futenW/CS-16 | /cs16/hw2/arraysearch.py | 887 | 4.34375 | 4 | #!/usr/bin/python3
class InvalidInputException(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value)
def array_search(item, array):
"""array_search: int * (int array) -> bool
Purpose: Checks if a specific integer is in an int array
Consumes: an integer and an array
Produces: a boolean indicating if the integer is in the array
Example: array_search(3, [1,3,4]) -> True
array_search(6, [1,3,4]) -> False
"""
# error checking on input array -- is it valid?
if array is None:
raise InvalidInputException("array is None (invalid)")
# error checking on input item -- is it valid?
if item is None:
raise InvalidInputException("item is None (invalid)")
for i in array:
if i == item:
return True # yay
return False # aww
| true |
70980d13c585838167b2f1960418c3e329061796 | futenW/CS-16 | /cs16/hw6/increment.py | 1,397 | 4.25 | 4 | #! /usr/bin/python3
class InvalidInputException(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value)
def increment(number):
"""increment: list -> list
Purpose: Checks if input is valid and then calls increment helper.
This should throw InvalidInputException if your list is empty or null.
Consumes: A list of digits representing a number
Produces: A list of 0's and 1's representing that number + 1
"""
if number == None: # null input
raise InvalidInputException("Input is null")
if len(number) == 0: # empty list
raise InvalidInputException("List is empty")
return increment_helper(number)
def increment_helper(number):
"""increment: list -> list
Purpose: Increments a binary number by 1. This is the method that recurses on itself and actually increments the number
Consumes: a list of 0's and 1's representing a binary number, k
Produces: a list of 0's and 1's representing k + 1
Example:
increment([1,1,0,0]) -> [1,1,0,1]
"""
if number.pop() == 0: # right most digit is 0
number.append(1)
return number
else: # right most digit is 1
if len(number) == 0: # left most digit was 1
return [1,0]
new = increment_helper(number) # size of one less
new.append(0)
return new
| true |
eaede8c254b5d8dcafebce58a4dded5085752e3e | StevenJ87/Python_Learning | /app6.py | 453 | 4.3125 | 4 | course = 'Python for Beginners'
# Count the number characters in a string
print(len(course))
# Methods that can be used on strings
print(course.upper())
print(course)
print(course.lower())
print(course.find('P'))
print(course.find('o'))
print(course.find('E'))
print(course.find('Beginners'))
print(course.replace('Beginners','Absolute Beginners'))
print(course.replace('P','Sl'))
# 'in' operator use
print('Python' in course)
print('baby' in course) | true |
e68fa7e97670c48ec794eb8675a615453cf9cb63 | lxw15337674/Language_learning | /python/basic_gramma/Error, debug, test/debug.py | 1,914 | 4.15625 | 4 | ##debug(调试)
#print()
"""即直接打出可能出现问题的变量"""
#断言(assert)
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
"""assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码
肯定会出错。
如果断言失败,assert语句本身就会抛出AssertionError:
$ python3 err.py
Traceback (most recent call last):
...
AssertionError: n is zero!
启动Python解释器时可以用-O参数来关闭assert:
$ python3 -O err.py
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
关闭后,你可以把所有的assert语句当成pass来看。"""
#logging
"""把print()替换为logging,和assert比,logging不会抛出错误,而且可以输出到文件:"""
import logging
logging.basicConfig(level=logging.INFO)
s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)
"""看到输出了:
$ python3 err.py
INFO:root:n = 0
Traceback (most recent call last):
File "err.py", line 8, in <module>
print(10 / n)
ZeroDivisionError: division by zero
这就是logging的好处,它允许你指定记录信息的级别,有debug,info,warning,error
等几个级别,当我们指定level=INFO时,logging.debug就不起作用了。同理,指定
level=WARNING后,debug和info就不起作用了。这样一来,你可以放心地输出不同级别的
信息,也不用删除,最后统一控制输出哪个级别的信息。
logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,
比如console和文件。"""
##pdb
"""让程序以单步方式运行,可以随时查看运行状态。"""
##pdb.set_trace()
"""这个方法也是用pdb,但是不需要单步执行,我们只需要import pdb,然后,在
可能出错的地方放一个pdb.set_trace(),就可以设置一个断点"""
| false |
03eae4d2792f4c947c84103b578067341ab7fd7c | lxw15337674/Language_learning | /python/basic_gramma/Object-oriented/Use metaclasses/type().py | 1,965 | 4.25 | 4 | #Use metaclasses(使用元类)
#type()
"""动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时
动态创建的"""
#例如定义一个Hello的class,就写一个hello.py模块
class Hello(object):
def hello(self,name='world'):
print('Hello,%s' %name)
"""当py的解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建
出一个Hello的class对象"""
#from hello import Hello
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
"""type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,
而h是一个实例,他的类型就是class.Hello
class的定义是运行时动态创建的,而创建class的方法就是使用type()函数
type()函数可以返回一个对象的类型,又可以创建出新的类型"""
#可以通过type()函数创建出Hello类,而无需通过class Hello(object)...定义:
def fn(self,name='world'): #先定义函数
print('Hello,%s.' % name)
Hello = type('hello',(object,),dict(hello=fn) #创建Hello class
h = Hello()
h.hello()
print(type(Hello))
print(type(h))
"""要创建一个class对象,type()函数需要传入3个参数:
1.class的名称
2.继承的父类集合,注意python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法
3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上
通过type()函数创建的类和直接写class是一样的,因为py的解释器遇到class定义时,仅仅
是扫描一下class定义的语法,然后调用type()函数创建出class。
正常情况下,我们都用class Xxx....来创建类,但是,type()函数也允许我们动态创建出类
而静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码,
实,本子都是动态编译
-
| false |
a888e74aaec08acabc0df1c171100bf2cb8d9634 | lxw15337674/Language_learning | /python/basic_gramma/Built-in module/use_collections.py | 1,721 | 4.25 | 4 | """collections是Python内建的一个集合模块,提供了许多有用的集合类。"""
#nametuple
from collections import namedtuple
Point = namedtuple('Point',['x','y']) #定义一个坐标
p = Point(1,2)
print(p.x,p.y)
"""namedtuple用来穿件一个自定义的tuple对象,并规定tuple元素个数,并用属性而不是索引来引用元素"""
Circle = namedtuple('Circle',['x','y','r'])
c = Circle(1,2,3)
print(c)
#deque
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)
"""deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈,
deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。"""
#defaultdict
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print(dd['key1']) # key1存在
print(dd['key2']) # key2不存在
"""用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict"""
#OrderedDict
from collections import OrderedDict
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d) # dict的Key是无序的
od = OrderedDict([('a', 5), ('b', 2), ('c', 3)])
print(od) # OrderedDict的Key是有序的
print(list(od.keys()))#按照插入的key的顺序返回
"""OrderedDict可以实现FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key."""
#Counter
from collections import Counter
c = Counter()
for ch in 'programming':
c[ch] = c[ch] + 1
print(c)
"""Counter是一个简单的计数器,例如,统计字符出现的个数:
Counter实际上也是dict的一个子类"""
| false |
da4348a76a46ebd05d25beb196aedda653c9ffd8 | mulualem04/ISD-practical-3 | /ISD practical3Q1.py | 325 | 4.15625 | 4 | x=int(input("Enter a number: "))
y=int(input("Enter a number: "))
# input from the user is assigned to a variable 'x' and 'y'
a=x+y # Addition
b=x-y # Substraction
c=x*y # Multiplication
d=x/y # Division
e=x%y # Modulus
f=x**y # Exponent
g=x//y # Floor Division
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
| true |
36bf43b989d3c52fe4eff374e536d419dbbc8dac | isthatjoke/projects | /python algorithm/lesson_1/Task_9.py | 553 | 4.3125 | 4 | # Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
# https://drive.google.com/file/d/1YCLhS-6C10v-gNm3RybBDDtheBF7c4Ns/view?usp=sharing
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
c = int(input("Введите третье число: "))
if b <= a <= c or c <= a <= b:
print(a)
elif a <= b <= c or c <= b <= a:
print(b)
else:
print(c)
| false |
47b02e6f616f79e4d55b9d18b01b80ef3bf5de25 | isthatjoke/projects | /python algorithm/lesson_1/Task_5.py | 1,091 | 4.25 | 4 | # Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят,
# и сколько между ними находится букв.
# https://drive.google.com/file/d/1YCLhS-6C10v-gNm3RybBDDtheBF7c4Ns/view?usp=sharing
first_letter = input('Введите букву латинского алфавита: ')
second_letter = input('Введите букву латинского алфавита: ')
print(f'Буква {first_letter} находится на {ord(first_letter.upper()) - 64} месте в алфавите')
print(f'Буква {second_letter} находится на {ord(second_letter.upper()) - 64} месте в алфавите')
if ord(first_letter.upper()) > ord(second_letter.upper()):
print(f'Разница между буквами составляет'
f' {ord(first_letter.upper()) - ord(second_letter.upper())}')
else:
print(f'Разница между буквами составляет'
f' {ord(second_letter.upper()) - ord(first_letter.upper())}')
| false |
44c746372b909106356a01d1dab43fc99301c70a | marius-str/PythonPractice | /PracticeContent/Practice1.py | 1,209 | 4.46875 | 4 | print("Hello there", '\n')
print('Hello there')
####################
print('Hello World', '\n')
####################
name = input('Enter a name to display: ')
print(name)
# this is a comment
'''
this is a comment
on a
different
line
'''
#######################
name = "Jack"
def printname(myname):
# this function receives a name parameter and prints it
print("##########################")
print("in printname() function")
print(myname)
print("##########################")
printname(name)
# >>> String Variables <<<
first_name = 'Susan'
print(first_name)
#######################
sentence = 'This is a dog'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
print('i appears', sentence.count('i'), 'times in the sentence')
#######################
first = input('What is your first name? ')
middle = input('What is your middle name? ')
last = input('What is your last name? ')
# formatting strings in the print statements
# wrapping on different lines
print('Hello ' + first.capitalize() + ' '
+ middle.capitalize() + ' '
+ last.capitalize())
# combining strings
print('Hi ' + first + ' ' + last)
#######################
| true |
b0eabb90c7d1c0390a32c9e9c3c17b451ec362ce | AAQ6291/PYCATCH | /source code/code/ch711.py | 855 | 4.15625 | 4 | #!/usr/bin/env python
#coding=utf-8
# 定義Obj類別
class Obj:
# 在屬性名稱前加上兩個底線表示為私有(Private)變數
__VariableHidden = 10
def __init__(self):
# 在屬性名稱前加上兩個底線表示為私有(Private)變數
self.__hiddentoo = 20
# 定義op()方法, 並對私有(Private)變數進行運算
def op(self):
self.__VariableHidden += 1
print self.__VariableHidden
self.__hiddentoo += 2
print self.__hiddentoo
def __bar(self):
print "in bar!"
class subObj(Obj):
def __init__(self):
pass
def foo(self):
print Obj.__VariableHidden
# Obj類別
obj = Obj()
obj.op()
# subObj類別
subobj = subObj()
# 底下這3行的宣告都會出現AttributeError錯誤訊息。
subobj.__bar()
subobj.op()
subobj.foo()
| false |
374d78687be52f50b3543828035ef01ec9877f10 | zantaclaus/2021s-CodingDaily | /Day044-Zan.py | 264 | 4.25 | 4 | def sortString(string):
ans = ""
for letter in string:
if letter.isupper():
ans += letter
for letter in string:
if letter.islower():
ans += letter
return ans
string = input()
print(sortString(string))
| false |
2b9dfbf946ad04654d4fe2c633e46f5ba3743871 | localpunter/Learning_Python_through_Blockchain | /Assignments/assignment_7.py | 2,275 | 4.15625 | 4 | # 1) Create a Food class with a “name” and a “kind” attribute as well as a “describe()” method (which prints “name” and “kind” in a sentence).
class Food:
def __init__(self, name, kind):
self.name = name
self.kind = kind
# Overwrite a “dunder” method to be able to print your “Food” class.
def __repr__(self):
return "Name: {}, Kind: {}".format(self.name, self.kind)
def describe(self):
print("\nTask 1: I like to eat a {} {}.\nIt is delicious!".format(self.kind, self.name))
def eat1(self):
print("\nI like {} with {} sauce".format(self.name, self.kind))
def eat2(self):
print("\n{} is my favourite {}".format(self.name, self.kind))
apple = Food("apple", "Granny Smith")
apple.describe()
pork = Food("pork", "chop")
pork.describe()
# 2) Try turning describe() from an instance method into a class and a static method. Change it back to an instance method thereafter.
# class Food:
# name = ""
# kind = ""
# @classmethod
# def describe(cls):
# print("Task 2 '@classmethod': I like to eat a {} {}.\nIt is delicious!".format(cls.kind, cls.name))
# Food.name = "apple"
# Food.kind = "Granny Smith"
# Food.describe()
# class Food:
# @staticmethod
# def describe(name, kind):
# print("Task 2 '@staticmethod': I like to eat a {} {}.\nIt is delicious!".format(kind, name))
# name = "Apple"
# kind = "Granny Smith"
# Food.describe(name, kind)
# class Food:
# def __init__(self, name, kind):
# self.name = name
# self.kind = kind
# def describe(self):
# print("\nTask 1: I like to eat a {} {}.\nIt is delicious!".format(self.kind, self.name))
# def eat1(self):
# print("\nI like {} with {} sauce".format(self.name, self.kind))
# def eat2(self):
# print("\n{} is my favourite {}".format(self.name, self.kind))
# apple = Food("apple", "Granny Smith")
# apple.describe()
# pork = Food("pork", "chop")
# pork.describe()
# 3) Create a “Meat” and a “Fruit” class – both should inherit from “Food”. Add a “cook()” method to “Meat” and “clean()” to “Fruit”.
# 4) Overwrite a “dunder” method to be able to print your “Food” class.
print(pork)
| true |
cd1f40e7ad3ea921a3129c974e9fe6758b2a7cc4 | localpunter/Learning_Python_through_Blockchain | /Documents/Section 07 - Working with Files/files-assignment-1-solution/assignment.py | 1,854 | 4.40625 | 4 | # 1) Write a short Python script which queries the user for input (infinite loop with exit possibility) and writes the input to a file.
# running = True
# while running:
# print('Please choose')
# print('1: Add input')
# print('2: Output data')
# print('q: Quit')
# user_input = input('Your Choice: ')
# if user_input == '1':
# data_to_store = input('Your text: ')
# with open('assignment.txt', mode='a') as f:
# f.write(data_to_store)
# f.write('\n')
# elif user_input == '2':
# with open('assignment.txt', mode='r') as f:
# file_content = f.readlines()
# for line in file_content:
# print(line)
# elif user_input == 'q':
# running = False
# 2) Add another option to your user interface: The user should be able to output the data stored in the file in the terminal.
# 3) Store user input in a list (instead of directly adding it to the file) and write that list to the file – both with pickle and json.
import json
import pickle
running = True
user_input_list = []
while running:
print('Please choose')
print('1: Add input')
print('2: Output data')
print('q: Quit')
user_input = input('Your Choice: ')
if user_input == '1':
data_to_store = input('Your text: ')
user_input_list.append(data_to_store)
with open('assignment.p', mode='wb') as f:
# f.write(json.dumps(user_input_list))
f.write(pickle.dumps(user_input_list))
elif user_input == '2':
with open('assignment.p', mode='rb') as f:
file_content = pickle.loads(f.read())
for line in file_content:
print(line)
elif user_input == 'q':
running = False
# 4) Adjust the logic to load the file content to work with pickled/ json data.
| true |
b6d88ccb049049c78f037b5924f4c6eb11a02d42 | sreyemnayr/jamf_pro_api | /jssapi/decorators.py | 1,455 | 4.25 | 4 | # -*- coding: utf-8 -*-
#
class alias(object):
"""
Alias class that can be used as a decorator for making methods callable
through other names (or "aliases").
Note: This decorator must be used inside an @aliased -decorated class.
For example, if you want to make the method shout() be also callable as
yell() and scream(), you can use alias like this:
@alias('yell', 'scream')
def shout(message):
# ....
"""
def __init__(self, *aliases):
"""Constructor."""
self.aliases = set(aliases)
def __call__(self, f):
"""
Method call wrapper. As this decorator has arguments, this method will
only be called once as a part of the decoration process, receiving only
one argument: the decorated function ('f'). As a result of this kind of
decorator, this method must return the callable that will wrap the
decorated function.
"""
f._aliases = self.aliases
return f
def aliased(aliased_class):
original_methods = aliased_class.__dict__.copy()
for name, method in original_methods.items():
if hasattr(method, '_aliases'):
# Add the aliases for 'method', but don't override any
# previously-defined attribute of 'aliased_class'
for alias in method._aliases - set(original_methods):
setattr(aliased_class, alias, method)
return aliased_class
| true |
98a527f8c5be70fd9a6b6b2ecc9bd92370f49258 | ashvinikumar-1/data_science | /function/function.py | 912 | 4.3125 | 4 | # Define the function shout
def shout():
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = 'congratulations'+'!!!'
# Print shout_word
print(shout_word)
# Define shout with the parameter, word
def shout_param(word):
"""Print a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = word + '!!!'
# Print shout_word
print(shout_word)
# Define shout with the parameter, word
def shout_ret(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = word + '!!!'
# Replace print with return
return shout_word
# Pass 'congratulations' to shout: yell
yell = shout_ret('congratulations')
# Print yell
print(yell)
# Call shout with the string 'congratulations'
shout_param('congratulations')
# Call shout
shout()
| true |
616c440a8529c902c71e277ce6c52cb8424d7803 | coopertingey123/coopertingey-devpipeling-projects | /september/sept-8/calendar.py | 383 | 4.125 | 4 | day_of_week = 3
month= "September"
year="2021"
month_year = month + " " + year
days_in_month=30
print(f"{month_year:^28}\n")
print(" S M T W T F S\n")
for spaces in range(day_of_week):
print(" ", end="")
for day in range(1, days_in_month+1):
print(f"{day:>3}", end=" ")
day_of_week = day_of_week + 1
if day_of_week == 7:
print("\n")
day_of_week = 0 | false |
af2ea5c5ed274d92ef836cd41abcdfc94159dcc8 | ehsan1233/thesis-report | /NLTK tutorial/stemming.py | 493 | 4.125 | 4 | # stemming is to finding the root of words.
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
# # having stem of words in list
# example_words = ["Python","pythoning","pythoned"]
# for w in example_words:
# print(ps.stem(w))
# to stemming words in a sentence
new_text = "it is very important to be regular and regularity is important like importantly acting like people"
words = word_tokenize(new_text)
for z in words:
print(ps.stem(z)) | false |
1074c2b0b3c5959e765498fde1e0b610eef29d08 | gchopra/pythonConstructs | /Binary_Tree/DeptFirstSearch_BinaryTree.py | 2,138 | 4.15625 | 4 |
#create a node for th binary tree
class node:
def __init__(self,value):
self.value = value
self.right = None
self.left = None
#create the tree using nodes
class binaryTree:
def __init__(self,root):
self.root = node(root)
#Pre order traversal: root node -> left node -> right node
#In the sequence every node end up printing in the form of base node
def preOrderTraversal(self,base_node,travel_path):
if base_node:
travel_path += str(base_node.value) + '-'
travel_path = self.preOrderTraversal(base_node.left,travel_path)
travel_path = self.preOrderTraversal(base_node.right,travel_path)
return travel_path
#In order traversal: left node -> root node -> right node
def inOrderTraversal(self,base_node,travel_path):
if base_node:
travel_path = self.inOrderTraversal(base_node.left,travel_path)
travel_path += str(base_node.value) + '-'
travel_path = self.inOrderTraversal(base_node.right,travel_path)
return travel_path
def postOrderTraversal(self,base_node,travel_path):
if base_node:
travel_path = self.postOrderTraversal(base_node.left,travel_path)
travel_path = self.postOrderTraversal(base_node.right,travel_path)
travel_path += str(base_node.value) + '-'
return travel_path
"""
The tree being created would look something like this
10
20 30
40 50 60 70
pre order sequence = 10-20-40-50-30-60-70-
in order sequence = 40-20-50-10-60-30-70-
post order sequence = 40-50-20-60-70-30-10-
"""
if __name__ == '__main__':
tree = binaryTree(10)
tree.root.left = node(20)
tree.root.right = node(30)
tree.root.left.left = node(40)
tree.root.left.right = node(50)
tree.root.right.left = node(60)
tree.root.right.right = node(70)
print(tree.preOrderTraversal(tree.root,""))
print(tree.inOrderTraversal(tree.root, ""))
print(tree.postOrderTraversal(tree.root, "")) | true |
06ab829c9c9a093f1534f7abc9dfa0082a1b40e2 | Riddhesh06/HactoberFest | /diffie_hellman.py | 578 | 4.21875 | 4 | p = int(input("Enter prime number : "))
g = int(input("Enter primitive root : "))
Xa = int(input("Enter private key of A : "))
Xb = int(input("Enter private key of B : "))
while(Xa >= p):
Xa = input("Enter a private key for A less than the prime number.")
while(Xb >= p):
Xb = input("Enter a private key for B less than the prime number.")
A = pow(g,Xa,p)
B = pow(g,Xb,p)
Ka = pow(B,Xa,p)
Kb = pow(A,Xb,p)
print("Public key of A is " + str(A))
print("Public key of B is " + str(B))
print("Symmetric key of A is " + str(Ka))
print("Symmetric key of B is " + str(Kb))
| false |
9562b54fc5075b34da04daeb059a61e2eaeb6962 | chelseadole/data-structures-and-algorithms | /practice_problems/reverse_a_string_with_stack.py | 338 | 4.125 | 4 | """
Reverse a string using a stack.
Input: string
Output: string
EX: "chelsea" --> "aeslehc"
"""
from data_structures.stack import Stack
def stack_reverse_string(input):
stk = Stack()
for elem in input:
stk.push(elem)
res = ""
while stk.size() > 0:
elem = stk.pop()
res += elem
return res
| true |
3b1fa163ccb63beb4262b773847e90f9dbd89bb3 | jasonstan/math_game | /math_game.py | 2,866 | 4.25 | 4 | """
Game to test user's arithmetic abilities. Allows user to determine
number of questions in quiz, whether or not division is included in
quiz, the number of factors included in each question of quiz, and both
the low and high of the ranges from which random numbers are chosen
when assembling each new equation.
Author: Jason Stanley
"""
import random
import operator
import time
import numpy
def get_random_operators(ops_exclude, factors):
"""
Get mathematical operators. Retrieve one less than the number of
factors that user has requested for equations. Parameter 'div'
allows user to exclude division operator.
"""
operators = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
for o in ops_exclude:
operators.pop(o)
ops = []
for i in range(factors-1):
op_key = random.choice(list(operators.keys()))
op_value = operators.get(op_key)
ops.append({op_key: op_value})
return ops
def get_random_numbers(N, low, high):
"""Get N random numbers between low and high."""
return numpy.random.randint(low, high, size=N)
def get_random_equation(ops_exclude, factors, low, high):
"""
Generate a random equation with N random numbers and N-1 randomly
selected math operators.
BUG: not yet evaluating order of operations correctly
"""
nums = get_random_numbers(factors, low, high)
ops = get_random_operators(ops_exclude, factors)
answer = nums[0]
ques = 'What is {}'.format(nums[0])
for i in range(1, factors):
answer = ops[i-1].values()[0](answer, nums[i])
ques = ques + ' ' + ops[i-1].keys()[0] + ' ' + str(nums[i])
ques = ques + '?'
print ques
return answer
def evaluate_response(ops_exclude, factors, low, high):
"""
Get correct answer and user response, evaluate equivalence, return
True if correct, False otherwise, and return correct answer.
"""
answer = get_random_equation(ops_exclude, factors, low, high)
guess = float(input())
return {'correct': guess == answer,
'answer': answer}
def quiz(N=10, ops_exclude=None, factors=2, low=1, high=15):
"""
Loop through N questions, store number of correct responses.
"""
print("Welcome. This is a {} question math quiz. Operators excluded: {}\n"
.format(N, ops_exclude))
score = 0
for i in range(N):
print('Question #{} of {}:'.format(i+1, N))
eval = evaluate_response(ops_exclude, factors, low, high)
correct = eval['correct']
if correct:
score += 1
print('Correct!\n')
else:
print('Incorrect! The correct answer is {}.\n'.format(eval['answer']))
time.sleep(1)
print('Your score was {}/{}'.format(score, N))
| true |
ccd6e98478ea0a289889eba4e585d7cedbd238dd | liangminCH/pythonPractise | /syntax/enumerate01.py | 527 | 4.21875 | 4 | # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,
# 一般用在 for 循环当中。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list01 = list(enumerate(seasons))
print(list01) #[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list02 = list(enumerate(seasons, start=1)) # 下标从 1 开始
print(list02) #[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
| false |
e9d215d2bc7523023f148747ee0baeb8679da887 | augustedupin123/python_practice | /p_tuple2.py | 640 | 4.34375 | 4 | #Write python program to replace last values of tuples in a list.
def replacetuples(list1):
for i in list1:
if i is tuple:
p = list(i)
p[-1] = 100
i = tuple(p)
list1.append(i)
print(list1)
replacetuples([2,3,(10,20,2,),4,(12,234,19,)])
'''def epalcetuple(list1):
list2 = []
list3 = []
for i in list1:
if i is tuple:
list1.remove(i)
list2.append(i)
for j in list2:
for k in list2[j]:
list2[j][k][-1] = 100
print(list2)
epalcetuple([2,3,(10,20,2),4,(12,234,19)])
wrong output'''
| false |
6d7829b7227b94eee1eba46ad3e377059e184c11 | augustedupin123/python_practice | /p30_length_of_string_countingoccurance.py | 770 | 4.21875 | 4 | #Count the occurance of a particular character and find the length of a string.
#def length_of_string(str1):
# count = 0
# for i in str1:
# count+=1
# return count
#print(length_of_string('mohammedbinsalmanbinabdulaziz'))
'''def roughstring(abc):
for i in abc:
print(abc)
a = input('enter abc')
roughstring(a)'''
'''def roughstring(abc):
for i in abc:
print(str(i))
a = input('enter abc')
roughstring(a)'''
'''def roughstring(abc):
for i in abc:
print (i)
a = input('enter the string')
roughstring(a)'''
def roughstring(abc):
count = 0
for i in abc:
if (i== " "):
count+=1
print('no of times space occurs is:')
print (count)
a = input('enter the string')
roughstring(a)
| false |
a4cf7c7ea0bb3252db05519554289880d8c31d68 | augustedupin123/python_practice | /p4_prc.py | 1,325 | 4.15625 | 4 | # def num(n):
# if n > 0 :
# return 'positive'
# elif n < 0 :
# return 'negative'
# else:
# return '0'
# x = float(input('Enter the required number : '))
# print(num(x))
# check palindrome
def check_palindrome(s):
"""
take the original string
iterate it reversively
store the characters incresingly in reverse order
check if the new string and the old one are same
"""
# Complexity : n
# if s == s[::-1]:
# return True
# return False
# complexity = n/2
if s[0 : len(s)//2] == s[len(s) : len(s)//2 : -1]:
return True
return False
# complexity = n/2
# works both for even and odd
# for i in range(len(s)//2):
# if s[i] == s[-i-1]:
# pass
# else:
# return False
# return True
print(check_palindrome(input("enter string to check palindrome : ")))
"""
list
iterable - collection of more than one references
[]
different types of data can be there at every index
mutable
indexed
string
iterable - collection of more than one references
'', "" -> single line
""" """, ''' ''' -> multilined strings
at every index there should be only one character
immutable
indexed
character are 256 in number, defined by ASCII
""" | false |
a07df99c5a89903cea86f2578f445cea376bba18 | augustedupin123/python_practice | /p34_len_multiple.py | 356 | 4.21875 | 4 | #Reverse the string if length of string is a multiple of 4
#def string_function(a):
# print(len(a))
#m = input('enter the value of m')
#string_function(m)
def function1(m):
if(len(m)%4 == 0):
for i in reversed(m):
print(i)
else:
print('string is not a multiple of 4')
a = input('enter the string')
function1(a)
| true |
00ef9f9a4c90cd3bc12b3f85020d9b5c5aa93d03 | augustedupin123/python_practice | /ptuple5_reversetuple.py | 792 | 4.5625 | 5 | <<<<<<< HEAD
#Write a program to reverse a tuple
def reversetuple(tuple1):
list2 = []
for i in reversed(range(len(tuple1))):
list2.append(tuple1[i])
tuple2 = tuple(list2)
return(tuple2)
n = int(input('enter no. of tuple elements'))
list1 = []
for _ in range(n):
l = input()
list1.append(l)
tuple3 = tuple(list1)
print(reversetuple(tuple3))
=======
#Write a program to reverse a tuple
def reversetuple(tuple1):
list2 = []
for i in reversed(range(len(tuple1))):
list2.append(tuple1[i])
tuple2 = tuple(list2)
return(tuple2)
n = int(input('enter no. of tuple elements'))
list1 = []
for _ in range(n):
l = input()
list1.append(l)
tuple3 = tuple(list1)
print(reversetuple(tuple3))
>>>>>>> 71de252bd51c2625382c6bda77e62802edfb2b59
| false |
25144e67141e68e7a4a917a76b421e44c3a2594c | augustedupin123/python_practice | /p_longest_increasing_subarray.py | 456 | 4.15625 | 4 | #Find the length of longest increasing subarray in a given array.
def sfddih(list1):
n = len(list1)
list2 = []
i = 0
while(i<n):
count = 1
while(i<(n-1) and list1[i]<list1[i+1]):
count+=1
i+=1
list2.append(count)
i+=1
max2 = list2[0]
for j in range(len(list2)):
if(list2[j]>max2):
max2 = list2[j]
return(max2)
print(sfddih([2,3]))
| true |
e91aa5fcfe40dafe168672b0879c719cb4245bde | augustedupin123/python_practice | /p42_removing_oddcharacter.py | 307 | 4.40625 | 4 | #Write a program to remove the characters which have odd index values
#of a given string
def remove_odd_characters(str1):
str2 = ""
for i in range(len(str1)):
if(i%2 == 0):
str2 += str(str1[i])
print(str2)
a = input('enter the value of the string:')
remove_odd_characters(a) | true |
4100b390175cf4ab59798ec6e40a9272b6b378c4 | sansati/test | /bubble_sort.py | 1,065 | 4.21875 | 4 | '''
. Bubble sort
. Number of passes = total length of list - 1
. In outer loop, start with pass_num, and go till 0, decrease 1 every time
. In inner loop, run from 0 till pass_num, increase 1 every time
. In every run of inner loop, if the element that is in next index, is lesser than element in current index, then swap them
. COmplexity of bubble sort program-O (n2)
. Subsequent elements are compared (element at index 1 with element at index 2, element at index 2 with element at index 3 ...)
'''
def bubblesort(nlist): # function name bubblesort
for passnum in range(len(nlist)-1,0,-1): # for loop in reverse order from len-1 till 0
for i in range(passnum):
if nlist[i]>nlist[i+1]: # comparing
temp=nlist[i] # swap using temp
nlist[i]=nlist[i+1]
nlist[i+1]=temp
#nlist=[14,46,43,27,57,41,45,21,70]
nlist=[int(x) for x in input().split()] # list cpmrehension to define a space separeted list
bubblesort(nlist) # calling the function
print(nlist) # printing the sorted list
| true |
0c02173762ee59fe1e3be04fad859e04fccf75b6 | Jorgee97/AdventOfCode2019 | /Python Solutions/Day 1/day1_part2.py | 969 | 4.375 | 4 | ##############################################################
########## The Tyranny of the Rocket Equation ###############
########## https://adventofcode.com/2019/day/1 ###############
########## by Jorge Gomez ###############
##############################################################
from helpers import read_file
def calculate_fuel(m):
"""Return an integer
Fuel required to launch a given module(m) is based on its mass.
Specifically, to find the fuel required for a module,
take its mass, divide by three, round down, and subtract 2.
"""
return (m // 3) - 2
def calculate_fuel_total(m):
fuels = 0
m = calculate_fuel(m)
while m > 0:
fuels += m
m = calculate_fuel(m)
return fuels
if __name__ == "__main__":
modules = read_file('input.txt')
total_amount_of_fuel = sum([calculate_fuel_total(int(m)) for m in modules])
print(total_amount_of_fuel)
| true |
9dbc3c15e6202b88f9da4f29176dcc77231ca976 | rutuja1302/PythonPrograms | /AgeCalculator/age.py | 378 | 4.3125 | 4 | #age calulator
from datetime import date
from datetime import datetime
print("Your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("Your age is: ",age)
| true |
6e0e282090567738a4e70c0227daf33277b8eae2 | CescWang1991/LeetCode-Python | /python_solution/291_300/BestMeetingPoint.py | 1,681 | 4.28125 | 4 | # 296. Best Meeting Point
# A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values
# 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where
# distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
#
# For example, given three people living at (0,0), (0,4), and (2,2):
#
# 1 - 0 - 0 - 0 - 1
# | | | | |
# 0 - 0 - 0 - 0 - 0
# | | | | |
# 0 - 0 - 1 - 0 - 0
# The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.
#
# Hint:
# Try to solve it in one dimension first. How can this solution apply to the two dimension case?
class Solution:
# 我们考虑一维情况,将所有点按顺序排列[A, B, C, D],最佳开会地点在B, C之间,且距离为D - A + C - B。
# 拓展到二维空间,由于计算曼哈顿距离,只要把每个维度的距离相加即可。
def minTotalDistance(self, grid):
"""
:type grid: list[list[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
xAxis = []
yAxis = []
dist = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
xAxis.append(i)
yAxis.append(j)
xAxis = sorted(xAxis)
yAxis = sorted(yAxis)
n = len(xAxis)
lo, hi = 0, n-1
while lo < hi: # 从两头开始向中间遍历
dist += xAxis[hi] - xAxis[lo] + yAxis[hi] - yAxis[lo]
lo += 1
hi -= 1
return dist | true |
3ce23832d9ad9208dafb051165cff61ea84e3452 | CescWang1991/LeetCode-Python | /python_solution/311_320/BinaryTreeVerticalOrderTraversal.py | 2,027 | 4.125 | 4 | # 314. Binary Tree Vertical Order Traversal
# Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
# If two nodes are in the same row and column, the order should be from left to right.
# Examples:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its vertical order traversal as:
# [
# [9],
# [3,15],
# [20],
# [7]
# ]
# Given binary tree [3,9,20,4,5,2,7],
# _3_
# / \
# 9 20
# / \ / \
# 4 5 2 7
# return its vertical order traversal as:
# [
# [4],
# [9],
# [3,5,2],
# [20],
# [7]
# ]
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 采用BFS,将遍历到的节点加入queue,并且加入它的列数,root的列设为0,它的left列减一,right列加一,然后用一个dict记录
# 每一列所对应的列表,遍历时将节点值加入所对应列的列表即可。
def verticalOrder(self, root):
"""
:type root:
:rtype: list[list[int]]
"""
TreeMap = {}
queue = [(root, 0)]
TreeMap[0] = [root.val]
while queue:
curr = queue[0][0]
mark = queue[0][1]
del queue[0]
if curr.left:
queue.append((curr.left, mark-1))
if not TreeMap.get(mark-1):
TreeMap[mark - 1] = [curr.left.val]
else:
TreeMap[mark - 1].append(curr.left.val)
if curr.right:
queue.append((curr.right, mark+1))
if not TreeMap.get(mark+1):
TreeMap[mark + 1] = [curr.right.val]
else:
TreeMap[mark + 1].append(curr.right.val)
TreeMap = sorted(TreeMap.items(), key=lambda x:x[0])
res = []
for map in TreeMap:
res.append(map[1])
return res | false |
0ee2639b7480fd708af6faab32a0921f445d8195 | k4bir/PythonLab | /Lab_1/qn7.py | 952 | 4.34375 | 4 | """"You live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each
of the 10 stops on the way. How long will the bus journey take? Alternatively, you could run
to university. You could jog the first mile at 7mph; then run the next two at 15mph; before
jogging the last at 7mph; then run the next two at 15mph; before jogging the last at 7mph
again. Will this be quicker or slower than the bus?"""
#for bus
bus_distance=4
bus_speed=25
bus_t=bus_distance/bus_speed
bus_stop=2*10
bus_time=(bus_t*60)+bus_stop
print(f'Total time taken by bus is {bus_time}')
#for jogging
jog_distance=2
jog_speed=7
jog_time=(jog_distance/jog_speed)*60
#for running
run_distance=2
run_speed=15
run_time=(run_distance/run_speed)*60
total_time=(jog_time+run_time)
print(f'Total time taken by running is {total_time}')
if bus_time>total_time:
print("Taking bus is slower than running !!")
else:
print("Taking bus is faster than running !!") | true |
58b14489de26ae14c1a66b286bc8c360c9c42b35 | JennaScript/functions-tutorial-python | /functions.py | 629 | 4.125 | 4 | #Functions Tutorial
def area(width, height):
result = width * height
return result
result = area(5, 6)
print (result)
result = area(10, 10)
print (result)
result = area(11, 12)
print (result)
def subtract(num1, num2):
result = num1 - num2
return result
result = subtract (100, 50)
print (result)
result = subtract (500, 200)
print (result)
def divide (num1, num2):
result = num1 / num2
return result
result = divide (40, 5)
print (result)
def add (value1, value2):
result = value1 + value2
return result
result = add (100, 500)
print (result)
result = add (600, 100)
print (result) | true |
cce60e299f549ed38e480a097164b35a268c593b | ZFudge/Project-Euler-Python | /project3.py | 727 | 4.25 | 4 | #A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def isPalin(num):
return str(num) == str(num)[::-1]
def findLargestPalinProd():
largest = 0
res = []
for x in range(999,100,-1):
for y in range(999,100,-1):
z = x*y
if isPalin(z) and largest < z:
largest = z
res = [x,y]
print 'Largest product: ' + str(largest)
print 'Two factors: ' + str(res[0]) + ' ' + str(res[1])
findLargestPalinProd()
| true |
111d9ca4b08b0469ed6407b12fcf478126958f83 | stepans47/python | /Task14.py | 528 | 4.1875 | 4 | def isLetterVowel(letter):
vowels = ['a','e','i','o','u']
return letter in vowels
def isLetterConsonant(letter):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'y', 'z']
return letter in consonants
print('Enter one letter:')
letter = input()
if(isLetterVowel(letter.lower())):
print(letter + ' - letter is vowel')
elif(isLetterConsonant(letter.lower())):
print(letter + ' - letter is consonant')
else:
print(letter + ' - is not a letter')
| false |
679b344cabcde9ecc9ce584af133a0b7bb00b1f2 | stepans47/python | /Task10.py | 410 | 4.1875 | 4 | def sign(x):
if(x > 0):
return 1
elif(x < 0):
return -1
else:
return 0
isNumberIncorrect = True
while(isNumberIncorrect):
print("Enter one number and it's sign will be received:")
try:
number = int(input())
isNumberIncorrect = False
except:
print("You have to input a number!")
exit()
print("Ths sign is: " + str(sign(number))) | true |
af3e16cd53ddb5d98aada6b5e2d73c6d2b0a9050 | whbrewer/spc | /src/spc_apps/dna/bio.py | 1,984 | 4.25 | 4 | class DNA:
"""Class representing DNA as a string sequence."""
basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}
def __init__(self, s):
"""Create DNA instance initialized to string s."""
self.seq = s
def transcribe(self):
"""Return as rna string."""
return self.seq.replace('T', 'U')
def reverse(self):
"""Return dna string in reverse order."""
letters = list(self.seq)
letters.reverse()
return ''.join(letters)
def complement(self):
"""Return the complementary dna string."""
letters = list(self.seq)
letters = [self.basecomplement[base] for base in letters]
return ''.join(letters)
def reversecomplement(self):
"""Return the reverse complement of the dna string."""
letters = list(self.seq)
letters.reverse()
letters = [self.basecomplement[base] for base in letters]
return ''.join(letters)
def gc(self):
"""Return the percentage of dna composed of G+C."""
s = self.seq
gc = s.count('G') + s.count('C')
return gc * 100.0 / len(s)
def codons(self):
"""Return list of codons for the dna string."""
return self.__histogram(self.__analyze(3))
def nucleotides(self):
"""Return list of codons for the dna string."""
return self.__histogram(self.__analyze(1))
def dinucleotides(self):
"""Return list of codons for the dna string."""
return self.__histogram(self.__analyze(2))
def __analyze(self,n):
s = self.seq
end = len(s) - (len(s) % n) - 1
lx = [s[i:i+n] for i in range(0, end, n)]
return lx
def __histogram(self,x):
"""Compute a histogram"""
d = dict()
for e in x:
if e not in d:
d[e] = 1
else:
d[e] += 1
return d
| true |
26edfb70c453dd686ca4a77c38ef14dc392ad7dd | saint333/python_basico_1 | /diccionarios/7_ejercicio.py | 880 | 4.25 | 4 | #Escribir un programa que cree un diccionario de traducción español-inglés. El usuario introducirá las palabras en español e inglés separadas por dos puntos, y cada par <palabra>:<traducción> separados por comas. El programa debe crear un diccionario con las palabras y sus traducciones. Después pedirá una frase en español y utilizará el diccionario para traducirla palabra a palabra. Si una palabra no está en el diccionario debe dejarla sin traducir.
diccionario={}
palabras=input("introduzca las palabras en español e inglés separadas por dos puntos, y cada par <palabra>:<traducción> separados por comas: ")
for i in palabras.split(","):
clave, valor = i.split(":")
diccionario[clave]=valor
frase=input("Introduce una frase: ")
for i in frase.split():
if i in diccionario:
print(diccionario[i], end=" ")
else:
print(i, end=" ") | false |
b449ad388d092749bc8271fdcfb24b7ae2776166 | saint333/python_basico_1 | /bucles/6_ejercicio.py | 277 | 4.3125 | 4 | #Escribir un programa que pida al usuario un número entero y muestre por pantalla un triángulo rectángulo como el de más abajo, de altura el número introducido.
n = int(input("Introduce la altura del triángulo (entero positivo): "))
for i in range(n):
print("*"*(i+1)) | false |
e9aa8763e5601e87b67ca1f6d42810d22b55c669 | saint333/python_basico_1 | /list_and_tuples/6_ejercicio.py | 675 | 4.375 | 4 | #Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista, pregunte al usuario la nota que ha sacado en cada asignatura y elimine de la lista las asignaturas aprobadas. Al final el programa debe mostrar por pantalla las asignaturas que el usuario tiene que repetir.
cursos = ["Matemáticas", "Física", "Química", "Historia", "Lengua"]
desaprobados = []
for curso in cursos:
nota = input("¿Qué nota has sacado en " + curso + "?: ")
if nota >"11":
desaprobados.append(curso)
for curso in desaprobados:
cursos.remove(curso)
print(f"asignatura repetir es: {cursos}") | false |
322907641ce9dc91b959e11b5e7f516600672e66 | saint333/python_basico_1 | /condicionales/10_ejercicio.py | 1,777 | 4.53125 | 5 | """ La pizzería Bella Napoli ofrece pizzas vegetarianas y no vegetarianas a sus clientes. Los ingredientes para cada tipo de pizza aparecen a continuación.
Ingredientes vegetarianos: Pimiento y tofu.
Ingredientes no vegetarianos: Peperoni, Jamón y Salmón.
Escribir un programa que pregunte al usuario si quiere una pizza vegetariana o no, y en función de su respuesta le muestre un menú con los ingredientes disponibles para que elija. Solo se puede eligir un ingrediente además de la mozzarella y el tomate que están en todas la pizzas. Al final se debe mostrar por pantalla si la pizza elegida es vegetariana o no y todos los ingredientes que lleva. """
def ingredientes(eleccion):
if eleccion == "1":
ingredientes= input("""Eliga el ingredientes
1.- Pimiento
2.- Tofu
>>>>>> """)
if ingredientes == "1":
ingrediente = "pimiento"
else:
ingrediente = "tofu"
else:
ingredientes= input("""Eliga el ingredientes
1.- Peperoni
2.- Jamon
3.- Salmón
>>>>>> """)
if ingredientes == "1":
ingrediente = "peperoni"
elif ingredientes == "2":
ingrediente = "jamon"
else:
ingrediente = "salmon"
return ingrediente
def main():
pizza=input("""La pizzería Bella Napoli
1.- Vegetariana
2.- No vegetariana
¿Cual desea?: """)
if pizza == "1":
tipo = "vegetariana"
elif pizza == "2":
tipo = "no vegetariana"
else:
print("Numero incorrecto")
main()
ingrediente = ingredientes(pizza)
print(f"Tu tipo de pizza es {tipo} y tiene los siguientes ingredientes: mozzarrella, tomate y {ingrediente}")
if __name__=='__main__':
main() | false |
25234fccbb0e89c4fe4d4bfc750a4e5427f2f37b | BearWithAFez/Learning-Python | /Hoofdstuk 1/RockPaperScissors.py | 1,515 | 4.125 | 4 | from random import randint
print('let\'s play Rock Paper Scissors!')
print('You know how it works, just say -R- -P- or -S- respectively.')
print('Say -STOP- to stop the game.')
number = randint(0, 2)
points = 0
while True:
print('*** Current score: ' + str(points) + ' ***')
print('Alright 3- 2- 1- GO!')
x = input()
if x == 'STOP':
break
if x == 'S':
if number == 0:
print('ROCK!')
print('My point! (-1)')
points -= 1
elif number == 1:
print('PAPER!')
print('Your point! (+1)')
points += 1
else:
print('SCISSORS!')
print('Stalemate... (no points)')
elif x == 'R':
if number == 0:
print('ROCK!')
print('Stalemate... (no points)')
elif number == 1:
print('PAPER!')
print('My point! (-1)')
points -= 1
else:
print('SCISSORS!')
print('Your point! (+1)')
points += 1
elif x == 'P':
if number == 0:
print('ROCK!')
print('Your point! (+1)')
points += 1
elif number == 1:
print('PAPER!')
print('Stalemate... (no points)')
else:
print('SCISSORS!')
print('My point! (-1)')
points -= 1
else:
print("That\'s not a valid answer... say -R- -P- or -S-!")
number = randint(0, 2)
print('Thank you for playing!')
| true |
75e715b5660e838b930b77f00e9f9e1678dc1248 | Markelofnavi/LetsUpgrade-Python | /shekhar Day2 python.py | 2,370 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
#Python basic concepts taught in Day2
#Concepts practised by Shekhar Suman
#Formatting
# In[2]:
print("Hello World")
# In[4]:
print("Hello")
# In[6]:
print("hello python")
# In[7]:
""" ("") ---- ("")
('o')
(") - (")
(""')- (""') """
# In[113]:
#Triple string
# In[8]:
print(" Python's world")
# In[9]:
print("Hello\n Python")
# In[11]:
print(' Python\'s world')
# In[114]:
# \ tells the interpreter that it is in English, no need to interfere with interpretation
# In[12]:
print(" Hello \a Python")
# In[115]:
#alert sound
# In[15]:
print('Python \'s world')
# In[59]:
name = "xyz"
marks= 92.87
age= 26
print("The Name of person is", name,",Marks is", marks,",Age is", age)
print("The Name of person is %2s, Marks is %2d, Age is %2d" %(name,marks,age))
# In[60]:
print(f" The name of person is {name} the marks is {marks} age is {age}")
# In[ ]:
#fstring applicable for version above 3.4
# In[61]:
x=y=10
# In[62]:
x
# In[63]:
y
# In[64]:
x=20
id(x)
# In[65]:
y=20
id(y)
# In[116]:
#Variable declaration
# In[66]:
del x
# In[67]:
x
# In[68]:
y
# In[69]:
#Assignment operator
# In[70]:
5**5
# In[71]:
10+50
# In[72]:
10-25
# In[73]:
10/3
# In[74]:
10%4
# In[75]:
#Comparision operator
# In[76]:
x=10
# In[77]:
y=20
x==y
# In[78]:
z=10
x==z
# In[79]:
z<=x
# In[80]:
x>=y
# In[81]:
x>y
# In[82]:
x!=y
# In[83]:
x = get_ipython().getoutput('y')
# In[84]:
#no error but wirong format
# In[85]:
#Bitwise operator
# In[86]:
a=245
# In[87]:
b=1
# In[89]:
a|b
# In[90]:
bin(a)
# In[91]:
bin(b)
# In[92]:
a&b
# In[93]:
#logical operator
# In[94]:
a=1
b=20
a>20
# In[95]:
a>20 or 10>9
# In[96]:
a>20 and 10>9
# In[97]:
10>9 and 20>M
# In[98]:
10<9 and 20>M
# In[99]:
not 10>9
# In[100]:
not True
# In[101]:
str1= "pythonprogramming"
"a" in str1
# In[103]:
"x" not in str1
# In[104]:
"x" in str1
# In[105]:
x=1.5
y= 1.5
x==y
# In[106]:
x is y
# In[107]:
id(x)
# In[108]:
id(y)
# In[109]:
#different memory location
# In[110]:
10+10/29*4
# In[111]:
10/29
# In[112]:
10>8>9>11
# In[117]:
#10>8 and 8>9 and 9>11
# In[118]:
#DAY2 Finished
# In[ ]:
| false |
235c4b980b0ab9208fa33ae3bf0d30470410f556 | cmoody2/Python_Projects | /challenges/assignment_database_add_file.py | 2,039 | 4.21875 | 4 |
import sqlite3
fileList = ('information,docx', 'Hello.txt', 'myImage.png', \
'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
# ----------------------------------------------------------------
# This creates our database named file.db with two columns:
# ID(which will be the primary key) and FileName
# ----------------------------------------------------------------
conn = sqlite3.connect('file.db')
with conn:
cursor = conn.cursor()
# NOTE: FileName is set to only accept unique values by using
# the UNIQUE constraint
cursor.execute("CREATE TABLE IF NOT EXISTS Txt_Files( \
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
FileName TEXT UNIQUE\
)")
conn.commit()
conn.close()
# ----------------------------------------------------------------
# This iterates through the file list and grabs each file
# with the .txt type and enters them into the table under FileName
# ----------------------------------------------------------------
print("Search results for .txt files: \n")
for file in fileList:
if file.endswith(".txt"):
fileName = [file]
conn = sqlite3.connect('file.db')
with conn:
cursor = conn.cursor()
# Use IGNORE on the insert to stop program from trying to break the column 'FileName'
# UNIQUE constraint (i.e. stops duplicates)
cursor.execute("INSERT OR IGNORE INTO Txt_Files(FileName) VALUES (?)", \
(fileName))
conn.commit()
conn.close()
# ----------------------------------------------------------------
# This is our query to retrieve all records under column 'FileName'
# ----------------------------------------------------------------
conn = sqlite3.connect('file.db')
with conn:
cursor = conn.cursor()
cursor.execute("SELECT FileName FROM Txt_Files")
varFiles = cursor.fetchall()
for item in varFiles:
msg = "File Name: {}\n".format(item[0])
print(msg)
conn.close()
| true |
5cbd0bb7638ad9bb0506c2e7222ffcf6057e634f | cmoody2/Python_Projects | /exercises/keyboard_calculator.py | 1,512 | 4.125 | 4 | date = ("9/11/2020")
print("Today " + date + " we will be observing two of my favorite keyboard designs and finding out if I can afford them!")
RAMA = ("RAMA U80-A") #Here we define variables needed
RAMA_Price = 480
TGR = ("TGR Jane V2 CE")
TGR_Price = 550
My_Wallet = 880
print("")
print("Our first board is the " + RAMA + " at $" + str(RAMA_Price) + ".") #listing both boards and prices converting the int..
print("Our second board is the " + TGR + " at $" + str(TGR_Price) + ".") #... Price to str for concatenation.
print("And our budget is $880 available to spend.")
if TGR_Price + RAMA_Price <= My_Wallet: #expression to find if both boards can be purchased
print("I can buy both boards so I shall!")
if TGR_Price + RAMA_Price > My_Wallet:
print("I can't afford both boards!")
print("")
if TGR_Price + RAMA_Price > My_Wallet and TGR_Price < My_Wallet: #expression to find if either can be purchased standalone
print("I can afford to buy the " + TGR + " by itself.")
if TGR_Price + RAMA_Price > My_Wallet and RAMA_Price < My_Wallet:
print("I can afford to buy the " + RAMA + " by itself.")
if TGR_Price + RAMA_Price > My_Wallet and TGR_Price < My_Wallet and RAMA_Price < My_Wallet:
print("Decisions, Decisions...")
if TGR_Price + RAMA_Price > My_Wallet and TGR_Price < My_Wallet: #decision to purchase provided it fits in given budget
print("" + TGR + " will be the one I'll go with!")
| true |
b15468d1c0b7b1d548dcdbf7f69ddd8e7bf8ce5d | dpirvoiu/Python | /SinglyLinkedList/ReverseListMethod.py | 1,141 | 4.375 | 4 | # REVERSE A LINKED LIST, ITERATIVE AND RECURSIVE
# ITERATIVE Suing the PREVIOUS AND CURRENT NODE STRATEGY
def reverse_iterative(self):
prev = None
cur = self.head
while cur:
nxt = cur.next
cur.next = prev # THIS IS THE LINE THAT DOES THE WORK
prev = cur
cur = nxt
self.head = prev # WE SET THE HEAD to PREV because prev is now the last node in the linked list.
# RECURSIVE METHOD for REVERSE LIST
"""
We implement the base case.
We agree to solve the simplest problem, which in this case is to reverse just one pair of nodes.
We defer the remaining problem to a recursive call, which is the reversal of the rest of the linked list.
"""
def reverse_recursive(self):
def _reverse_recursive(cur, prev):
if not cur:
return prev
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return _reverse_recursive(cur, prev)
self.head = _reverse_recursive(cur=self.head, prev=None) | true |
997c062d02ee8a701b0315190652113e0f3bfd1f | thebatcn/python-study | /Learn_PYTHON3_the_HARD_WAY/ex45_rooms.py | 1,660 | 4.28125 | 4 | """ 室内场景类
包括了几个房间的类,基于room类"""
class room():
# def print_it(self):
# print("This is a room.")
def entry(self):
print("room's entry()")
class Corridor(room):
def entry(self):
print("进入了一小段狭窄的走廊,一端是客厅,另一端是去外面的大门。")
flag = True
while flag:
choices = input("你想进来?还是出去? ")
if choices == 'in':
flag = False
return 'living_room'
elif choices == 'out':
flag = False
return 'the_outside_world'
else:
print('输入错误,请输入 in 或者 out。')
class Living_room(room):
def entry(self):
print("这里是客厅。有一台正播放足球比赛的电视在墙上挂着。沙发就是电视的对面。客厅有2处大窗户,餐厅在另一边。")
def Watch_tv(self):
print("Watch tv")
def Dining(self):
print("Dining")
class Rest_Room(room):
def entry(self):
print("Rest_room")
def go_to_the_toilet(self):
print("嘘嘘 or 咚咚")
class Study(room):
def entry(self):
print("这里是书房")
def reading(self):
print("你先看什么书?")
class Bedroom(room):
def entry(self):
print("这是一间非常大的卧室")
def go_to_bed(self):
print("""是时间睡觉了
你进入了梦想。。。。。""")
class Finish():
def entry(self):
print("The finish map.")
| false |
9bac7f1b63324d98d8eba5bf0f3d13dd8aed677b | thebatcn/python-study | /算法图解/文字游戏.py | 1,972 | 4.375 | 4 | # 以下是使用Python编写的文字游戏代码示例:
# ```python
class Scene:
def __init__(self, description, options):
self.description = description
self.options = options
def play(self):
print(self.description)
for i, option in enumerate(self.options):
print(f"{i+1}. {option['text']}")
choice = input("请选择一个选项:")
if choice.isdigit() and 0 < int(choice) <= len(self.options):
self.options[int(choice)-1]['action']()
else:
print("无效的选项,请重新选择。")
self.play()
start_scene = Scene(
"你醒来发现自己在一个陌生的房间里,四周一片漆黑。你该怎么办?",
[
{
'text': "寻找出口",
'action': lambda: print("你摸索着四周,终于找到了一扇门。") or next_scene.play()
},
{
'text': "呼救",
'action': lambda: print("你大声呼救,但没有任何回应。") or next_scene.play()
}
]
)
next_scene = Scene(
"你打开门,发现自己置身于一片荒野之中。你该往哪个方向走?",
[
{
'text': "向东走",
'action': lambda: print("你向东走了一段路,发现了一座城镇。") or end_scene.play()
},
{
'text': "向南走",
'action': lambda: print("你向南走了一段路,遇到了一只凶猛的野兽。") or lose_scene.play()
}
]
)
end_scene = Scene(
"你来到了城镇,终于获得了自由。恭喜你通关!",
[]
)
lose_scene = Scene(
"你被野兽杀死了,游戏结束。",
[]
)
start_scene.play()
# ```
# 这个Python版本的游戏与JavaScript版本的游戏基本相同,只是语法和一些细节有所不同。玩家可以通过输入数字来选择选项,选择会影响游戏的进程,最终会通关或者失败。 | false |
9cadbc28c5193f60847ccd32d5818e491259fd9d | AngelosGeorgiou/PythonProjects | /ParityOutlier.py | 593 | 4.5 | 4 | # You are given an array (which will have a length of at least 3, but could be
# very large) containing integers. The array is either entirely comprised of
# odd integers or entirely comprised of even integers except for a single
# integer N. Write a method that takes the array as an argument and returns
# this "outlier" N.
def find_outlier(integers):
odd = even = 0
for i in [0,1,2]:
if integers[i]%2 == 0:
even += 1
else:
odd += 1
k = 1 if even > odd else 0
for i in integers:
if i%2==k:
return i
return None | true |
8072278f29eb74c212042f37e240437c954e1711 | Murarishetti-Shiva-Kumar/Python-Deep-Learning-Programming | /ICP 3/Employee.py | 1,930 | 4.15625 | 4 | """
Create a class Employee and then do the following
Create a data member to count the number of Employees
Create a constructor to initialize name, family, salary, department
Create a function to average salary
Create a Fulltime Employee class and it should inherit the properties of Employee class
Create the instances of Fulltime Employee class and Employee class and call their member functions
"""
class Employee:
Emp_Count = 0 # Data member(class variable)
Total_Salary = 0
def __init__(self, name, family, salary, department): # constructor to initialize name, family, salary, department
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.Emp_Count += 1
Employee.Total_Salary += salary
# return name, family, salary, department, Employee.Emp_Count
def avg_salary(self): # function to calculate average salary
avg_salary = Employee.Total_Salary / Employee.Emp_Count
return avg_salary
class Full_time_Emp(Employee): # Full Time Employee class inheriting the Employee class
def __init__(self, name, family, salary, department, emp_type):
Employee.__init__(self, name, family, salary, department)
self.emp_type = emp_type
# return emp_type
E1 = Employee("shiva", "Murarishetti", 525000, "ICD")
E2 = Employee("Srija", "Nalluri", 375000, "Dev")
E3 = Employee("Tejaswini", "Katteboina", 350000, "Dev")
F1 = Full_time_Emp("shiva", "Murarishetti", 600000, "ML", "Full-Time")
F2 = Full_time_Emp("Srija", "Nalluri", 675000, "Marketing", "Full-Time")
F3 = Full_time_Emp("Tejaswini", "Katteboina", 510000, "Dev-Java", "Contract")
print("Total Number of Employees are:", Employee.Emp_Count)
print("Total Salary given to Employees:", Employee.Total_Salary)
print("Average Salary is:", F3.avg_salary()) # invoking avg_salary function by using the instance
| true |
fb45eb568372ce1b6e0bb5744da0890ecc000143 | Murarishetti-Shiva-Kumar/Python-Deep-Learning-Programming | /ICP 1/String_Replace.py | 326 | 4.71875 | 5 | # Program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
str = input("Enter the String to be replaced:") # User inputs the string to be replaced
print("String after replacing:", str.replace("python", "pythons")) # Defining the word too be replaced with replace()
| true |
8016fcba9abfd389f6dd04a8429fdb2d3d715964 | curious2015/30-days-of-code-python | /coursera/classes/tamagotchi_game/dog.py | 1,286 | 4.125 | 4 | from coursera.classes.tamagotchi_game.pet import Pet
class Dog(Pet):
sounds = ['Woof', 'Ruff']
def feed(self):
"""
since we are not invoking the method the normal way, with <obj>.methodname,
we have to explicitly pass an instance as the first parameter.
In this case, the variable self in Dog.feed() will be bound to an instance of Dog,
and so we can just pass self: Pet.feed(self).
"""
Pet.feed(self)
print("Arf! Thanks!")
def teach(self, word):
"""
super().teach(word): it easier to read,
it puts the specification of the class that Dog inherits from in just one place, class Dog(Pet).
You just refer to super() and python takes care of looking up that the parent (super) class of Dog is Pet.
"""
super().teach(word)
print("Arf! Thanks for teaching me a new word!")
def mood(self):
if (self.hunger > self.hunger_threshold) and (self.boredom > self.boredom_threshold):
return "bored and hungry"
else:
return "happy"
if __name__ == '__main__':
d1 = Dog("Astro")
print(d1)
d1.feed()
print(d1)
for i in range(6):
d1.clock_tick()
print(d1)
d1.hi()
d1.teach("Gafff")
| true |
338ad1e84c06e711cdddbe4a7a291880c8f33643 | himu999/Python_Basic | /D.loop/F#armstrongnumber.py | 458 | 4.21875 | 4 | """
To check a number is armstrong or not?
153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3
1544 = 1 ^ 4 + 5 ^ 4 + 4 ^ 4 + 4 ^ 4
"""
num = input("Enter the number : ")
digit = int(num)
temp = digit
power = len(num)
summation = 0
while digit != 0:
digit_mod = digit % 10
digit = digit // 10
summation = summation + pow(digit_mod, power)
if summation == temp:
print(num, " : is a armstrong number")
else:
print(num, " : is not a armstrong number")
| true |
a0da6a5b45b0d01b14bd29e75e06323e15a077b5 | himu999/Python_Basic | /I.dictionaries/#O#bank_info.py | 2,168 | 4.3125 | 4 | bank_usr = {"Himu": 132, "Rafi": 933, "Jimi": 456}
print("Welcome to the bank")
print("What do you like to do?")
print(" " + '1.view balance')
print(" " + '2.view all bank info')
print(" " + '3.update balance')
print(" " + '4.exit')
while True:
number = input("Select your operation : ")
if number == '1':
name = input("Enter costumer name : ")
if name in bank_usr.keys():
print(name + " balance is ", bank_usr[name])
else:
print("The user can't found! would you like to add the user to the account?")
cond = input("Give your opinion : ")
if cond == "Yes":
name1 = input("Enter costumer name : ")
balance = input("Enter costumer balance : ")
bank_usr.update({name1: balance})
else:
print("Would you like to exit?")
cond1 = input("Give your opinion : ")
if cond1 == "Yes":
break
elif number == "2":
for k, v in bank_usr.items():
print("User name : ", k + " | " + "Balance =", v)
elif number == "3":
name = input("Enter your name : ")
if name in bank_usr.keys():
print("Do you want to add or subtract form costumer savings?")
cond2 = input("Give your opinion : ")
if cond2 == "Add":
current_balance = bank_usr[name]
amount = int(input("Enter amount you want to add : "))
new_balance = current_balance + amount
bank_usr.update({name: new_balance})
print("Balance updated! costumer current balance is :", bank_usr[name])
elif cond2 == "Subtract":
current_balance = bank_usr[name]
amount = int(input("Enter amount you want to add : "))
new_balance = current_balance - amount
bank_usr.update({name: new_balance})
print("Balance updated! costumer current balance is :", bank_usr[name])
else:
print("There is no such account in the bank database!!")
elif number == "4":
break
| true |
7083f6295d0cb99d561228fe17f5d8ef8e6c8bb9 | himu999/Python_Basic | /G.tuple/#C#update_tuple.py | 252 | 4.40625 | 4 | a = ("a", "b", "c", "d", "e")
b = list(a)
b.append("f")
a = tuple(b)
print(type(a))
print(a)
"""
Tuple is unchangeable but list is changeable that's why we need to convert tuple to list
Thank you
"""
c = list(a)
c.remove("f")
a = tuple(c)
print(a)
| true |
a4f51e9007ef72f42aa2190f33da908a1b585d16 | Herlitzd/simple-python-games | /rock_paper.py | 1,284 | 4.3125 | 4 | #! /usr/bin/python3
from random import randint
plays = dict(r="rock", s="scissor", p="paper")
# We need a list of all of the values in our dictionary for the computer move
# above, it is `key=value`, the value being the right hand side of the `=`
plays_as_list = list(plays.values())
def winner(user, computer):
if(user == computer):
print("draw, go again")
elif(user == "rock" and computer == "scissor"):
print("player wins")
elif(user == "paper" and computer == "rock"):
print("player wins")
elif(user == "scissor" and computer == "paper"):
print("player wins")
else:
print("computer wins")
while True:
# Get a random number between 0 and 2 (inclusive)
random_int = randint(0, 2)
# The computer just picks a random value from
# the possible plays
computer_play = plays_as_list[random_int]
# As the player for a play
play_letter = input("pick a play: r,p,s: ")
# Lookup the letter the player gave us in the dictionary
# so we can get the full value (not just the first letter)
player_play = plays.get(play_letter)
print("Player: "+player_play)
print("Computer: "+computer_play)
# See if there is a winner
winner(player_play, computer_play)
print("\n\n")
| true |
a446f90eb9155d5f0d17c682ddf82cc8b49e9e8b | juniorbraz93/Python | /Exercicios Basicos WikiPython/Estrutura Sequencial/11.py | 519 | 4.1875 | 4 | # Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# a. o produto do dobro do primeiro com metade do segundo .
# b. a soma do triplo do primeiro com o terceiro.
# c. o terceiro elevado ao cubo.
n1 = int(input('Digite o 1º numero: '))
n2 = int(input('Digite o 2º numero: '))
n3 = int(input('Digite o 3º numero: '))
dobro = n1 * 2
triplo = n2 * 3
cubo = n3 ** 2
print('O dobro do ', n1,' é ', dobro)
print('O triplo do ', n2,' é ', triplo)
print('O cubo do ', n3,' é ', cubo)
| false |
31ef892f72e84bb814f3e41ecd475ab74facdd0e | juniorbraz93/Python | /Exercicios Basicos WikiPython/Estrutura De Decisao/25.py | 1,410 | 4.21875 | 4 | # Faça um programa que faça 5 perguntas para uma pessoa sobre um crime.
# As perguntas são:
#"Telefonou para a vítima?"
#"Esteve no local do crime?"
#"Mora perto da vítima?"
#"Devia para a vítima?"
#"Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a
# participação da pessoa no crime. Se a pessoa responder positivamente a 2
# questões ela deve ser classificada como "Suspeita", entre 3 e 4 como
# "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado
# como "Inocente".
clas = 0
print('Responda S - Sim e N - Não')
resp1 = input('Telefonou para a vítima? ')
resp1 = resp1.upper()
if resp1 == 'S':
clas = clas + 1
resp2 = input('Esteve no local do crime? ')
resp2 = resp2.upper()
if resp2 == 'S':
clas = clas + 1
resp3 = input('Mora perto da vítima? ')
resp3 = resp3.upper()
if resp3 == 'S':
clas = clas + 1
resp4 = input('Devia para a vítima? ')
resp4 = resp4.upper()
if resp4 == 'S':
clas = clas + 1
resp5 = input('Já trabalhou com a vítima? ')
resp5 = resp5.upper()
if resp5 == 'S':
clas = clas + 1
print(clas)
print('Sua Classificação sobre a participação da pessoa no crime')
print()
if clas == 0 or clas == 1:
print('Inocente')
elif clas == 2:
print('Suspeita')
elif clas == 3 or clas == 4:
print('Cúmplice')
elif clas == 5:
print('Assassino')
else:
print('ERRO')
| false |
35f5f362c85f4f3a9d9b01539a0b9288d6452a96 | vadik1234/homeworkskills | /hw_bez_nomera(rabota_s_failamy).py/task_3_bez_nomera.py | 399 | 4.4375 | 4 | # Написать генератор, который будет принимать на вход имя файла и
# генерировать построчно(т.е yield каждой строки).
def read_file(file_name):
for row in open(file_name, "r"):
yield row
str_row = read_file("file.txt")
print(str_row.__next__())
print(str_row.__next__())
print(str_row.__next__()) | false |
ccf6a43caae9a6594dcac03569ecba171a57dec7 | christianrua/DataScienceWithPython | /HoneyProduction.py | 1,275 | 4.21875 | 4 | """
Honey Production
Now that you have learned how linear regression works, let’s try it on an example of real-world data.
As you may have already heard, the honeybees are in a precarious state right now. You may have seen articles about the decline of
the honeybee population for various reasons. You want to investigate this decline and how the trends of the past predict the
future for the honeybees.
Note: All the tasks can be completed using Pandas or NumPy. Pick whichever one you prefer
"""
import codecademylib3_seaborn
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv")
print(df.head())
prod_per_year=df.groupby('year').totalprod.mean().reset_index()
X=prod_per_year['year']
X=X.values.reshape(-1,1)
y=prod_per_year['totalprod']
plt.scatter(X,y)
plt.show()
regr=linear_model.LinearRegression()
regr.fit(X,y)
print(regr.coef_,regr.intercept_)
y_predict=regr.predict(X)
plt.scatter(X,y_predict)
plt.show()
X_future=np.array(range(2013,2051))
X_future=X_future.reshape(-1,1)
future_predict=regr.predict(X_future)
plt.clf()
plt.scatter(X_future,future_predict)
plt.show()
| true |
c91a3d9b43b9dc033a3e8ca57691cedf4ef5e73b | NikiDimov/SoftUni-Python-Advanced | /tuples_and_sets_09_21/battle_of_names.py | 584 | 4.125 | 4 | N = int(input())
even_numbers = set()
odd_numbers = set()
for i in range(1, N + 1):
name = input()
current_sum = 0
for el in name:
current_sum += ord(el)
current_sum //= i
if current_sum % 2 == 0:
even_numbers.add(current_sum)
else:
odd_numbers.add(current_sum)
if sum(even_numbers) == sum(odd_numbers):
print(*even_numbers.union(odd_numbers), sep=', ')
elif sum(odd_numbers) > sum(even_numbers):
print(*odd_numbers.difference(even_numbers), sep=', ')
else:
print(*odd_numbers.symmetric_difference(even_numbers), sep=', ')
| false |
43f209540606680e1fb3e3dec82ca9a3a8258c8b | amitshrestha-15/100daysof-code | /Day 3/tresure island.py | 775 | 4.25 | 4 | print("Welcome to Tresure Island.")
print("Your mission is to find the tresure.")
path = input("You are at a crossword, where do you want to go? Right or Left\n").lower()
if path == "left":
choice_2 = input("You see another island. You want to wait for boat or swim across. 'wait' or 'swim'\n").lower()
if choice_2 == "swim":
print ("You are eaten by shark .Game OVer")
if choice_2 == "wait":
choice_3 = input("YOu arrive at the island.THere is 3 doors with color red, yellow, blue.Which do you choose?\n").lower()
if choice_3 == "red":
print("Game over.")
elif choice_3 == "blue":
print("YOu found tresure!")
else:
print("game over")
else:
print("You fell into a hole.game over.")
| true |
e6deeb021aefc3f65df8d461413ef6a7b8117ef9 | ZaneWarner/Algorithms-II | /3-Knapsack/Knapsack.py | 1,748 | 4.21875 | 4 | #This is the third coding assignment for Algorithms 2 from Stanford Lagunita
#The task is to implement dynamic programming algorithms for two instances of the knapsack problem,
#one large and one small
# knapsackSmall = []
# with open("knapsack1.txt", 'r') as file:
# lines = iter(file)
# knapsackSize, nItems = map(int, next(lines).split())
# for line in lines:
# knapsackSmall.append(list(map(int, line.split())))
import sys
knapsackLarge = []
with open("knapsack_big.txt", 'r') as file:
lines = iter(file)
knapsackSize, nItems = map(int, next(lines).split())
for line in lines:
knapsackLarge.append(list(map(int, line.split())))
memo = {}
def Knapsack(size, items):
global memo
nItems = len(items)
#Base cases
if size == 0:
memo[(size, nItems)] = 0
return 0
if nItems == 0:
memo[(size, nItems)] = 0
return 0
# Calculate or look up comparisons for picking and not picking the last item
itemValue, itemWeight = items[-1]
if (size, nItems-1) in memo:
valueUnpicked = memo[(size, nItems-1)]
else:
valueUnpicked = Knapsack(size, items[:-1])
if size-itemWeight >= 0:
if (size-itemWeight, nItems-1) in memo:
valuePicked = memo[(size-itemWeight, nItems-1)] + itemValue
else:
valuePicked = Knapsack(size-itemWeight, items[:-1]) + itemValue
else:
valuePicked = 0
# Compare values and keep what's better
if valuePicked > valueUnpicked:
memo[(size, nItems)] = valuePicked
return valuePicked
else:
memo[(size, nItems)] = valueUnpicked
return valueUnpicked
sys.setrecursionlimit(4000)
v = Knapsack(knapsackSize, knapsackLarge)
print(v) | true |
7e561e508591c6fa99b5caf6580c36930c349651 | dyachoksa/beetroot-lessons | /stocks.py | 896 | 4.125 | 4 | """
Input data:
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
Create a function which takes as input two dicts with structure
mentioned above, then computes and returns the total price of stock.
"""
def calculate_stock(in_stock, in_prices):
total_stock = 0
for item in in_stock:
item_total = in_stock[item] * in_prices.get(item, 0)
total_stock += item_total
return total_stock
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
}
print("Total price in stock:", calculate_stock(stock, prices))
print(stock, prices)
stock["lemon"] = 2
prices["lemon"] = 2.5
print("Total price in stock:", calculate_stock(stock, prices))
print(stock, prices)
| true |
cde22af76394a548c34c6cf39577c416865b9376 | dyachoksa/beetroot-lessons | /tasks/lesson14_1.py | 611 | 4.375 | 4 | """
Write a decorator that prints a function with arguments passed to it.
NOTE! It should print the function, not the result of its execution!
For example:
"add called with 4, 5"
def logger(func):
pass
@logger
def add(x, y):
return x + y
@logger
def square_all(*args):
return [arg ** 2 for arg in args]
"""
def logger(func):
def wrapper(*args, **kwargs):
print(f"{func.__name__} was called with arguments:", args, kwargs)
return func(*args, **kwargs)
return wrapper
@logger
def square_all(*args):
return [arg ** 2 for arg in args]
print(square_all(2, 3, 4))
| true |
42329137802f900c484d960663571e34d9193a48 | dyachoksa/beetroot-lessons | /tasks/lesson12_2.py | 2,737 | 4.25 | 4 | """
Library
Write a class structure that implements a library. Classes:
1) Library - name, books = [], authors = []
2) Book - name, year, author (author must be an instance of Author class)
3) Author - name, country, birthday, books = []
Library class
Methods:
- new_book(name: str, year: int, author: Author) - returns an instance of Book
class and adds the book to the books list for the current library.
- group_by_author(author: Author) - returns a list of all books grouped
by the specified author
- group_by_year(year: int) - returns a list of all the books grouped by the specified year
All 3 classes must have a readable __repr__ and __str__ methods.
Also, the book class should have a class variable which holds the amount of all existing books
"""
import datetime as dt
class Author:
def __init__(self, name, country, birthday):
self.name = name
self.country = country
self.birthday = birthday
self.books = []
def __str__(self):
return self.name
def __repr__(self):
return f"<Author name={self.name} country={self.country}>"
class Book:
def __init__(self, name, year, author):
if not isinstance(author, Author):
raise ValueError("Should be an instance of Author class")
self.name = name
self.year = year
self.author = author
def __str__(self):
return self.name
def __repr__(self):
return f"<Book name={self.name} year={self.year}>"
class Library:
def __init__(self, name):
self.name = name
self.books = []
self.authors = []
def __str__(self):
return self.name
def __repr__(self):
return f"<Library name={self.name}>"
def new_book(self, name, year, author):
if not isinstance(author, Author):
raise ValueError("Should be an instance of Author class")
book = Book(name, year, author)
self.books.append(book)
return book
def get_by_author(self, author):
return [book for book in self.books if book.author.name == author.name]
def get_by_year(self, year):
return [book for book in self.books if book.year == year]
central_library = Library("Central Library")
author1 = Author("Fyodor Dostoyevsky", "Russian Empire", "November 11, 1821")
author2 = Author("J.R.R. Tolkien", "South Africa", "January 03, 1892")
central_library.new_book("Crime and Punishment", 1866, author1)
central_library.new_book("The Fellowship of the Ring", 1954, author2)
print(central_library)
# for book in central_library.books:
for book in central_library.get_by_author(author1):
print("{} by {}, {}".format(
book.name,
book.author.name,
book.year
))
| true |
4d820635eccd2b7df074d56408210470b20498a0 | fhbonini/pands-problems | /analyse.py | 286 | 4.1875 | 4 | # this program calculates BMI body mass index
height = float(input("Enter the height in cm: "))
weight = float(input("Enter the weight: "))
bmi = (weight) / (height * height)
print("Your BMI is ", (bmi*10000))
if bmi < 0.0025:
print("Thats ok")
else:
print("You gonna die")
| true |
115cfbbf18cd1ee2a9211b46d10e8079d37875e9 | collinskoech11/Python-Learning | /Calculator/Calculator.py | 348 | 4.28125 | 4 | #this is a simple calculator
num1 = int(input('Enter the first number: '))
op = input('Enter operator: ')
num2 = int(input('Enter the second number: '))
if op == '+':
print(num1 + num2)
elif op == '-':
print(num1 - num2)
elif op == '*':
print(num1 * num2)
elif op == '/':
print(abs(num1 / num2))
else:
print('invalid operand!') | false |
62dbfa5415c247e10ffc9091f355bb80f590f50f | etsvetanov/python-course | /session_1/if_statement.py | 230 | 4.28125 | 4 | x = 42
if x > 10:
print('x is bigger than 10')
else:
print('x is not bigger than 10')
y = 10
if y > 10:
print('y is bigger than 10')
elif y < 10:
print('y is smaller than 10')
else:
print('y is equal to 10') | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.