+ 1
Python Help
Explain this please: def f(n): x = y = 1.0 for i in range(1,n): x, y=y, x+y return y/x print(f(3))
5 odpowiedzi
+ 9
Looks like you got lots of good advice, but this might also help.
https://code.sololearn.com/cTRK2QlwEZ0F/?ref=app
+ 8
I think the function gives this:
https://en.m.wikipedia.org/wiki/Golden_ratio
The higher the number of the arg, the more accurate.
+ 8
Print the variable <x> and <y> before the loop and inside loop body. The output should give you a clear view how the code works
def f(n):
x = y = 1.0
print(f"Before loop x = {x} y = {y}")
loop = 1
for i in range(1, n):
x, y = y, x + y
print(f"Loop iteration {loop}, x = {x} y = {y}")
loop += 1
return y / x
print("Result", f(3))
+ 7
If the function would return y instead of y/x, I guess the program would find the n+1 element in fibonacci sequence 🤔. That would mean the program calculates the division of 2 consecutive fibonacci numbers
+ 7
In beginnig:
x = 1.0
y = 1.0
When i = ... then the variable values changed to ... :
i = 0:
x = 1.0 (x = y ---> x = 1.0)
y = 2.0 (y = x + y ---> y = 1.0 + 1.0 ---> y = 2.0)
i = 1:
x = 2.0 (x = y ---> x = 2.0
y = 4.0 (y = x + y ---> y = 2.0 + 2.0 ---> y = 4.0)
i = 2:
x = 4.0 (x = y ---> x = 4.0)
y = 8.0 (y = x + y ---> y = 4.0 + 4.0 ---> y = 8.0)
Then y / x was returned:
return y/x (y/x ---> 8.0 / 4.0 ---> 2.0)
2.0 was returned.