Why can't I run this fibonacci sequence? - python

extremely new to python, whenever I try to run this code
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end = ' ')
a, b = b, a+b
print()
I get an error message saying either
print(a, end=' ') SyntaxError: invalid syntax
or
fib() not defined.
how can I solve this?

Because you didn't take value of n from the user.
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end = ' ')
a, b = b, a+b
print()
fib(10)

Your code has no issue if you were to use Python 3 so consider using that instead.
If you like python2 a lot then modify your code to the following:
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(str(a) + ' ')
a, b = b, a+b
This is because python2 doesn't allow the use of
print(a, end = ' ')
It is a python3 feature

Related

Equation solving using bisection method using python

I wrote a python code to find root of 2*x-4 using bisection method
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)
Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))
def Input():
a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()
See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:

Specific Character Pattern Python

I am trying to achieve the following;
Write a program that produces the following output giving an integer input n.
The result should be the following;
n=1 n=2 n=3 n=4
+ A+B AA+BB AAA+BBB
+E+ A+E+B AA+E+BB
C+D +EEE+ A+EEE+B
C+E+D +EEEEE+
CC+DD C+EEE+D
CC+E+DD
CCC+DDD
I am having issues solving this problem.
When I enter 2 I am currently getting the following but unable how to make it look like the above.
Current result;
A+
B+
E+
C+
D
Here is my code;
def specific_pattern(n):
addition = "+"
alp = "A, B, E, C, D"
# myList = ["A, B, C, D, E"]
newList = []
for j in range(0, n):
for i in range(0, j):
if n == 1:
print(addition)
else:
letters = alp.split(", ")
for letter in range(len(letters)):
newList.append(letters[letter]*j+addition)
newchar = "".join(newList)
print(newchar[:-1])
n = int(input("Enter a number: "))
specific_pattern(n)
You can use simple iteration to create both the top and bottom of the desired diamond:
def sequence(d):
c, l = 0, 1
while c < d - 1:
if l%2:
yield l
c += 1
l += 1
def make_pattern(d):
t, b, r = f'{"A"*(d-1)}+{"B"*(d-1)}', f'{"C"*(d-1)}+{"D"*(d-1)}', list(sequence(d))
body = '\n'.join(f'{"A"*((r[-1]-i)//2)}+{"E"*i}+{"B"*((r[-1]-i)//2)}' for i in r[:-1]) + \
f'\n+{"E"*r[-1]}+\n'+'\n'.join(f'{"C"*((r[-1]-i)//2)}+{"E"*i}+{"D"*((r[-1]-i)//2)}' for i in r[:-1][::-1])
return f'{t}\n{body}\n{b}'
def diamond(d):
return {1:lambda _:'+', 2:lambda _:'A+B\n+E+\nC+D'}.get(d, make_pattern)(d)
print(diamond(3))
print('-'*5)
print(diamond(4))
Output:
AA+BB
A+E+B
+EEE+
C+E+D
CC+DD
-----
AAA+BBB
AA+E+BB
A+EEE+B
+EEEEE+
C+EEE+D
CC+E+DD
CCC+DDD

Making Range Function Act Over Given Values in Python

I would like to know if there is a way to make the range function act only over some given values.
I'm trying to write some code for Problem 2 of Project Euler where I must find the sum of the even-valued terms of the Fibonacci sequence whose values do not exceed 4,000,000.
My code at the moment looks like this:
#Fibonacci Even Sum
even_sum = 0
def fib(n):
a, b = 1,2
while a < n:
print (a)
a, b = b, a + b
print ()
return a
for i in range(fib(4000000)):
if i % 2 == 0:
even_sum = i + even_sum
print (even_sum)
The problem seems to be that my code adds up all the even numbers up to 3524578, not just the even Fibonacci numbers. How can I change this?
Many thanks !
You should use a generator function, range() does not suit your problem. You can convert your fib function to a generator by giving yield a inside the while loop, that would make the function keep spitting out fibonacci numbers till n and you can find sum like that.
Example of generator -
>>> def fib(n):
... a, b = 1,2
... while a < n:
... yield a
... a, b = b, a+b
...
>>>
>>>
>>>
>>> for i in fib(200):
... print(i)
...
1
2
3
5
8
13
21
34
55
89
144
you can make similar changes to your function.
Code would look like -
even_sum = 0
def fib(n):
a, b = 1,2
while a < n:
print (a)
a, b = b, a + b
yield a
for i in fib(4000000):
if i % 2 == 0:
even_sum = i + even_sum
print (even_sum)

print the ratio of Fibonacci numbers until a specific condition

I will print to screen first 70 Fibonacci numbers. And then in the same script I also want to print F(i+1)/F(i) ratio until a defined F(i+1)-F(i)<=536 condition is met.
My script prints first 70 Fibonacci numbers but it doesn't print the ratio F(i+1)/F(i).
It gives the following error:
Traceback (most recent call last):
File "fib.py", line 13, in
while b-a > 536:
NameError: name 'b' is not defined
In my code a and b represent F(i) and F(i+1), respectively. How can I fix my code?
#!/usr/bin/python
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a
for c in range(0, 70):
print(F(c))
while b-a > 536:
print 'Ratio:', b/a
Try this:
a,b = 0,1
l = []
def F(n):
global a
global b
a,b = 0,1
for i in range(0, n):
a, b = b, a+b
return a
for c in range(0, 70):
num = F(c)
print(num)
l.append(num)
for i in range(0, len(l)-2):
if l[i+1]-l[i] <= 536:
#print b
#print a
print 'Ratio:', float(b)/a
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a
factorials = []
for c in range(0, 70):
factorials.append((F(c)))
for i in xrange(1,len(factorials)-1):
if factorials[i+1] - (factorials[i]) > 536:
print "ratio :"+str(factorials[i+1]/float(factorials[i]))
The output mainly consists of integers starting with 1.61803, Is that what you were trying to achieve ?
def FR(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a , b/float(a) if b-a > 536 else None
for c in range(0, 70):
fb , ra = FR(c)
print fb if ra is None else fb,' Ratio:', ra
b is not definied in your while (as a).
In fact a and b are only define in the F(n) function and they are local variables.
You should read some documentation about Programming and python first. But the following code should works:
(I suppose that you want while a/b <= 536 as this is not clear in your question)
def F(n):
a, b = 0, 1
for i in range(0, n):
a, b = b, a+b
return a, b
for c in range(0, 70):
a,b = F(c)
print(a)
while a/b <= 536:
print('Ratio:{}/{}'.format(b,a))
a, b = F(a)
An other solution is to totaly rewrite your code:
def F(a, b):
c = a + b
return c,a
a, b = 0, 1
for c in range (0,70):
a, b = F(a,b)
print (a)
while a/b <=536:
print(a/b)
a,b = F(a, b)

Python: Usage of Variables and their difference ("a, b = 0, 1" VS "a = 0", "b = 1") [duplicate]

This question already has answers here:
Python - Difference between variable value declaration on Fibonacci function
(4 answers)
Closed 8 years ago.
I was looking at the Python Manual and found this snippet for a Fibonacci-Number generator:
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
The output is dependent on n and returns a valid Fibonacci sequence.
If you remodel this to use the variables "a" and "b" seperately like so:
def fib(n): # write Fibonacci series up to n
a = 0
b = 1
while b < n:
print(b, end=' ')
a = b
b = a+b
print()
then it will print a number sequence that increments by the power of 2 (e.g. 1, 2, 4, 8, 16 and so on).
So I was wondering why that happens? What is the actual difference between the two uses of variables?
Doing:
a, b = b, a+b
is equivalent to:
temp = a
a = b
b += temp
It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.
The difference is that in your second piece of code, when you do the second line b = a+b, you have already modifed a in the previous line which is not the same as the first piece of code.
Examples
>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a,b = b,a
>>> a,b
3 2
On the other hand, if you use the second approach shown in your question:
>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a = b
>>> b = a
>>> a,b
3 3
In
a, b = b, a+b
the right-hand expressions are evaluated first, and their results are assigned to a and b. This is similar to the following:
_new_a = b
_new_b = a+b
a = _new_a
b = _new_b
On the other hand, in
a = b
b = a+b
you are modifying a before adding it to b. This is equivalent to
a, b = b, b+b
which explains where the powers of two are coming from.

Categories