How to assign the average and print as an integer - python

The instructions are to assign avg_owls with the average owls per zoo. Print avg_owls as an integer. However, the math keeps coming up wrong with the sample inputs. Even when I do the math by hand. The code is as follows.
Given sample inputs are 1 2 4
avg_owls = 0.0
num_owls_zooA = int(input())
num_owls_zooB = int(input())
num_owls_zooC = int(input())
avg_owls = int(num_owls_zooA + num_owls_zooB + num_owls_zooC / 3)
print('Average owls per zoo:', int(avg_owls))
Your output
Average owls per zoo: 4
Expected output
Average owls per zoo: 2
I have written and can only alter the code avg_owls = int(num_owls_zooA + num_owls_zooB + num_owls_zooC / 3)
I don't understand how it's coming up with 4 when the actual math comes out to 2.333
What am I doing wrong?

Operator precedence, and the rules of maths, say that
num_owls_zooA + num_owls_zooB + num_owls_zooC / 3
will be calculated as
num_owls_zooA + num_owls_zooB + (num_owls_zooC / 3)
You need some brackets to get the result you want:
(num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3
As an extra note, applying int to the result feels potentially wrong. It will cause it to always round down. For an average you would usually want to either keep it as a floating point value or at least round to the nearest value rather than always down.

Two problems here. In pemdas or germdas, division comes before addition. SO you need parentheses around the addition. Also if you do int(4.3) you will get 4. float will give you your desired output
avg_owls = 0.0
num_owls_zooA = float(input())
num_owls_zooB = float(input())
num_owls_zooC = float(input())
avg_owls = (num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3
print(f'Average owls per zoo: {avg_owls} ')
also I suggest using f strings.

Change to:
avg_owls = int((num_owls_zooA + num_owls_zooB + num_owls_zooC) / 3)
This solution works as tested.

Related

Loop code with: {x_(n+1) = x_n * r * (1- x_n)}

Little new here and any help would be appreciated.
I have been tooling around with this code for a while now and I cant seem to wrap my head around it. Im fairly new to python so I dont quite know or remember all the tricks yet/skills.
So the question at hand:
Equation: {x_(n+1) = x_n * r * (1- x_n)}
With x_n between (0,1) and r between (0,4).
The goal here is to make a loop function that will gather a value for 'x_n' and 'r' and spit out the iteration 'n' and the current 'x_n+1'; i.e. print(n , x_n+1), at each 'n' step while checking to see if the new value is within 0.0000001 of the old value.
If it settles on a fixed point within 20,000 (0.0000001), print the final 'n' + message. If not then and goes to 20,000 then print another message.
All i have so far is:
import math
x_o=float(input("Enter a 'seed' value: "))
r=float(input("Enter an 'r' value: "))
x_a=((x_o + 0) * r * (1-(x_o + 0)))
while x_a != (0.0000001, x_o , 0.0000001):
for n in range(0,99):
x_a=((x_o + n) * r * (1-(x_o + n)))
print(n , x_a)
I'm pretty sure this is no where close so any help would be awesome; if you need any more info let me know.
Much appreciated,
Genosphere
You could write a generator function and use it directly in your for loop. If you need to keep track of the rank of intermediate values you can use enumerate on the generator.
def fnIter(fn,x,delta=0.000001):
while True:
yield x
prev,x = x,fn(x)
if abs(x-prev)<delta:break
output:
r = 2
seed = 0.1
for i,Xn in enumerate(fnIter(lambda x:x*r*(1-x),seed)):
print(i,Xn)
0 0.1
1 0.18000000000000002
2 0.2952
3 0.41611392
4 0.4859262511644672
5 0.49960385918742867
6 0.49999968614491325
7 0.49999999999980305
To implement the maximum iteration check you can either add a conditional break in the loop or use zip with a range:
maxCount = 20000
n,Xn = max(zip(range(maxCount+1),fnIter(lambda x:x*r*(1-x),seed)))
if n < maxCount:
print(n,Xn)
else:
print(Xn,"not converging")
This is an exponentially-weighted moving average. Pandas has a function for this: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
You have a good start so far. You might be overthinking it, though.
The following approach just tries to generate this sequence for 20,000 terms. Each time, it checks whether the new value is within 0.0000001 from the previous value. If so, it breaks out of the loop and prints that. If not, it uses python's for/else construct to print a different value. Note the different levels of indentation.
x_0 = float(input("enter a 'seed' value: "))
r = float(input("enter an 'r' value: "))
x_m = x_0 # placeholder for 'previous value'
delta = 0.0000001
# Try to calculate 20 thousand terms of this sequence
# We will break out of the loop early if our x_n converges
for _ in range(20000):
x_n = x_m * r * (1 - x_m)
if abs(x_n - x_m) < delta:
print("Settled on value for x_n: ", x_n)
break
else:
x_m = x_n # move forward to the next value
else:
print("x_n did not converge in 20000 terms")

Print the value of the series x = 1 + 1/2 + 1/3 + 1/4 + … + 1/n for the user’s input of n

Python 2 how to do this.Print the value of the series x = 1 + 1/2 + 1/3 + 1/4 + … + 1/n for the user’s input of n.
Here you go:
n = int( input() ) # reading user input
x = 0
for i in range(1, n + 1): # adding 1/1 + 1/2 + 1/3 + ... + 1/n
x += 1.0/i
print(x) # => outputs : 2.283333333333333
There may be a Harmonic Series function in Python packages like math or numpy, or some similar way to deal with it, especially if you need high precision at large values of n. Otherwise, you could just do this:
>>> n = 5
>>> print(sum(1.0/i for i in range(1,n+1)))
2.28333333333
Note that the "1.0" is important for Python 2.x so that it knows to deal with floats. Otherwise things get rounded along the way:
>>> print(sum(1/i for i in range(1,n+1)))
1

need help in understanding a code

Can anyone explain this code a little. I can't understand what n does here? We already have taken N = int(input()) as input then why n=len(bin(N))-2? I couldn't figure it out.
N = int(input())
n = len(bin(N))-2
for i in range(1,N+1):
print(str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n))
n counts the number of bits in the number N. bin() produces the binary representation (zeros and ones), as as string with the 0b prefix:
>>> bin(42)
'0b101010'
so len(bin(n)) takes the length of that output string, minus 2 to account for the prefix.
See the bin() documentation:
Convert an integer number to a binary string prefixed with “0b”.
The length is used to set the width of the columns (via str.rjust(), which adds spaces to the front of a string to create an output n characters wide). Knowing how many characters the widest binary representation needs is helpful here.
However, the same information can be gotten directly from the number, with the int.bitlength() method:
>>> N = 42
>>> N.bit_length()
6
>>> len(bin(N)) - 2
6
The other columns are also oversized for the numbers. You could instead calculate max widths for each column, and use str.format() or an f-string to do the formatting:
from math import log10
N = int(input())
decwidth = int(log10(N) + 1)
binwidth = N.bit_length()
hexwidth = (binwidth - 1) // 4 + 1
octwidth = (binwidth - 1) // 3 + 1
for i in range(1, N + 1):
print(f'{i:>{decwidth}d} {i:>{octwidth}o} {i:>{hexwidth}X} {i:>{binwidth}b}')

Python Issue with Loops

I have designed a code which will take a 'number' as an input from the user.
The number will be used to make a...
numerator = (3*number) - 2
and a denominator, which will be denominator = (4*n) + 1.
The code will also allow the user to choose how many times they want this sequence to go on after which the sum of all the fractions will be totaled and displayed.
Here is the Code I have:
l=int(input("How many times do you repeat this sequence?: "))
n=int(input("Enter a base number: "))
n1=n
n2=n
total=0
s = ''
def calculate(l,n,n1,n2,total,s):
for j in range(l):
s += "{}/{} + ".format(3*n1-2, 4*n2+1)
n1=n+n1
n2=n+n2
total=(((n*3)-2)/((4*n)+1))+total
print(s)
print(total)
calculate(l, n, n1, n2, total, s)
Now here are the two errors that I receive when I get the output for this code for example:
How many times do you repeat this sequence?: 2
Enter a base number: 1
1/5 + 4/9 +
0.4
The two Issues:
Since 4/9 is the last fraction, is there a way to get rid of that "+" addition sign at the end, because it just points to a blank space..
The total for the two fractions shows to be 0.4 which is incorrect, the total sum should be 1/5 + 4/9 = 0.2 + 0.44 = 0.64, I am unsure where I went astray when inputting my total sum formula above.
Any suggestions/comments would be appreciated!
A cheap way of removing the + would be to simply cut off the last character in the string: str[:-1].
As far a issue 2 goes, it looks like you want to use n1 and n2 instead of n.
As of now, you're getting 1/5(.2) + 1/5(.2) = .4
Instead of concatening a string like that, collect all the parts in a list and then join the items on the plus sign:
s = []
s.append('{}/{}'.format(1, 5))
s.append('{}/{}'.format(4, 9))
print(' + '.join(s)) # 1/5 + 4/9
I’m not really sure what you are doing but if you want to get the sum of the fractions you print, you should just make sure that you calculate those individual fractions in the same way. So instead of incrementing n1 and n2 first before calculating the sum, calculate the sum in the same way you did for the fraction output and only afterwards change those variables:
s.append("{}/{}".format(3 * n1 - 2, 4 * n2 + 1))
total += (3 * n1 - 2) / (4 * n2 + 1)
n1 += n
n2 += n
I dont know python but you could do the following to correct your logical errors.
to remove the '+' at the end, you can do something like below,
if j = l (implies last fraction)
dont include +
else
include +
While calculating total you are using 'n' value which always remains as your input value
total=(((n*3)-2)/((4*n)+1))+total
Here use n1 or n2
total=(((n1*3)-2)/((4*n2)+1))+total

Python average of 3 numbers calculation

for some reason, my calculation is not coming out correct. All I'm trying to do is find the average of 3 numbers that a user inputs. Here's def that it sits in, if more is needed, just ask.
#===================== Calculates the average of all three ==========================
def calc_average(self): #average calculation
stop_one_mileage = self.__route[0].stop_one_mileage #stop_one_mileage average
stop_two_mileage = self.__route[0].stop_two_mileage #stop_two_mileage
stop_three_mileage = self.__route[0].stop_three_mileage #stop_three_mileage
avg = int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage)/3 #adds all three and divides by three
return "<div class='results-container'><span class='title'>Average Mileage: </span><span class='results-container'>" + str(avg) + " miles</span></div>" #returns results
The problem is here:
avg = int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage)/3
Change it to:
avg = (int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage))/3
Because this is what's happening:
>>> 2 + 2 + 2 / 3
4
>>> (2 + 2 + 2) / 3
2
Perhaps did you forget to use parenthesis?
avg = (int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage))/3
Otherwise it will divide only the last number by 3 then it will sum the others. Take a look at Python operator precedence documentation.

Categories

Resources