Skip to main content

Rock paper scissors

0 likes • Nov 19, 2022 • 0 views
Python
Loading...

More Python Posts

Number guessing game

0 likes • Nov 19, 2022 • 0 views
Python
""" Number Guessing Game
----------------------------------------
"""
import random
attempts_list = []
def show_score():
if len(attempts_list) <= 0:
print("There is currently no high score, it's yours for the taking!")
else:
print("The current high score is {} attempts".format(min(attempts_list)))
def start_game():
random_number = int(random.randint(1, 10))
print("Hello traveler! Welcome to the game of guesses!")
player_name = input("What is your name? ")
wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))
// Where the show_score function USED to be
attempts = 0
show_score()
while wanna_play.lower() == "yes":
try:
guess = input("Pick a number between 1 and 10 ")
if int(guess) < 1 or int(guess) > 10:
raise ValueError("Please guess a number within the given range")
if int(guess) == random_number:
print("Nice! You got it!")
attempts += 1
attempts_list.append(attempts)
print("It took you {} attempts".format(attempts))
play_again = input("Would you like to play again? (Enter Yes/No) ")
attempts = 0
show_score()
random_number = int(random.randint(1, 10))
if play_again.lower() == "no":
print("That's cool, have a good one!")
break
elif int(guess) > random_number:
print("It's lower")
attempts += 1
elif int(guess) < random_number:
print("It's higher")
attempts += 1
except ValueError as err:
print("Oh no!, that is not a valid value. Try again...")
print("({})".format(err))
else:
print("That's cool, have a good one!")
if __name__ == '__main__':
start_game()

Display Calendar

0 likes • May 31, 2023 • 0 views
Python
import calendar
# Prompt user for year and month
year = int(input("Enter the year: "))
month = int(input("Enter the month: "))
# Create a calendar object
cal = calendar.monthcalendar(year, month)
# Display the calendar
print(calendar.month_name[month], year)
print("Mon Tue Wed Thu Fri Sat Sun")
for week in cal:
for day in week:
if day == 0:
print(" ", end="")
else:
print(str(day).rjust(2), " ", end="")
print()

Using logic with sets

0 likes • Nov 18, 2022 • 0 views
Python
#Sets
U = {0,1,2,3,4,5,6,7,8,9}
P = {1,2,3,4}
Q = {4,5,6}
R = {3,4,6,8,9}
def set2bits(xs,us) :
bs=[]
for x in us :
if x in xs :
bs.append(1)
else:
bs.append(0)
assert len(us) == len(bs)
return bs
def union(set1,set2) :
finalSet = set()
bitList1 = set2bits(set1, U)
bitList2 = set2bits(set2, U)
for i in range(len(U)) :
if(bitList1[i] or bitList2[i]) :
finalSet.add(i)
return finalSet
def intersection(set1,set2) :
finalSet = set()
bitList1 = set2bits(set1, U)
bitList2 = set2bits(set2, U)
for i in range(len(U)) :
if(bitList1[i] and bitList2[i]) :
finalSet.add(i)
return finalSet
def compliment(set1) :
finalSet = set()
bitList = set2bits(set1, U)
for i in range(len(U)) :
if(not bitList[i]) :
finalSet.add(i)
return finalSet
def implication(a,b):
return union(compliment(a), b)
###########################################################################################
###################### Problems 1-6 #######################################
###########################################################################################
#p \/ (q /\ r) = (p \/ q) /\ (p \/ r)
def prob1():
return union(P, intersection(Q,R)) == intersection(union(P,Q), union(P,R))
#p /\ (q \/ r) = (p /\ q) \/ (p /\ r)
def prob2():
return intersection(P, union(Q,R)) == union(intersection(P,Q), intersection(P,R))
#~(p /\ q) = ~p \/ ~q
def prob3():
return compliment(intersection(P,R)) == union(compliment(P), compliment(R))
#~(p \/ q) = ~p /\ ~q
def prob4():
return compliment(union(P,Q)) == intersection(compliment(P), compliment(Q))
#(p=>q) = (~q => ~p)
def prob5():
return implication(P,Q) == implication(compliment(Q), compliment(P))
#(p => q) /\ (q => r) => (p => r)
def prob6():
return implication(intersection(implication(P,Q), implication(Q,R)), implication(P,R))
print("Problem 1: ", prob1())
print("Problem 2: ", prob2())
print("Problem 3: ", prob3())
print("Problem 4: ", prob4())
print("Problem 5: ", prob5())
print("Problem 6: ", prob6())
'''
Problem 1: True
Problem 2: True
Problem 3: True
Problem 4: True
Problem 5: True
Problem 6: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
'''

Calculator

0 likes • Nov 19, 2022 • 0 views
Python
""" Calculator
----------------------------------------
"""
def addition ():
print("Addition")
n = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 0
while n != 0:
ans = ans + n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def subtraction ():
print("Subtraction");
n = float(input("Enter the number: "))
t = 0 //Total number enter
sum = 0
while n != 0:
ans = ans - n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def multiplication ():
print("Multiplication")
n = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 1
while n != 0:
ans = ans * n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def average():
an = []
an = addition()
t = an[1]
a = an[0]
ans = a / t
return [ans,t]
// main...
while True:
list = []
print(" My first python program!")
print(" Simple Calculator in python by Malik Umer Farooq")
print(" Enter 'a' for addition")
print(" Enter 's' for substraction")
print(" Enter 'm' for multiplication")
print(" Enter 'v' for average")
print(" Enter 'q' for quit")
c = input(" ")
if c != 'q':
if c == 'a':
list = addition()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 's':
list = subtraction()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 'm':
list = multiplication()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 'v':
list = average()
print("Ans = ", list[0], " total inputs ",list[1])
else:
print ("Sorry, invilid character")
else:
break

Print "X" pattern

0 likes • Nov 19, 2022 • 0 views
Python
def print_x_pattern(size):
i,j = 0,size - 1
while j >= 0 and i < size:
initial_spaces = ' '*min(i,j)
middle_spaces = ' '*(abs(i - j) - 1)
final_spaces = ' '*(size - 1 - max(i,j))
if j == i:
print(initial_spaces + '*' + final_spaces)
else:
print(initial_spaces + '*' + middle_spaces + '*' + final_spaces)
i += 1
j -= 1
print_x_pattern(7)

ZapFinder

0 likes • Jan 23, 2021 • 0 views
Python
import subprocess #for the praat calls
import os #for ffmpeg and the pause call at the end
#Even if we wanted all videos being rendered asynchronously, we couldn't see progress or errors
import glob #for the ambiguous files
import tempfile
audioFileDirectory = 'Audio Files'
timeList = {}
fileList = glob.glob(audioFileDirectory + '\\*.wav')
pipeList = {}
for fileName in fileList:
arglist = ['Praat.exe', '--run', 'crosscorrelateMatch.praat', 'zeussound.wav', fileName, "0" , "300"]
print(' '.join(arglist))
pipe = subprocess.Popen(arglist, stdout=subprocess.PIPE)
pipeList[fileName[len(audioFileDirectory)+1:-4]] = pipe #+1 because of back slash, -4 because .wav
#for fileName, pipe in pipeList.items():
# text = pipe.communicate()[0].decode('utf-8')
# timeList[fileName] = float(text[::2])
for fileName, pipe in pipeList.items():
if float(pipe.communicate()[0].decode('utf-8')[::2]) > .0003: #.000166 is not a match, and .00073 is a perfect match. .00053 is a tested match
arglist = ['Praat.exe', '--run', 'crosscorrelate.praat', 'zeussound.wav', audioFileDirectory + '\\' + fileName + '.wav', "0" , "300"]
print(' '.join(arglist))
text = subprocess.Popen(arglist, stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
timeList[fileName] = float(text[::2])
clipLength = 10
for fileName, time in timeList.items():
arglist = ['ffmpeg', '-i', '"'+fileName+'.mp4"', '-ss', str(time-clipLength), '-t', str(clipLength*2), '-acodec', 'copy' , '-vcodec', 'copy', '"ZEUS'+ fileName + '.mp4"']
print(' '.join(arglist))
os.system(' '.join(arglist))
tempFile = tempfile.NamedTemporaryFile(delete=False)
for fileName in glob.glob('ZEUS*.mp4'):
tempFile.write(("file '" + os.path.realpath(fileName) + "'\n").encode());
tempFile.seek(0)
print(tempFile.read())
tempFile.close()
arglist = ['ffmpeg', '-safe', '0', '-f', 'concat', '-i', '"'+tempFile.name+'"', '-c', 'copy', 'ZeusMontage.mp4']
print(' '.join(arglist))
os.system(' '.join(arglist))
os.unlink(tempFile.name) #Delete the temp file
#print(timeList)
os.system('PAUSE')