python, print intermediate values while loop - python

I am sorry if this is very basic, I am new to programming.
When I run my code, only the last value is printed.
How can I modify my code, so that the entire list in range N is displayed, using a while loop?
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)

You didn't indent the x.append. So the code is not inside the loop and only the last value is appended to x. Correct would be:
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)

Your indenting is slightly off, but beyond that you can simply add the print statement to the while loop
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(xn)
print(x)

You need to put the x.append(xn) inside the while loop. Otherwise only the last xn will be appended to x.
x0 = 100
p = 5
N = 4
i = 0
x = []
while i <=N:
i += 1
xn = ((1 + (p/100))**i)*x0
x.append(xn)
print(x)

Related

How to loop multiple appends for python

num_pixels_per_cell_one_axis = 5
num_cells_per_module_one_axis = 3
inter_cell_sep = 4
max_items_in_list = num_cells_per_module_one_axis * num_pixels_per_cell_one_axis + (num_cells_per_module_one_axis-1) * inter_cell_sep
print(max_items_in_list)
indices_to_retain = list(range(max_items_in_list))
indices_to_remove = indices_to_retain[num_pixels_per_cell_one_axis :: num_pixels_per_cell_one_axis + inter_cell_sep]
if inter_cell_sep == 2:
for k in range(0,len(indices_to_remove)):
indices_to_remove.append(indices_to_remove[k]+1)
if inter_cell_sep == 3:
for k in range(0,len(indices_to_remove)):
indices_to_remove.append(indices_to_remove[k]+1)
indices_to_remove.append(indices_to_remove[k]+2)
for k in indices_to_remove:
indices_to_retain.remove(k)
print(indices_to_remove)
print(indices_to_retain)
I want to find a way to loop inter_cell_sep for any positive number and as it increases the lines for appending the list also increases. The expected answer should be [0,1,2,3,4,9,10,11,12,17,18,19,20]
I think instead of using if statements for each value of inter_cell_sep you could loop through a range of inter_cell_sep. Here is what I came up with.
num_pixels_per_cell_one_axis = 5
num_cells_per_module_one_axis = 3
inter_cell_sep = 3
max_items_in_list = num_cells_per_module_one_axis * num_pixels_per_cell_one_axis + (num_cells_per_module_one_axis - 1) * inter_cell_sep
print(max_items_in_list)
indices_to_retain = list(range(max_items_in_list))
indices_to_remove = indices_to_retain[num_pixels_per_cell_one_axis:: num_pixels_per_cell_one_axis + inter_cell_sep]
for k in range(0, len(indices_to_remove)):
indices_to_remove.extend([indices_to_remove[k] + x for x in range(1, inter_cell_sep)])
for k in indices_to_remove:
indices_to_retain.remove(k)
print(indices_to_remove)
print(indices_to_retain)

Add variables in an loop to a formula

I have a problem.
I am using a formula:
x = var1 * multiplier1 + var2 * multiplier2, etc.
I have 300 variables, so I want to loop through the variables and add them, but what I try doesn't work. I understand why it is not working, but I can't figure out how I have to do it correctly. This is my code:
multiplier = {}
count = 0
while (count != len(data[0])):
ri = np.random.randint(len(data))
point = data[ri]
x = point[count] * multiplier[count]
count += 1
It is not adding the variables to the formula, but it calculates it again. How can I make it work?
You seem to be missing a + sign.
Change x = point[count] * multiplier[count]
to x += point[count] * multiplier[count]
And declare x=0 before your loop.
Beware that nowhere in this code the multiplier dict is populated with values !
multiplier = {}
count = 0
x = 0
while (count != len(data[0])):
ri = np.random.randint(len(data))
point = data[ri]
x += int(point[count]) * multiplier[count]
count += 1

Stopping arithmetico-geometric sentence

I have a function u_terme that computes values of the sequence 3u + 1. I would like a stop function reached(M) that returns the lowest u value at which a given functional value is reached.
However, my code below doesn't work: it exits immediately and prints a single 0. Help?
def u_terme(x):
i = 0
u = 0
while i < x:
u = (3 * u) + 1
i = i + 1
print(u)
def reached(M):
x = 0
f = 0
while f >= M:
f = u_terme(x)
x = x + 1
print(x)
ANALYSIS:
u_terme fails to return any value.
reached exits immediately: your while loop quits as soon as f < M.
You have that logic reversed: you want to continue while f <= M.
Also, please use meaningful variable names.
REPAIR:
Make u_term return the computed value:
def u_terme(x):
u = 0
for i in range(x):
u = 3*u + 1
# print x, u
return u
Make reached iterate properly and return its result:
def reached(limit):
val = 0
func_val = 0
while func_val < limit:
val += 1
func_val = u_terme(val)
print val, func_val
return val
print reached(50)
Output:
1 1
2 4
3 13
4 40
5 121
5
Output:
17
Unfortunately the question is so unclear that it is difficult to provide a definitive answer. For example, what are allowable values of M?
At the first look, however, it is obvious that your u_terme() function has no return value (well, that is, it always return None). This means that f in the reached() function after the first iteration will be None and the loop will terminate.
Just because back-in-forth in comments doesn't work to well, I think this is the correct simplified, more efficient version of the code:
def u_terme(u):
return (3 * u) + 1
def reached(M):
x = 0
u = 0
while u < M:
u = u_terme(u)
x += 1
return x
print(reached(50)) # 5
EDIT
To help with the confusion in the comments. This new u_terme doesn't do what the previous one did. The previous one took a number x and computed u x times. This new one just returns the next value based on the previous one. This avoids duplicate work.
This code shows how to use it to get the expected values:
def u_terme(u):
return (3 * u) + 1
u = 0
for i in range(5):
print(i, u)
u = u_terme(u)
# Output:
# 0 0
# 1 1
# 2 4
# 3 13
# 4 40
EDIT 2
Just for fun, here's another way to do this. Why this is correct is an exercise left to the reader. :-)
def reached(M):
u = 0
x = 0
while u < M:
u += 3**x
x += 1
return x

Python function returning first value twice

I've written this function to calculate sin(x) using Taylor series to any specified degree of accuracy, 'N terms', my problem is the results aren't being returned as expected and I can't figure out why, any help would be appreciated.
What is am expecting is:
1 6.28318530718
2 -35.0585169332
3 46.5467323429
4 -30.1591274102
5 11.8995665347
6 -3.19507604213
7 0.624876542716
8 -0.0932457590621
9 0.0109834031461
What I am getting is:
1 None
2 6.28318530718
3 -35.0585169332
4 46.5467323429
5 -30.1591274102
6 11.8995665347
7 -3.19507604213
8 0.624876542716
9 -0.0932457590621
Thanks in advance.
def factorial(x):
if x <= 1:
return 1
else:
return x * factorial(x-1)
def sinNterms(x, N):
x = float(x)
while N >1:
result = x
for i in range(2, N):
power = ((2 * i)-1)
sign = 1
if i % 2 == 0:
sign = -1
else:
sign = 1
result = result + (((x ** power)*sign) / factorial(power))
return result
pi = 3.141592653589793
for i in range(1,10):
print i, sinNterms(2*pi, i)
I see that you are putting the return under the for which will break it out of the while loop. You should explain if this is what you mean to do. However, given the for i in range(1,10): means that you will ignore the first entry and return None when the input argument i is 1. Is this really what you wanted? Also, since you always exit after the calculation, you should not do a while N > 1 but use if N > 1 to avoid infinite recursion.
The reason why your results are off is because you are using range incorrectly. range(2, N) gives you a list of numbers from 2 to N-1. Thus range(2, 2) gives you an empty list.
You should calculate the range(2, N+1)
def sinNterms(x, N):
x = float(x)
while N >1:
result = x
for i in range(2, N):
Your comment explains that you have the lines of code in the wrong order. You should have
def sinNterms(x, N):
x = float(x)
result = x
# replace the while with an if since you do not need a loop
# Otherwise you would get an infinite recursion
if N > 1:
for i in range(2, N+1):
power = ((2 * i)-1)
sign = 1
if i % 2 == 0:
sign = -1
# The else is not needed as this is the default
# else:
# sign = 1
# use += operator for the calculation
result += (((x ** power)*sign) / factorial(power))
# Now return the value with the indentation under the if N > 1
return result
Note that in order to handle things set factorial to return a float not an int.
An alternative method that saves some calculations is
def sinNterms(x, N):
x = float(x)
lim = 1e-12
result = 0
sign = 1
# This range gives the odd numbers, saves calculation.
for i in range(1, 2*(N+1), 2):
# use += operator for the calculation
temp = ((x ** i)*sign) / factorial(i)
if fabs(temp) < lim:
break
result += temp
sign *= -1
return result

Leaving the for / while loop if certain conditions are met

I wrote a set of codes to calculate a Diophantine equation:
bestSoFar = 0
packages = (6,9,20)
numMc = 0
guess= 0
possibn = []
for n in xrange(1, 150):
for a in xrange(0, (n/ packages[0]) +1):
for b in xrange(0,(n/ packages[1]) +1):
c = (n - packages[0]* a - b * packages[1]) / packages[-1]
numMc = packages[0] *a + packages[1] * b + packages[-1] * c
if numMc == n and n not in possibn:
possibn.append(n)
print possibn
if len(possibn) >6 and possibn [-1] - possibn[-6] == 5:
bestSoFar = n
break
The original problem set is designed by the MIT course. Basically it is to calculate the number of McNuggets that could be bought by arranging the ratio of packages-in-different-size ( McDonald does 6,9,20 McNuggets in a package). Say, 21 McNuggets could be bought by buying two 6-McNuggets and one 9-McNuggets. if the number of McNuggets are possible to be bought in exact quantity of packages, I store them into a list. It is found that if 6 consecutive numbers are also possible to be bought in exact quantity, the remained numbers could also be possible.
From my code the result of bestSoFar=149 while the expected answer is 40. The reason would be that it keeps looping until n reaches 149. I would like to stop right at 40 ( with the break statement). However, it fails and I am seeking the advices for you all. Also, if there is anyway to program the problem faster/easier, I am happy to know and learn it too.
Thank you so much.
Casey
If you are not supposed to use a function, just assign a variable to cause breaks out of the other loops.
bestSoFar = 0
packages = (6,9,20)
numMc = 0
guess= 0
possibn = []
finished = False
for n in xrange(1, 150):
for a in xrange(0, (n/ packages[0]) +1):
for b in xrange(0,(n/ packages[1]) +1):
c = (n - packages[0]* a - b * packages[1]) / packages[-1]
numMc = packages[0] *a + packages[1] * b + packages[-1] * c
if numMc == n and n not in possibn:
possibn.append(n)
# print possibn
if len(possibn) >6 and possibn [-1] - possibn[-6] == 5:
bestSoFar = n
finished = True
break
if finished: break
print bestSoFar
Turn it into a function and return:
from __future__ import print_function
def solve(*packages):
bestSoFar = 0
numMc = 0
guess= 0
possibn = []
for n in xrange(1, 150):
for a in xrange(0, (n / packages[0]) + 1):
for b in xrange(0, (n / packages[1]) + 1):
c = (n - packages[0] * a - b * packages[1]) / packages[-1]
numMc = packages[0] * a + packages[1] * b + packages[-1] * c
if numMc == n and n not in possibn:
possibn.append(n)
print possibn
if len(possibn) > 6 and possibn [-1] - possibn[-6] == 5:
return n
return bestSoFar
x = solve(6, 9, 20)
print(x)
I am not actually clear on what you are expecting. But, what i see is you want to break out of everything. The break which you have given only exits inner loop. Put another break statement outside the inner loop and inside first loop.

Categories