How can I solve this problem without using lists? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Problem: You're a swimmer, and you want to compare all of your race times to find the fastest one. Write a program that continuously takes race times as doubles from standard input, until the input is "no more races," at which point it should print out the time of your fastest race.
The answer I found on another thread was using lists like:
list1 = []
race_time = input("Enter a race time or type no more races to quit: ")
while race_time != "no more races":
list1.append(float(race_time))
race_time = input("Enter a race time or type no more races to quit ")
print(min(list1))
The problem is from if-else, and loops chapter and lists aren't introduced to us yet. How would I store the race times and compare them?

You can just store the best time that you've seen so far and whenever the new time is better overwrite the old one:
import math
best_time = math.inf
[... your code ...]
while ...:
if race_time < best_time:
best_time = race_time

Without list, it will be a little bit difficult to store all races. But as you are only looking for the speedest race:
race_time = input("Enter a race time or type no more races to quit: ")
best_time=float(race_time)
while race_time != "no more races":
race_time = input("Enter a race time or type no more races to quit ")
if race_time != "no more races":
race_time=float(race_time)
if race_time<best_time:
best_time=race_time
print(best_time)

Related

How do I add input to a if funtion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How exactly do I add an additional input to this if function, or atleast add a function which will allow me to give the user another option. Thank you, in advance.
ask = input ("Would you like to 1 input an existing number plate \n or 2 view a random number? 1 or 2: ")
if ask == "1":
print("========================================================================")
ask = input()("Please enter it in such form (XX00XXX): " )
If this ask = input()("Please enter it in such form (XX00XXX): " ) is actually in your code, just changing it to ask = input("Please enter it in such form (XX00XXX): " ) will fix your problem. You had one extra pair of brackets.
DISCLAIMER: This works in Python 3.x
For Python 2, use raw_input("Your question") instead of input("Your question").
As an answer to the question in your own answer:
What is wrong in this code?
ask = input ("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
if int(ask) == 1:
print("========================================================================")
while True:
ask2 = input("Please enter it in such form (XX00XXX): " ).lower()
if re.ask3("[a-z]{2}[0-9]{2}[a-z]{3}",ask2):
print("Verification Success")
break
else:
print("Verification Failed")
You have to indent the while loop once (default is 4 spaces) and everything inside of the while loop twice (default 8 spaces). When pasting a code like this, make sure to include all code needed to run. In this case, show your import re (I had to find out myself you imported that).
I hope I helped.
You are comparing an int(1) to str("1").
It should be
if int(ask) == 1:
# rest of your code
or you can use raw_input() function which returns a string value

How could I loop a code involving a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm fairly new to python and I was wondering if someone was able to help me with looping this block of code and I did looping in the past but this one involves a list element having to change every time 1 through to 10 and I don't know how I could make that change.
print ("Question 1: ")
print (questions[0])
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(questions[0]):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
The closest way to do so while maintaining your code is the following
for index, question in enumerate(questions):
print ("Question {}: ".format(index+1))
print (question)
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(question):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
Note that you should avoid using eval because it is unsafe. Recommended alternatives are to either make a dictionary with pre-baked questions and answers, e.g.
questions = {'What is 5 + 4?' : 9,
'What is 3 - 1?' : 2}
Or programmatically come up with questions and answers.

Write a Python program that repeatedly asks the user to input coin values until the total amount matches a target value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
However, I realized that I don't actually know how to do this myself without examining every possible combination of coins. There has to be a better way of solving this problem, but I don't know what the generic name for this type of algorithm would be called, and I can't figure out a way to simplify it beyond looking at every solution.
I was wondering if anybody could point me in the right direction, or offer up an algorithm that's more efficient.
You can try something like this:
MaxAmount = 100
TotalAmount = 0
while TotalAmount < MaxAmount:
#Here if you want it to be more precise on decimals change int(raw_input("Amount: ")) to float(raw_input("Amount: "))
EnteredAmount = float(raw_input("Amount: "))
if EnteredAmount > MaxAmount:
print "You can not go over 100"
elif TotalAmount > MaxAmount:
#You can go two ways here either just set TotalAmount to MaxAmount or just cancel the input
print "You can not go over 100"
elif EnteredAmount <= MaxAmount:
TotalAmount = TotalAmount + EnteredAmount
print TotalAmount
print "You have reached the total amount of ", MaxAmount
Could use a loop into an if - elif - else statements
e.g. populate a variable with your amount, then using this for the loop condition keep asking to take away coin amounts until you reach 0

Python vending machine snacks and drinks [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Hi guys I have been trying to create a working python vending machine for over a month now and it doesn't look like I am making any progress. If somebody could help me that could be great :) Here is my program so far:
print ("Welcome to the Vending Machine\n")
total = 0
dr = 1
sn = 3
money=int(input("How much money do you want to insert"))
print ("Prices: Drinks: £1, Snacks: £3\n")
Drinks = {'Coke','Pepsi','Orange Juice', 'Apple Juice','Water'}
Snacks = {'Chocolate', 'Snickers','Twix','Peanuts','Crisp'}
state = 'subtotal'
while total <= money:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
if choice in Drinks:
total += dr
elif choice in Snacks:
total += sn
else:
state = 'total'
print("\n\nThat will be a",state,"of £",total)
else:
print("You have exceeded your inserted money good bye")
I'm trying to make the code reject invalid input and stop when the user has gone over his spending limit.
There is only one problem with this when I run this. So, here is the fix with some explanation so you can learn something. It may seem like a simple mistake but we all make them at some point and eventually, indenting will be second nature.
Indents
Unlike some langues, in Python the indentation matters. A lot. Let's look at your first if statement.
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
Can you see the problem? After an if statment, or more precisely, after the :, we need to indent everything else that we want to be carried out by the if statement otherwise Python won't know where to stop! So by making this simple change:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
We have no more error and your program now runs. Notice the indents? Just check that they are always right.

Nested Choices in a python program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of random numbers. I have it set up (I think) so that typing a number that's not in the first list of choices will just print "Bad choice" and try getting the number again.
[Edit] After taking the advice of the answer I changed a couple of the inputs to raw inputs. And I changed the structure of the program. It now works perfectly except it still prints out "Bad Choice" even after a success.
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
choices = {1:SelectionSorter,2:ComparisonSorter}
print "Please enter the type of sort you would like to perform."
print "1. Selection Sort\n2. Comparison Sort"
while(True):
try:
choice=input("Your choice: ")
for i in range(2):
if(choice==i+1):
choice2=fileOrRandom()
if(choice2=='A'):
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif(choice2=='B'):
num = input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
else:
raise Exception
else:
raise Exception
break
except Exception:
print "Bad Choice"
My issue is that it works as expected for the first part where it will return "bad choice" for a number that's not in the list, and it will get fileOrRandom(), but it still prints "Bad Choice" when selecting good values that should print out my results because sorter.timedSort(sorter.sort) executes my sorting algorithm and prints out a bunch of other things to the screen. Am I just missing something simple or is there a better way to deal with these nested options in a Python program?
use raw_input()
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
your while loop should look like this (after fixing the indentation)
while True :
choice=raw_input("Your choice: ")
for i in range(2):
if choice==i+1 and fileOrRandom()=="A" :
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif choice==i+1 and fileOrRandom()=="B" :
num = raw_input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
elif choice in ['q','Q']: break
else: print "Bad choice"

Categories