python 3.x overwrite previous terminal line - python

I wrote a simple program to calculate average outcome of a dice throw (pretty pointless, but you have to start somewhere ;P):
import random, time
from random import randrange
count = 0
total = 0
one_count = 0
for x in range(10000000):
random = randrange(1,7)
count = count + 1
total = total + random
average = total / count
percentage = one_count / count * 100
if random == 1:
one_count = one_count + 1
print("the percentage of ones occurring is", percentage, "and the average outcome is", average)
# time.sleep(1)
To clean it up I want the output to overwrite the previous line. I tried everything I could find, but the only thing I managed to to is to print to the same line without erasing the previous content by changing the last line to:
print("the percentage of ones occuring is", percentage, "and the average outcome is", average, "/// ", end="")
which outputs:
the percentage of ones occuring is 0.0 and the average outcome is 4.0 /// the percentage of ones occuring is 0.0 and the average outcome is 4.5 /// the percentage of ones occuring is 0.0 and the average outcome is 3.6666666666666665 ///
Any ideas?

Add a \r at the end. That way, the next line you write will start at the beginning of the previous line. And then flush output so it shows immediately.
Note: If the next line is shorter, the remaining characters will still be there.

use end='\r:
for x in range(100000):
rnd = randrange(1,7) # don't use random
count += 1
total = total + rnd
average = total / count
percentage = one_count / count * 100
if rnd == 1:
one_count += 1
print("the percentage of ones occurring is {} and the average outcome is {}".format(percentage,average),end='\r')
time.sleep(.1)
On another note using total = total + random is not a good idea, you are importing the random module and using random as a variable name.

Related

Count the dice throws to get to file 5 100 times(board is 0-5)

I'm trying to find out how many times you have to throw the dice to get on file 5 100 times(board is played from 0 to 5). This is how I tried(I know the answer is 690 but I don't know what I'm doing wrong).
from random import *
seed(8)
five = 0
count = 0
add = 0
while five < 100:
count = count + 1
print(randint(1,6))
add = add + randint(1,6)
if add % 5 == 0 :
five = five + 1
else: add = add + randint(1,6)
print(count)
This is the code I think you were trying to write. This does average about 600. Is it possible your "answer" came from Python 2? The random seed algorithm is quite likely different.
from random import *
seed(8)
five = 0
count = 0
add = 0
while five < 100:
count += 1
r = randint(0,5)
if r == 5:
five += 1
else:
add += r
print(count, add)
You're adding a second dice throw every time you don't get on 5, this makes the probability distribution irregular (i.e. advancing by 7 will be more probable (1/6) than any other value, e.g. 1/9 for 5) so your result will not be the same as counting single throws.
BTW there is no fixed result for this, just a higher probability around a given number of throws. However, given that you seeded the random number generator with a constant, every run should give the same result. And it should be the right one if you don't double throw the dice.
Here is an example of the process that arrives at 690:
import random
random.seed(8)
fiveCount = 0
throwCount = 0
position = 0
while fiveCount < 100:
position = (position + random.randint(1,6)) % 6
throwCount += 1
fiveCount += position == 5
print(throwCount) # 690
Other observations:
Updating the position wraps around using modulo 6 (there are 6 positions from 0 to 5 inclusively)
Your check of add%5 == 0 does not reflect this. It should have been add%6 == 5 instead but it is always preferable to model the computation as close as possible to the real world process (so keep the position in the 0...5 range)

Python function for calculating compound interest percentage

I'm new to programming, so any experienced programmer will probably be able to answer this question easily.
I am trying to write a Python function which will tell me what percentage compound interest is necessary to end up with a specific sum. For example, if I deposited $100, and after 17 years of compound interest I have $155, the function will tell me what percentage interest was I receiving. I wrote the following function, with 'start' being the original sum deposited, 'finish' the sum I ended up with, and 'years' the number of years it accrued interest. I designed it to give a result in decimal points, for example for 1.5% it will show 0.015.
Here's the code I wrote:
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
It's giving an output of 0.00017499999999999962 (i.e. 0.017499999999999962%), which is totally wrong.
I can't understand where I've gone wrong.
You need to reset the num=start after every time you guess a percentage.
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
num = start
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
However, you'd probably be better off solving this problem by simply re-arranging the compound interest formula:
A=P*(1+r/n)^(nt)
(where A = Final balance, P = Initial balance, r = Interest rate, n = number of times interest applied per time period, and t = number of time periods elapsed.)
The rearrangement gives:
r=n((A/P)^(1/nt)-1)
and putting this into python gives us:
def calculate(start, finish, years):
num = ((finish / start)**(1/years))-1
return num
print(calculate(12000.0, 55000.0, 100.0))
which gives the expected results.
You can do a one-liner if you understand how compound interest works
def calculate(start, finish, years):
return (finish/start)**(1/years) - 1
print(calculate(12000, 55000, 100) * 100, '%')

How to fix printing of score values?

This program should display:
Here are your grades
Math score is 100
Science score is 90
Reading score is 70
Average grade score is 86.66
However with the code I have, it is displaying this:
Here are your grades:
Math score is 100.0
Sciencee score is 95.0
Reading score is 86.66666666666667
The average score is 86.66666666666667
So basically the average is correct but now the scores are not.
gradesFile = open("grades.txt","r")
#Establishes the variables
total = 0
numberOfLines = 0
lines = 0
print('Here are your grades:','\n')
# Creates a loop that will print out each score, until there aren't anymore
# scores to read. For example:
#Math score is 100
#Science score is 90
#and so on.
for line in gradesFile:
numberOfLines += 1
lines = line.strip()
total += float(gradesFile.readline())
score = total / numberOfLines
print(lines + ' score is', score)
gradesFile.close
average = float(total) / (numberOfLines)
print('The average score is', average)
The grades.txt file looks like this:
Math
100.0
Science
90.0
Reading
70.0
Your score is essentially a rolling average. There's no need for that, just print it directly:
for line in gradesFile:
numberOfLines += 1
lines = line.strip()
score = float(gradesFile.readline())
total += score
print(lines + ' score is', score)

Finding probability of unsafe lift simulation

I can find this using Excel but I'd like to know how to do it using Python.
Each column under Person is randomly generated with normal distribution of a standard deviation 15 and mean of 80.
Number of people is randomly generated between 1 to 6.
Total weight is the sum of person with the number of people. e.g. the first one is the sum of first 4 person.
Unsafe is a boolean. If the total weight is more than 500 then 1 otherwise 0.
Trials is 3997. The sum of unsafe is 148. Then the probability is calculated by number over weight divided by trials.
I can create a normal distribution using numpy. I create a random number with 80 mean and 15 sd and a random number between 0 and 7 (1 to 6).
import numpy as np
from decimal import *
total_num = 0
i=1
trial = 100
while i < trial:
rand_num =np.random.randint(1,7)
person = np.random.normal(80, 15)
total_weight = int(rand_num)*Decimal(person)
# print(total_weight)
if total_weight > int(500):
total_num += total_num
i += 1;
total_num/trial
But I am getting 0 in my output.
What am I doing wrong here?
I just needed to modify total_num += 1.
import numpy as np
count = 0
i=int(1)
trial = int(10000)
limit = int(500)
while i < trial:
rand_num =np.random.randint(1,7)
person = np.random.normal(80, 15)
total_weight = int(rand_num)*person
# print(total_weight)
if total_weight > limit:
#print('yes')
count += 1
count
i += 1;
print("Probability is: ")
print(count/trial)

Loop not iterating

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.

Categories

Resources