The distance a vehicle travels can be calculated as follows:
distance = speed * time
Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output:
What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3
Hour Distance Traveled
1 : 40
2 : 80
3 : 120
I've gotten everything done so far but can't manage to get the table to come out properly, as shown in the example table at the first hour (1) it should start at 40 but instead it starts at 120. Can someone help me fix the code? forgot to mention it should work for any value the user enters such as if someone was going 50 mph in 5 hours
g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))
if time <= 0 or speed <= 0:
print('Invalid Hours and mph must be greater than 0')
else:
for t in range(time):
distance = speed * time
print(t + 1,':', distance)
time = time * 2
g = 'n'
print('End')
Just change 2 things in your program. First, there's no need to double the time inside for loop, Second use variable t instead of time to calculate distance.
g = 'y'
while g == 'Y' or g == 'y':
speed = int(input('Enter mph: '))
time = int(input('Enter hours: '))
if time <= 0 or speed <= 0:
print('Invalid Hours and mph must be greater than 0')
else:
for t in range(time):
distance = speed * (t+1) // Use t+1 instead of time
print(t + 1,':', distance)
# time = time * 2 // No need to double the time
g = 'n'
print('End')
Input:
40
3
Output:
(1, ':', 40)
(2, ':', 80)
(3, ':', 120)
End
You need to remove the commas from the print line, and print out the numbers in string format and concat it to the string colon like:
print(str(t + 1) + ':' + str(distance))
You also need to increment the time by one not multiply by 2
time = time + 1
Your output distance also can be fixed by calculating it based on t instead of time
distance = speed * (t+1)
Related
A standard science experiment is to drop a ball and see how high it bounces. Once the “bounciness” of the ball has been determined, the ratio gives a bounciness index. For example, if a ball dropped from a height of 10 meters bounces 6 meters high, the index is 0.6 and the total distance traveled by the ball is 16 meters after one bounce. If the ball were to continue bouncing, the distance after two bounces would be 10 meters + 6 meters + 6 meters + 3.6 meters = 25.6 meters. Note that distance traveled for each successive bounce is the distance to the floor plus 0.6 of that distance as the ball comes back up.
Write a program that lets the user enter the initial height of the ball and the number of times the ball is allowed to continue bouncing. Output should be the total distance traveled by the ball.
What I have so far is :
def Bounce_Calculator():
initialHeight = float(input( "What is the initial height? "))
bouncesAllowed = float(input( "What is the amount of bounces allowed: "))
bounceIndex = float(input("What is the bounce index : "))
n=0
while n <= bouncesAllowed :
newHeight = float(initialHeight*bounceIndex)
heightDifference = initialHeight-newHeight
bounceSum = (newHeight/1-bounceIndex)
totalDistance = ((((2*bounceSum) + initialHeight )))
print ("The total distance is : ", totalDistance)
n=bouncesAllowed + 1
Bounce_Calculator()
This is a classic recursion process.
There are three approaches that one might take:
recursive method. (needs end condition)
while loop. (needs end condition)
for loop. (finishes at the end of the loop)
Using method 3 from the above this works:
def Bounce_Calculator(initial_height:float, bouncyness:float,
len_travelled=0):
''' takes height and bouncyness and returns then next bounce
'''
next_bounce = initial_height * bouncyness
len_travelled += initial_height + bouncyness
return next_bounce, len_travelled
# initial conditions
len_trav = 0
list_of_cycles = [0]
h = 100
b = 0.6
# the loop
for i in range(1, 10):
h, len_trav = Bounce_Calculator(h, b, len_trav)
list_of_cycles.append(len_trav)
percent_moved = (list_of_cycles[i]-list_of_cycles[i-1]) / list_of_cycles[i]
if percent_moved < 0.01:
# stopped bouncing
break
print('bounces', list_of_cycles)
print('total length travelled', len_trav)
result:
bounces [0, 100.6, 161.2, 197.79999999999998, 219.99999999999997, 233.55999999999997, 241.93599999999998, 247.20159999999998, 250.60096, 252.880576]
total length travelled 252.880576
The problem:
There are 3 paths where only one leads home.
The first path gets you lost for 3 days, then you're back to the beginning where you have to pick another path.
The second path gets you lost for 2 days, then you're back at the beginning and you have to pick another path.
The last door leads you home in 1 day.
Basically you keep going until you pick the last path. I'm trying to find the average time it takes to get home by simulating 1000 tries.
Here is what I have thus far:
days=0
for i in range(1000):
door=["a","b","c"]
numpy.random.choice(path)
if numpy.random.choice(path)=="a":
days=+2
if numpy.random.choice(path)=="b":
days=+3
if numpy.random.choice(path)=="c":
days=+1
print(steps)
As is, my code will just print out a value from 1-3 as the days.
I'm having trouble figuring out how to pick one and then accumulate it into the days and then restarting the loop until it picks path C.
I've done research and think a while loop might work but I don't know how to apply that.
You can use a while loop that keeps iterating while you are stuck and then when door 'a' is selected it adds the 1 to get home but then the person is no longer stuck so it drops out of the while loop. Then before entering the while loop again, just set stuck = True and the process continues always adding to the total number of days, then at the end just take the average.
import numpy
days=0
door=["a","b","c"]
N = 1000
for i in range(N):
stuck = True
while stuck:
if numpy.random.choice(door)=="a":
days += 2
if numpy.random.choice(door)=="b":
days += 3
if numpy.random.choice(door)=="c":
days += 1
stuck = False
print('Average number of days taken to get home: ', days / N)
I hope this helps!
Here's the code you're looking for:
import numpy
def runOnce():
days = 0
door=["a","b","c"]
while(True):
path = numpy.random.choice(door)
if path=="a":
days+=2
if path=="b":
days+=3
if path=="c":
days+=1
return days
total = 0
for i in range(1000):
total += runOnce()
print(total / 1000.0)
This code must solve your problem:
import random
doors = ['a', 'b', 'c']
total_days = 0
runs = 1000
for i in range(runs):
days = 0
choice = None
while choice != 'c':
choice = random.choice(doors)
if choice == 'a':
days += 2
if choice == 'b':
days += 3
if choice == 'c':
days += 1
total_days += days
avg_days = total_days / runs
print(avg_days)
I'm not quite sure on your rules, but this is my attempt
import numpy as np
def choose_path():
p =np.random.randint(3)
#print("Path = {}".format(p))
return p
N = 100000
days=0.0
for i in range(N):
#make sure you don't take the wrong path twice
taken = [False, False, False]
path = choose_path()
while(path != 2):
if(path==0):
if(not(taken[path])):
taken[path] = True
days += 2.0
if(path==1):
if(not(taken[path])):
taken[path] = True
days += 3.0
path = choose_path()
days += 1.0
# print("Days = {}".format(days))
print("Average for {} iterations = {}".format(N, days/N))
In contrast to the some of the other codes my guy doesn't take the same route twice. I'm not sure how you problem is defined. My solution seems to be 3.5.
Some of the mistakes you made are:
=+ is an assignment of a positive number a = +3 or a = -3
+= is an increment a = a + 3 <=> a += 3
you define door, but never use it
you never define steps but you use it
I think you should come up with an algorithm first and then implement it.
There are a few problems with your code. For example, you define a door list of possible choices, but then you pass path to the choice function. At the end of your program you print steps, but that's not defined anywhere. Instead, you should be printing days, or days / 1000. You need to pay attention to things like that when you're programming!
As others have shown, you need to do this with two loops. Each iteration of the outer loop performs a trial. The inner loop chooses paths until you get home and adds the day counts to the current total.
In your code, each if test generates a fresh random choice on top of the one you make at the start of the loop. That's not right. Just make the choice at the top of the loop, determine how many days to add to the count, and if you're home, break out of the loop.
We can do this in a simpler way. Rather than choosing from 'a', 'b', or 'c', just choose from 1, 2, or 3, the number of days each path takes. And as I said earlier, there's no need to use Numpy for this, we can just call the random module functions directly instead of letting Numpy do it on our behalf.
Here's a short demo.
from random import randint
trials = 10000
days = 0
for n in range(trials):
while True:
path = randint(1, 3)
days += path
if path == 1:
break
print(days, days / trials)
typical output
59996 5.9996
We can get a more accurate estimate to the true expected time by performing multiple runs and averaging the results. We could do that by wrapping the previous code in an extra loop, but it makes the code more readable if instead we wrap the old code in a function, and call that function in a loop. Like this:
from random import randint
def sim(trials):
days = 0
for n in range(trials):
while True:
path = randint(1, 3)
days += path
if path == 1:
break
return days
num = 10
trials = 10000
total = 0
for i in range(num):
days = sim(trials)
x = days / trials
print(i, x)
total += x
print('Final', total / num)
typical output
0 5.9732
1 6.007
2 6.0555
3 5.9943
4 5.9964
5 5.9514
6 6.0689
7 6.0457
8 5.9859
9 5.9685
Final 6.00468
It looks like the true expected value is 6 days. Actually, it's not hard to show that mathematically.
Let d equal the expected number of days to get home. 1/3 of the time we get home in 1 day, 1/3 of the time we get back to the start in 2 days and so we still have d days before we get home, and 1/3 of the time we get back to the start in 3 days and so, once again we still have d days before we get home.
We can put that into an equation:
d = (1/3)*1 + (1/3)*(2 + d) + (1/3)*(3 + d)
3*d = 1 + 2 + d + 3 + d
3*d = 6 + 2*d
d = 6
#This program will calculate distance traveled
#ask for miles traveled
speed = int(input("Enter speed in mph: "))
#ask for hours traveled
hour = int(input("Enter hours traveled: "))
increment = 1
def main ():
print ('Hours\t Distance')
print ('----------------')
for hour in range(speed, hour, increment):
distance = speed * hour
print(hour, '\t' , distance)
main()
I know I'm looking right at the problem and just not seeing it. I can get the column headers and the separator to print, but the for statement will not run. Any suggestions?
Thank you in advance.
Your range needs to start at 0 (or maybe increment if you don't want 0), not speed
for hour in range(0, hour, increment):
distance = speed * hour
print(hour, '\t' , distance)
If you want to skip the 0, you probably need this
for hour in range(increment, hour+increment, increment):
distance = speed * hour
print(hour, '\t' , distance)
I'm running into a dilemma with a for i in range(x) loop not iterating. The purpose of my program is to simulate foxes and rabbits interacting with one another on an island and printing out the populations of each respective animal after each day. I know the equations are correct, the problem I am having is my loop will only run once for a large range.
My code:
def run_simulation():
print()
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(input("Enter the initial number of foxes: "))
print()
RABBITS = eval(input("Enter the initial number of rabbit: "))
print()
DAYS = eval(input("Enter the number of days to run the simulation: "))
print()
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
for i in range(DAYS):
RABBITS_START = round((RABBIT_BIRTH_RATE * RABBITS) - (INTERACT * RABBITS * FOXES))
FOXES_START = round((INTERACT * SUCCESS * RABBITS * FOXES) - (FOX_BIRTH_RATE * FOXES))
y = y + x
print (y,"\t",(RABBITS_START+RABBITS),"\t","\t",(FOXES_START+FOXES),"\t")
run_simulation()
When this is run with an example of 500 Foxes, 10000 Rabbits, and 1200 days, my output will look like
Day Rabbits Foxes
0 10000 500
1 10050 498
With the second output line repeating the remaining 1199 times.
Any help would be greatly appreciated I cannot figure out what I am doing wrong.
You set RABBITS and RABBIT_BIRTH_RATE at the beginning. Then, on every loop iteration, you set RABBITS_START to some formula involving these two numbers. You never change the value of RABBITS or RABBIT_BIRTH_RATE or FOXES or anything, so every time you run through the loop, you're just calculating the same thing again with the same numbers. You need to update the values of your variables on each iteration --- that is, set a new value for RABBITS, FOXES, etc.
The biggest issue for me is what you named your "change in rabbits/foxes". RABBITS_START sounds like an initial count for RABBITS, but it's not. This is why I renamed it to RABBITS_DELTA, because really it's calculating the CHANGE in rabbits for each day.
I think I got it. At the very least this behaves more like a simulation now:
def run_simulation():
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(str(input("Enter the initial number of foxes: ")))
RABBITS = eval(str(input("Enter the initial number of rabbits: ")))
DAYS = eval(str(input("Enter the number of days to run the simulation: ")))
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
count = 0
while count < DAYS:
RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
- (INTERACT * RABBITS * FOXES))
FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
- (FOX_BIRTH_RATE * FOXES))
y = y + x
RABBITS += RABBITS_DELTA
FOXES += FOXES_DELTA
print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")
count += 1
run_simulation()
I'm going to take a wild stab at trying to interpret what you mean:
for i in range(1, DAYS + 1):
rabbit_delta = ... # RABBITS_START
fox_delta = ... # FOXES_START
RABBITS += rabbit_delta
FOXES += fox_delta
print(i, "\t", RABBITS, "\t\t", FOXES, "\t")
edited based on others' answers. (Wild stab is less wild.)
See BrenBarn's answer for an explanation in prose.
In python: how do I divide an int received by a user from a list while every time it runs in the for loop I need to divide the value I received from the round before in the next round?
This is my code:
a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
for i in coin_bills:
hef = b - a
print (hef / i), '*', i
else:
print 'pay up!'
Example: a=370 b=500 ---> b-a=130
Now in the loop I will receive (when i=100) 1, and (when i=50) I will receive 2 but I want in the second round (when i=50) to divide 30 (130[=b-a]- 100[=answer of round 1*i]) by 50.
What do I need to change in the code?
Thanks!
You just need to subtract the amount of change you give back at each step from the total amount of change you're returning. It's much easier to see if you change your variable names to something meaningful:
price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
You could also clear up the output a bit by only printing the coins/bills that you actually return. Then the inner loop might look something like this:
for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
OK, I'm assuming that you're trying to calculate change for a transaction using a number of types of bills.
The problem is that you need to keep a running tally of how much change you have left to pay out. I used num_curr_bill to calculate how many of the current bill type you're paying out, and your hef I changed to remaining_change (so it would mean something to me) for the remaining change to pay.
a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]
if b>=a:
# Calculate total change to pay out, ONCE (so not in the loop)
remaining_change = b-a
for i in coin_bills:
# Find the number of the current bill to pay out
num_curr_bill = remaining_change/i
# Subtract how much you paid out with the current bill from the remaining change
remaining_change -= num_curr_bill * i
# Print the result for the current bill.
print num_curr_bill,'*',i
else:
print 'pay up!'
So, for a price of 120 and cash paid 175, the output is:
price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5
One bill for 50 and one for 5 add up to 55, the correct change.
Edit: I'd go more sparingly on the comments in my own code, but I added them here for explanation so that you could more clearly see what my thought process was.
Edit 2: I would consider removing the 0.5 in coin_bills and replacing 1 with 1.0, since any fractional amounts will wind up being fractions of 0.5 anyway.