For function a(0) = 3, a(n) = 2*a(n-1) -1, generator should be like:
def p():
b = 3
while True:
yield b
b = 2 * b -1
So for function c(1) = 9, c(n) = 9*c(n-1) + 10**(n-1)- c(n-1),
how to write the generator for this function?
For the sequence, you have value for c(1) as 9, calculate the value for c(0) using c(1) which turns out to be 1, then write a generator which first yeilds c(0), and c(1), then for each next values, apply the formula, and get the next value and yield it, finally replace the previous value b0 by this next value b1 in order to continue the sequence.
def generate_seq():
b0 = 1
b1 = 9
n=2
yield b0
yield b1
while True:
b1 = 9*b1 + 10**(n-1) - b1
yield b1
b0 = b1
n += 1
seq = generate_seq()
for i in range(10):
print(next(seq))
OUTPUT:
1
9
82
756
7048
66384
631072
6048576
58388608
567108864
Similar to your original, just the extra power of 10:
def p():
c = 1
pow10 = 1
while True:
yield c
c = 8*c + pow10
pow10 *= 10
Try it online!
Related
I would like to write a program for Pythagorean Triplet. Program for numbers a, b, c return Pythagorean three natural numbers a1, b1, c1 such that a1 >= a, b1 >= b, c1 >= c.
def Triplet(a, b, c):
a1 = a
b1 = b
n = 5
m = 0
while True:
m += 1
while b1 <= (b + n * m):
a1 = a
while a1 <= b1:
#while c1 > c:
c1 = (a1 * a1 + b1 * b1) ** .5
if c1 % 1 == 0:
return a1, b1, int(c1)
a1 += 1
b1 += 1
print(Triplet(3,4,6))
For input: (3, 4, 6), output should be: (6, 8, 10). Where is the error?
The issue is that you've commented out your incorrect check for c1 > c, but not replaced it with anything.
If you just add that condition back before the return, it works:
def Triplet(a,b,c):
a1=a
b1=b
n=5
m=0
while True:
m+=1
while b1<=(b+n*m):
a1=a
while a1<=b1:
c1=(a1*a1+b1*b1)**.5
if c1>=c and c1%1==0:
return a1,b1,int(c1)
a1+=1
b1+=1
print(Triplet(3,4,6))
If you change the condition to if c1%1==0 and c1>=c: then the issue will get fixed.
I ran it locally and i got (6, 8, 10)
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I want to make a1=0, a2=0,... aN=0.
I thought using "for"
For example N=10
for i in range(0, 10):
print('a%d'%i)
but it isn't not zeros(just print).
So, I did 'a%d'%i=0. but It didn't work
How can I make that?
For printing use .format() (or f-strings on python 3.6+ :
for i in range(0, 10):
print('a{} = {}'.format(i,i)) # the 1st i is put into the 1. {}, the 2nd i is put ...
If you want to calculate with those as names, store them into a dictionary and use the values to calculate with them:
d = {}
for i in range(0, 10):
d["a{}".format(i)] = i # the nth i is put instead nth {}
print("sum a4 to a7: {} + {} + {} + {} = {}".format( # use the values stored in dict to
d["a4"], ["a5"], ["a6"], ["a7"], # calculate and print the single
d["a4"]+d["a5"]+d["a6"]+d["a7"])) # values where needed
Output:
# for loop
a0 = 0
a1 = 1
a2 = 2
a3 = 3
a4 = 4
a5 = 5
a6 = 6
a7 = 7
a8 = 8
a9 = 9
# calculation
sum a4 to a7: 4 + ['a5'] + ['a6'] + ['a7'] = 22
You can use a dictionary for that.
var_name = 'a'
for i in range(0, 10):
key = var_name + str(i) # an
new_values[key] = 0 # assign 0 to the new name
For accessing them individually,
new_values['a1']
>>> 0
or you can access them all together like this,
for k,v in new_values.items():
print(k,'=',v)
outputs:
a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
Simple solution, using const value x=0, and counter i:
x = 0
for i in range(0,10):
print(f"a{i} = {x}")
output:
a0 = 0
a1 = 0
a2 = 0
a3 = 0
a4 = 0
a5 = 0
a6 = 0
a7 = 0
a8 = 0
a9 = 0
def genfibon(n): #fib sequence until n
a=1
b=1
for i in range n:
yield a
t=a
a=b
b=t+b
Can someone explain the t variable? It seems like t=a so then a=b and then b=t because a=b and a=t. How does b=t+b?
Let's say a = 2 and b = 3.
t = a # now t = 2
a = b # now a = 3, but t is unchanged
b = t + b # now b = 5
The key is that second part. t = a means t gets the same value as a. It does not mean that t and a are now both the same thing.
You might try this in a Python prompt:
a = 3
b = a
a = 5
print(b) # still 3
It's called swapping of variables. how do you replace the values of variables?
as #smarx said, when a = 2 and b = 3, how do you make it a = 3 and b = 2?
when you do a = 3, the old value of a(2) is lost so you wont know what to set b with. so we store this in a temporary variable(t).
so,
t = a //(saves 2 in t)
a = b //(now both a and b have same values)
b = t //(b gets the old value of a)
// now a = old value of b
// and b = old value of a.
voila, the variables are swapped.
Well, that goes for swapping. which is only partly used in this code. the last statement b = t + b what the code is doing is, adding the old value of a with b(rather than replacing it). why? you get the next number in a fibonacci sequence by adding the previous 2.
2, 3, 5 is a fibonacci sequence since 5 = 2 + 3(given 2 and 3 are seed values). that's exactly what this code is doing.
In your first run
yield a # will return 1
t = a # which is 1
a = b # which is 1
b = t + b # which is 2 as t = 1 and b = 1
In your 2nd run
yield a # will return 1
t = a # which is 1
a = b # which is 2
b = t + b # which is 3 as t = 1 and b = 2
In your 3rd run
yield a # will return 2
t = a # which is 2
a = b # which is 3
b = t + b # which is 5 as t = 2 and b = 3
In your 4th run
yield a # will return 3
t = a # which is 3
a = b # which is 5
b = t + b # which is 8 as t = 3 and b = 5
And so on...
Let us go statement by statement.
t=a means value of a is stored in t.
a=b means value of b is stored in a. (Thus a now contains the next element in the series)
b=t+b means value of b is now t + b which means a+b since t now contains the value of a (According to first step).
i'm not in computer science or computer related major. i'm civil engineering student, and i'm trying to make app to ease my calculation that can't be calculated by spreadsheet. i know python basic. and please don't be cruel to me haha
so i have this code
from math import ceil
print('Masukan jarak antar pias')
jarakAntarPias = float(input())
print('Masukan kedalaman sondir')
kedalamanSondir = float(input())
jumlahTitik = int(ceil(kedalamanSondir/jarakAntarPias+1))
conus = []
cn2a = []
cn3a = []
for i in range(0, jumlahTitik):
a = float(input())
if a < 0:
b = float(input())
conus[i-1] = [(i-1)*jarakAntarPias, b]
a = float(input())
if a >= 0:
conus.insert(i, [i*jarakAntarPias, a])
conusAtas = []
conusBawah = []
print(conus)
diameter = float(input())
d4 = diameter*4
d8 = diameter*8
y = 0
a1 = 0
while y <= jumlahTitik:
if (d4/jarakAntarPias+1) >= y:
while a1 <= y:
conusAtas.insert(a1, conus[y-a1][1])
a1 += 1
else:
while a1 <= (int((d4/jarakAntarPias))+1):
conusAtas.insert(a1, conus[int((d4/jarakAntarPias))+1-a1][1])
a1 += 1
a1 = 0
print(conusAtas)
if (d8/jarakAntarPias+1) <= jumlahTitik-y:
while a1 <= jumlahTitik-y:
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
else:
while a1 <= (d8/jarakAntarPias+1):
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
#more code below
print(conusBawah)
conusAtas = []
conusBawah = []
y += 1
my problem is, the code works flawlessly as i expected if i didn't add this code
if (d8/jarakAntarPias+1) <= jumlahTitik-y:
while a1 <= jumlahTitik-y:
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
else:
while a1 <= (d8/jarakAntarPias+1):
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
those code actually similar like this code below
if (d4/jarakAntarPias+1) >= y:
while a1 <= y:
conusAtas.insert(a1, conus[y-a1][1])
a1 += 1
else:
while a1 <= (int((d4/jarakAntarPias))+1):
conusAtas.insert(a1, conus[int((d4/jarakAntarPias))+1-a1][1])
a1 += 1
but when the program is running this code
conusBawah.insert(a1, conus[y+a1][1])
it always have ListIndex error
this is the traceback
Traceback (most recent call last):
File "C:/Users/afahm/PycharmProjects/untitled2/DULS.py", line 56, in <module>
conusBawah.insert(a1, conus[y+a1][1])
IndexError: list index out of range
please help me, i've been stuck in this code for two days.
thanks
you need to add a condition to all of your while statements where you use conus[y+a1], because y + a1 is bigger that the length of conus.
so... it would look like:
if (d4/jarakAntarPias+1) >= y:
while a1 <= y and (y+a1) < len(conus):
conusAtas.insert(a1, conus[y-a1][1])
a1 += 1
else:
while a1 <= (int((d4/jarakAntarPias))+1) and (int((d4/jarakAntarPias))+1-a1) < len(conus):
conusAtas.insert(a1, conus[int((d4/jarakAntarPias))+1-a1][1])
a1 += 1
a1 = 0
print(conusAtas)
if (d8/jarakAntarPias+1) <= jumlahTitik-y:
while a1 <= jumlahTitik-y and (y+a1) < len(conus):
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
else:
while a1 <= (d8/jarakAntarPias+1) and (y+a1) < len(conus):
conusBawah.insert(a1, conus[y+a1][1])
a1 += 1
This checks that the length conus is less than y + a1. eg. if conus = [[0.0, 3.0], [1.0, 4.0], [2.0, 5.0]] the len(conus) would be 3. you where getting the IndexError, is because y +a1 was 3, and because conus is Zer0 indexed that would mean thatconus[2] == [2.0, 5.0]. in other wordsconus[3]` would fail.
In this iteration you are filling your list:
for i in range(0, jumlahTitik):
which means, your highest index is jumlahTitik - 1
in this iteration you are trying to access your list:
while y <= jumlahTitik:
On your last iterarion y would be jumlahTitik and a1 would be >0
so conus[y+a1] trys to access conus[jumlahTitik + a1] which cant work, since your highest index is jumlahTitik - 1
What is the thought process when evaluating a loop? I really have no idea how the shell gets these answers (A: 12, B: 2, C: 4, D: 6).
A, B, C, D = 0, 0, 0, 0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
Perhaps you can read it more easily if you break it down:
A = 0
while A <= 10:
A += 2
Can you read this? Do you understand how it gets to 12?
A, D = 0, 0
while A <= 10:
A += 2
D += 1
Also including D should not make it any harder.
Can you read and understand the if-statement by itself?
if A%3 == 0:
B += 1
else:
C += 1
How about when it is inside the loop?
A, B, C, D = 0, 0, 0, 0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
B and C are related; exactly one of them are incremented in each iteration, so they should add up to the same as D, which they do.
Do you have any specific problems reading and understanding this now? :)
The other answers are good. I would highly recommend going through things with a pen and paper to make sure you understand what's going on.
Using print inside the loop is also useful to see what is going on while your program runs.
A,B,C,D = 0,0,0,0
while A <= 10:
A += 2
if A%3 == 0:
B += 1
else:
C += 1
D += 1
print "A =", A, " B =", B, " C =", C, " D =", D
The output shows you the values of A, B, C, D at the end of every loop iteration.
A = 2 B = 0 C = 1 D = 1
A = 4 B = 0 C = 2 D = 2
A = 6 B = 1 C = 2 D = 3
A = 8 B = 1 C = 3 D = 4
A = 10 B = 1 C = 4 D = 5
A = 12 B = 2 C = 4 D = 6
You can see that:
A gets incremented by 2 every loop iteration
B gets incremented by 1 IF A is divisible by 3, that is A%3 == 0
C gets incremented by 1 IF A is NOT divisible by 3
D gets incremented by 1 every loop iteration
When it comes to loops, you can think of the collection of indented code as a single "chunk" of code that gets executed once for every repetition of the loop. The formal term for this code chunk is a block. It also applies to if/else statements.
The body of the while loop will execute 6 times (for A=0,2,4,6,8,10).
At each iteration, A is incremented by 2, so after the first statement
within the loop it has values 2,4,6,8,10,12.
B is incremented by one twice (when A=6 and A=12);
C is incremented by one for the remaining values of A.
D is incremented every time round the loop.
Hence, after the loop, A=12, B=2, C=4 and D=6.