limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
if current_speed - limit_speed == 0:
print("no charge")
elif current_speed - limit_speed == 20:
print("charge 20 dollars")
elif current_speed - limit_speed == 40:
print("charge 40 dollars")
How do I make this function work so that it will check the difference between the 2 integers and print out based on it?
I think this is what you are looking for:
limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
if current_speed <= limit_speed:
print("no charge")
else:
print(f'charge: {current_speed - limit_speed}')
You can simply check if one value is greater than the other. (I think you would want this)...
def displayPenalty(limit_speed, current_speed):
if current_speed>limit_speed: print(f"Charge {current_speed-limit_speed} dollars")
else: print("no charge")
see below (I think this is what you are looking for)
limit_speed = 50
def displayPenalty(limit_speed, current_speed):
delta = current_speed - limit_speed
if delta == 0:
print("no charge")
elif 0 < delta <= 20:
print("charge 20 dollars")
elif 20 < delta:
print("charge 40 dollars")
current_speed = int(input("speed now :"))
displayPenalty(limit_speed, current_speed)
Related
def main():
x = abc_to_def(input("What time is it? "))
if x >= "7.0" and x <= "8.0":
print("breakfast time")
elif x >= "12.0" and x <= "13.0":
print("lunch time")
elif x >= "18.0" and x <= "19.0":
print("dinner time")
else:
print()
def abc_to_def(p):
hours, minutes = p.split(":")
if float(int(hours)) + int(minutes)/int(60):
return p
if __name__ == "__main__":
main()
When I run the code in the terminal, everything is correct, but when I run check50 it says my output is "".
#!/usr/local/bin/python3
def main():
y = input("What time is it? ")
x = abc_to_def(y)
if x >= 7.0 and x <= 8.0:
print("breakfast time")
elif x >= 12.0 and x <= 13.0:
print("lunch time")
elif x >= 18.0 and x <= 19.0:
print("dinner time")
else:
print("no food")
def abc_to_def(p):
hours, minutes = p.split(":")
p = float(int(hours)) + int(minutes)/int(60)
return p
if __name__ == "__main__":
main()
The program should display ‘Out of range’ if credits entered are not in the range 0, 20, 40,
60, 80, 100 and 120. There are 28 outcomes. user will input credits to pass, fail ,defer
range_of_credits = [0,20,40,60,80,100,120]
def credit_input(number_of_credits,error_message = 'Integer required'):
while True:
try:
credit= int(input(number_of_credits))#
except ValueError:
print(error_message)
continue
break
return credit
while True:
credits_to_pass= credit_input('Enter the number of credits to pass:')
credits_to_defer= credit_input('Enter the number of credits to Defer:')
credits_to_fail= credit_input('Enter the number of credits to fail:')
if credits_to_pass == 120:
print('Progress')
elif credits_to_pass == 100:
print('Progress(module trailer)')
elif credits_to_pass == 80 or credits_to_pass == 60 or credits_to_fail == 60 or credits_to_pass == 40\
or credits_to_defer ==120 or credits_to_defer ==100 or credits_to_defer==80 or credits_to_defer==60:
print('Do not progress - module retriever')
elif credits_to_fail == 80 or credits_to_fail == 100 or credits_to_fail == 120 or credits_to_pass == 0 or credits_to_pass == 20:
print('Exclude')
credit_input(credits_to_pass,credits_to_defer,credits_to_fail)
I am trying to write a code in Python to where it outputs exact change using the fewest coins and one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. I also have to use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. When I input 45 and ran the code, I got an error saying (Your program produced no output). Here is my code:
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 100:
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(dollar + ' Dollar')
elif dollar > 1:
print(dollar + ' Dollars')
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(quarter + ' Quarter')
elif quarter > 1:
print(quarter + ' Quarters')
elif quarter_change >= 10:
dime = quarter_change // 10
dime_change = quarter_change % 10
if dime == 1:
print(dime + ' Dime')
elif dime > 1:
print(dime + ' Dimes')
elif dime_change >= 5:
nickel = dime_change // 5
nickel_change = dime_change % 5
if nickel == 1:
print(nickel + ' Nickel')
elif nickel > 1:
print(nickel + ' Nickels')
elif nickel_change >= 1:
penny = nickel_change // 1
if penny == 1:
print(penny + ' Penny')
else:
print(penny + ' Pennies')
total = int(input())
if total == 0:
print("No change")
else:
denominations = [(100, "Dollar", "Dollars"), (25, "Quarter", "Quarters"), (10, "Dime", "Dimes"), (5, "Nickel", "Nickels"), (1, "Penny", "Pennies")]
for d in denominations:
coins = total // d[0]
total %= d[0]
if coins > 1:
print(f"{coins} {d[2]}")
elif coins == 1:
print(f"1 {d[1]}")
In this answer, I created a list full of tuples of all the coins and their values in cents. I then created a for loop which runs through all the tuples in the list, dividing the total removing the remainder for the number of coins
like this:
*coins = total // d[0] #returns the number of coins of the current iteration
Then, in order for the loop to continue to the next iteration and do the calculations correctly, I set the total in cents equal to the remainder of the total divided by the current iteration.
like this:
total %= d[0] #can also be written as total = total % d[0]
Then, I take the number of coins and check if the value is greater than one. If the conditional is met, it prints the number of coins followed by the corresponding "plural version" of the word.
like this:
if coins > 1:
print(f"{coins} {d[2]}")
#d[2] refers to the third item in the tuple of the current iteration
Finally, I use an else-if conditional to return 1 plus the "singular version" of the word
like this:
elif coins == 1:
print(f"1 {d[1]}")
#d[1] refers to the second item in the tuple of the current iteration
Your code has numerous problems that needed to be resolved, including the lack of a condition for input values 0 < total_change < 100, problems with indentation (the elif blocks should be aligned), unnecessary variables (you do not need variables like nickel_change and dime_change - total_change is all that matters), and you tried to print dollar + ' Dollar' even though dollar was a numeric variable.
I wanted to improve on the issues in your code and make it, well, functional, but without entirely rewriting your work. So, the basic framework of the code I'm going to provide is the same.
I used the method of recursion. I have the following function with all of your (cleaned) code:
def printCurrency(total_change):
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(str(dollar) + ' Dollar')
printCurrency(total_change-1*100)
elif dollar > 1:
print(str(dollar) + ' Dollars')
printCurrency(total_change-dollar*100)
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(str(quarter) + ' Quarter')
printCurrency(total_change-1*25)
elif quarter > 1:
print(str(quarter) + ' Quarters')
printCurrency(total_change-quarter*25)
elif dollar_change >= 10:
dime = dollar_change // 10
dime_change = dollar_change % 10
if dime == 1:
print(str(dime) + ' Dime')
printCurrency(total_change-1*10)
elif dime > 1:
print(str(dime) + ' Dimes')
printCurrency(total_change-dime*10)
elif dollar_change >= 5:
nickel = dollar_change // 5
nickel_change = dollar_change % 5
if nickel == 1:
print(str(nickel) + ' Nickel')
printCurrency(total_change-1*5)
elif nickel > 1:
print(str(nickel) + ' Nickels')
printCurrency(total_change-nickel*5)
elif dollar_change >= 1:
penny = dollar_change // 1
if penny == 1:
print(str(penny) + ' Penny')
printCurrency(total_change-1*1)
else:
print(str(penny) + ' Pennies')
printCurrency(total_change-penny*1)
Notice how every time a line is printed, the function is ran again but after subtracting out the change we've already processed.
A few examples:
>>> printCurrency(45)
1 Quarter
2 Dimes
>>> printCurrency(101)
1 Dollar
1 Penny
>>> printCurrency(349)
3 Dollars
1 Quarter
2 Dimes
4 Pennies
And to tie this into your original framework with an input...
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 0:
printCurrency(total_change)
Let me know if you have any questions about the changes I've made to your code!
This is more of an answer that zybooks is looking for considering what it has taught up to this point. All that I have done here is decrement total_change each time I go down the list of coins. If there were no coins for that set then print a statement on the previous line.
total_change = int(input())
if total_change <= 0:
print('No change')
else:
dollar = total_change // 100
if dollar == 1:
print(dollar, 'Dollar')
total_change = total_change - (dollar * 100)
elif dollar <= 0:
print(end='')
else:
print(dollar, 'Dollars')
total_change = total_change - (dollar * 100)
quarter = total_change // 25
if quarter == 1:
print(quarter, 'Quarter')
total_change = total_change - (quarter * 25)
elif quarter <= 0:
print(end='')
else:
print(quarter, 'Quarters')
total_change = total_change - (quarter * 25)
dime = total_change // 10
if dime == 1:
print(dime, 'Dime')
total_change = total_change - (dime * 10)
elif dime <= 0:
print(end='')
else:
print(dime, 'Dimes')
total_change = total_change - (dime * 10)
nickel = total_change // 5
if nickel == 1:
print(nickel, 'Nickel')
total_change = total_change - (nickel * 5)
elif nickel <= 0:
print(end='')
else:
print(nickel, 'Nickels')
total_change = total_change - (nickel * 5)
penny = total_change // 1
if penny == 1:
print(penny, 'Penny')
total_change = total_change - (penny * 1)
elif penny <= 0:
print(end='')
else:
print(penny, 'Pennies')
total_change = total_change - (penny * 1)
Edit: New code. Both solutions were working perfectly, but for some reason did not improve my time results and that doesn`t make sense to me just yet.
Seeing my desperation, a friend PMed me his solution, which is working fine with the time given, but somehow fails on this specific input:
9
1 2 2 3 3 4 4 5
3 6 6 7 3 8 8 9 9 10
It gives "9" instead of "5". Any ideas why that could be?
maxNum = int(0)
idxArr = []
def ReadInput():
global array
global firstNum
arr = input().split()
firstNum = int(arr[0])
while int(arr[0]) * 2 + 1 > len(arr):
tempArray = input().split()
arr = arr + tempArray
iterator = int(0)
array = [0] * int(arr[0])
for i in range(1, int(arr[0]) * 2, 2):
tempArray = [0] * 3
tempArray[0] = int(arr[i])
tempArray[1] = int(arr[i + 1])
tempArray[2] = None
array[iterator] = tempArray
iterator+=1
def SortArray(array):
array.sort(key=lambda x: x[1])
array.sort(key=lambda x: x[0])
def MergeDominos(array):
tempNum = int(0)
for item in array:
if (item[2] == None):
iterator = tempNum
counter = int(0)
tempBool = False
try:
while item == array[iterator]:
if (tempBool):
array.pop(iterator)
counter += 1
else:
iterator += 1
counter += 1
tempBool = True
except IndexError:
True == True
if (counter % 2 == 1):
item[2] = counter
tempNum += 1
else:
tempItem = item.copy()
array.insert(tempNum + 1, tempItem)
array[tempNum + 1][2] = int(1)
item[2] = counter - 1
tempNum += 1
else:
tempNum += 1
def GetLengthOfArray(array):
counter = int(0)
for item in array:
counter += item[2]
return counter
def SwitchPlaces(item):
item[0], item[1] = item[1], item[0]
def GetMaxLength(array, tempArray, left, right):
global maxNum
# print("This is temp: ", tempArray)
for i in range(len(array)):
# print("Testing: ", array[i], "Iteration: ", i)
# print("IdxArr: ", idxArr)
if (len(array) <= len(idxArr)):
#print("BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE ")
break
if (i not in idxArr):
#print("Condition:")
if (left == array[i][0]):
#print("LL")
if (i in idxArr):
break
else:
idxArr.append(i)
SwitchPlaces(array[i])
if (len(array) >= len(idxArr)):
tempArray.insert(0, array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (left == array[i][1]):
#print("LR")
if (i in idxArr):
break
else:
idxArr.append(i)
if (len(array) >= len(idxArr)):
tempArray.insert(0, array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (right == array[i][0]):
#print("RL")
if (i in idxArr):
break
else:
idxArr.append(i)
if (len(array) >= len(idxArr)):
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (right == array[i][1]):
#print("RR")
if (i in idxArr):
break
else:
idxArr.append(i)
SwitchPlaces(array[i])
if (len(array) >= len(idxArr)):
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
#else:
# print("No condition BIG OOOF")
ReadInput()
SortArray(array)
MergeDominos(array)
for i in range(len(array)):
#print("iter num: ", i)
tempArray = []
idxArr = []
idxArr.append(i)
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
print(maxNum)
E1: The input is made in this weird way, because the first item of the list gives the number of dominoes, and also, the input can come in multiple rows and then I create list item pairs.
Example input:
5 1 2
1 2
2 3
2
17
2 17
And the dominoes are:
[('1','2'),('1','2'),('2','2'),('2','17'),('2','17')]
Expected result:
5
(3,2)-(2,1)-(1,2)-(2,17)-(17-2)
The following is a rewrite of your solution with one significant change:
if maximum == len(listOfDominos) + len(tempList):
break
This prevents the code from exploring any further once it has a maximum that it knows it can't improve on. For the example input you provided, it reduced the number of searches by 20x:
def find(listOfDominos, tempList):
maximum = len(tempList)
for currentDominoIndex, domino in enumerate(listOfDominos):
if maximum == len(listOfDominos) + len(tempList):
break # we can't do any better, so why try?
remainingDominos = listOfDominos[:currentDominoIndex] + listOfDominos[currentDominoIndex+1:]
if tempList:
backwardDomino = domino[::-1]
head, tail = tempList[0], tempList[-1]
if domino[1] == head[0]:
maximum = max(find(remainingDominos, [domino] + tempList), maximum)
elif backwardDomino[1] == head[0]:
maximum = max(find(remainingDominos, [backwardDomino] + tempList), maximum)
elif domino[0] == tail[1]:
maximum = max(find(remainingDominos, tempList + [domino]), maximum)
elif backwardDomino[0] == tail[1]:
maximum = max(find(remainingDominos, tempList + [backwardDomino]), maximum)
else:
maximum = max(find(remainingDominos, [domino]), maximum)
return maximum
listOfNumbers = input().split()
numberOfDominos = int(listOfNumbers.pop(0))
while numberOfDominos * 2 > len(listOfNumbers):
listOfNumbers += input().split()
listOfDominos = list(zip(listOfNumbers[0::2], listOfNumbers[1::2]))
print(find(listOfDominos, []))
Give this a try to see if it improves performance without introducing any bugs in the process.
Try this solution:
def solution(dominoes):
if len(dominoes) == 0:
return 0
def get_sequence(d, sol=None):
if sol is None:
sol = []
if len(d) == 0:
return
for i in range(len(d)):
rest = d[:i] + d[i+1:]
d1, d2 = d[i], d[i][::-1]
if d1 == d2:
if (not sol) or (sol[-1][1] == d1[0]):
yield sol + [d1]
yield from get_sequence(rest, sol + [d1])
else:
if (not sol) or (sol[-1][1] == d1[0]):
yield sol + [d1]
yield from get_sequence(rest, sol + [d1])
if (not sol) or (sol[-1][1] == d2[0]):
yield sol + [d2]
yield from get_sequence(rest, sol + [d2])
return(len(max(get_sequence(dominoes), key=len)))
dominoes = [('1','2'),('1','2'),('2','2'),('2','17'),('2','17')]
print(solution(dominoes))
Prints:
5
Simple football simulation for my class project. I simplified a lot of the rules and aspects of the game, so everything isn't very accurate compared to an actual football game. However, When I try running my function, only the line of code which prints the name of the QB throwing to the receiver prints. For example when I run it only, "Jared Goff throws to Brandin Cooks for 33 yards!" shows up in the display. How can I get the whole function to run/print? Not sure where I went wrong.
import random
rams_qb = ["Jared Goff"]
patriots_qb = ["Tom Brady"]
rams_receivers = ["Cooper Kupp", "Brandin Cooks"]
patriots_receivers = ["Julian Edelman", "Josh Gordon"]
rams_score = 0
patriots_score = 0
quarter_time = 900
def remaining_time():
global quarter_time
global rams_score
global patriots_score
if quarter_time > 0:
if random.randint(0,100) < 50:
return rams_possesion()
else:
return patriots_possesion()
elif quarter_time == 0:
if rams_score > patriots_score:
print ("Rams Win!")
else:
print ("Patriots Win!")
def rams_possesion():
global quarter_time
global rams_score
rams_ball_position = 50
rams_downs = 1
if rams_ball_position == rams_ball_position + 10:
rams_downs = 1
else:
rams_downs += 1
if rams_ball_position == 100:
rams_score == rams_score + 6
print ("RAMS TOUCHDOWN!")
return rams_fieldgoal
if rams_downs <= 4:
rams_yardage_gained = random.randint(0,50)
print ((random.choice(rams_qb)),("throws to"),
(random.choice(rams_receivers)),("for"),(str(rams_yardage_gained)),
("yards!"))
rams_ball_position == rams_ball_position + rams_yardage_gained
quarter_time -= random.randint(0,30)
if rams_downs >= 5:
return patriots_possesion
def rams_fieldgoal():
global rams_score
if random.randint(0,100) < 83:
rams_score == rams_score + 1
print ("RAMS SCORE FIELDGOAL!")
else:
print ("RAMS MISS FIELDGOAL")
return patriots_possesion
def patriots_possesion():
global patriots_score
patriots_ball_position = 50
patriots_downs = 1
if patriots_ball_position == patriots_ball_position + 10:
patriots_downs = 1
else:
patriots_downs += 1
if patriots_ball_position == 100:
patriots_score == patriots_score + 6
print ("PATRIOTS TOUCHDOWN!")
return patriots_fieldgoal
if patriots_downs <= 4:
patriots_yardage_gained = random.randint(0,50)
print ((random.choice(patriots_qb)),("throws to"),
(random.choice(patriots_receivers)),("for"),(str(patriots_yardage_gained)),
("yards!"))
patriots_ball_position == patriots_ball_position +
patriots_yardage_gained
if patriots_downs >= 5:
return rams_possesion()
def patriots_fieldgoal():
global patriots_score
if random.randint(0,100) < 87:
patriots_score == patriots_score + 1
print ("PATRIOTS SCORE FIELDGOAL!")
else:
print ("PATRIOTS MISS FIELDGOAL")
return rams_possesion()
remaining_time()
My best guess here is that your comparisons are not taking into account the fact that the values can go over the target. For example, when checking yardage, you're checking for equality to 100, but you aren't guaranteeing that the value won't go over 100. You have a similar bug with checking if the quarter_time == 0 when it should be <= 0 to make sure it triggers.
I can't tell you if changing these comparisons will fix your program, but try these changes and comment how the behavior changes.