Hi I'm trying to create a Fibonacci sequence generator in Python. This is my code:
d =raw_input("How many numbers would you like to display")
a = 1
b = 1
print a
print b
for d in range(d):
c = a + b
print c
a = b
b = c
When I ran this program, I get the error:
File "Fibonacci Sequence Gen.py", line 10, in <module>
for d in range(d):
TypeError: range() integer end argument expected, got str
Thanks for your help, I'm trying to teach myself python with basic projects.
raw_input returns a string. So convert d to an integer with:
d = int(d)
One more thing: Do not use for d in range(d). It works but it is awful, unpythonic, whatever.
Try this way for example:
numbers = raw_input("How many numbers would you like to display")
a = 1
b = 1
print a
print b
for d in range(int(numbers)):
c = a + b
print c
a = b
b = c
Edit: I complete below the answer with additional code tuning (thanks to commenters):
# one space will separate better visually question and entry in console
numbers = raw_input("How many numbers would you like to display > ")
# I personnally prefer this here, although you could put it
# as above as `range(int(numbers))` or in `int(raw_input())`
# In a robust program you should use try/except to catch wrong entries
# Note the number you enter should be > 2: you print 0,1 by default
numbers = int(numbers)
a, b = 0, 1 # tuple assignation
# note fibonnaci is 0,1,1,2,3...
print a # you can write this as print "%i\n%i" % (a, b)
print b # but I think several prints look better in this particular case.
for d in range(numbers - 2): # you already printed 2 numbers, now print 2 less
c = a + b
print c
a, b = b, c # value swapping.
# A sorter alternative for this three lines would be:
# `a, b = b, a + b`
# `print b`
Problem
The problem here is that here:
d = raw_input("How many numbers would you like to display")
you assign string from the input into the d variable, and later you pass it to range(). But range() expects expects integers, not strings, and Python does not convert it automatically (it leaves conversion to you).
Solution
The solution is to convert result of raw_input() into int like that:
d = int(raw_input("How many numbers would you like to display"))
and everything will work unless you provide non-integer.
But there is better (shorter, more efficient, more encapsulated) method of generating Fibonacci numbers (see below).
Better method of generating Fibonacci numbers
I believe this is the best (or nearly the best) solution:
def fibo(n):
a, b = 0, 1
for i in xrange(n):
yield a
a, b = b, a + b
This is a generator, not a simple function. It is very efficient, its code is short and does not print anything, but you can print its result like that:
>>> for i in fibo(20):
print i,
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
or convert it into a list like that:
>>> list(fibo(20))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
Applying the above in your case
After applying the above to your code, it could look like this:
def fibo(n):
a, b = 0, 1
for i in xrange(n):
yield a
a, b = b, a + b
d = int(raw_input("How many numbers would you like to display"))
for i in fibo(d):
print i
Does it answer your question?
You have to convert the input to a number, like this:
d = int(raw_input("How many numbers would you like to display: "))
Also, just for fun, the fibonacci sequence can be expressed more succinctly:
a, b = 0, 1
for i in range(d):
print a
a, b = b, a+b
raw_input returns string type.You need to convert it to int.
>>> x = raw_input()
2
>>> x
'2'
>>> type(x)
<type 'str'>
and range function requires int as an argument not string.
Thats why when i do
>>> range(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got str.
So, change it to
for x in range(int(d)):
Simpler method:
a = [0,1]
for n in range(1,41):
a.append(a[n]+a[n-1])
print a[-1]
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
165580141
I see many over complicated Fibonacci Sequence programs so I just did this with a while loop; changing the number after the while loop
a = 0
b = 1
while a <= 1000000000: #Changing this number will change how long the sequence goes on for
print(a)
print(b)
a = a+b
b = b+a
I know this isn't your program but it is a very basic version;
I hope this helps :)
Related
Considering that epsilon is the smallest number that you can add to one.
I'm getting 1 instead of 1+epsilon when I perform the addition and print the result.
I've implemented a getEpsilon function. I added a print statement for debugging.
The function is implemented as follows:
def getEpsilon():
a = np.float128(1)
b = np.float128(1)
c = np.float128(2)
while a + b != a:
b = b / c
d = a+b
print (F"b={b:3.50f}, d={d:3.50f}")
return b * c
After some iterations of the while loop the value of d is just 1, but a + b != a still evaluates as True.
This is the output:
b=0.5000000000000000000000000, d=1.5000000000000000000000000
b=0.2500000000000000000000000, d=1.2500000000000000000000000
...
b=0.0000000000000004440892099, d=1.0000000000000004440892099
b=0.0000000000000002220446049, d=1.0000000000000002220446049
b=0.0000000000000001110223025, d=1.0000000000000000000000000
b=0.0000000000000000555111512, d=1.0000000000000000000000000
...
b=0.0000000000000000001084202, d=1.0000000000000000000000000
b=0.0000000000000000000542101, d=1.0000000000000000000000000
Why does a + b != a have a different behavior than d = a+b
It looks like some operation is done with 64 bits instead.
If I repeat it with the float64 equivalent type the result is (last 2 lines):
b=0.0000000000000002220446049, d=1.0000000000000002220446049
b=0.0000000000000001110223025, d=1.0000000000000000000000000
I would like pass the variables into the function that uses range(). How do I pass variable C that has more then one number via one variable. Something like range(5, 10, 2)?
Here is my example code:
a = 0
b = 10
c = 2
def num_count(a, b, c):
for number in range(c):
a += b
print("New Count is: {0}".format(a))
I tried passing it as a string and converting it to an integer as well as by using a list. Nothing worked.
you can pass in the range like you mentioned with only a small change to the
for loop
a = 0
b = 10
c = range(5, 10, 2)
def num_count(a, b, c):
for number in c:
a += b
print("New Count is: {0}".format(a))
num_count(a,b,c)
or, as khelwood* mentioned, pass in a list/tuple and expand it with *
a = 0
b = 10
c = (5, 10, 2)
def num_count(a, b, c):
for number in range(*c):
a += b
print("New Count is: {0}".format(a))
num_count(a,b,c)
both output 30 which is expected
I had written a simple pascal triangle code in python but I am getting a error
def factorial(n):
c=1
re=1
for c in range(n):
re = re * c;
return(re)
print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
for c in range(n-i-1):
print ""
for c in range(i):
a = factorial(i);
b = factorial(c);
d = factorial(i-c);
z = (a/(b*d));
print "%d" % z
print "\n"
ERROR:
Traceback (most recent call last):
File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
Your factorial() function returns 0 for any input because of how you defined your range.
The range builtin starts at 0 unless otherwise defined so:
for c in range(n):
re = re * c # no semicolons in Python
is doing:
re = re * 0
on the first iteration so for all subsequent iterations:
re = 0 * c
will always be 0
Start your range at 1 like so
for c in range(1, n):
re *= c # The *= operator is short hand for a = a * b
you can see this more explicityly:
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>>
or instead of rolling your own function use the one that comes with Python:
>>> from math import factorial
>>> factorial(3)
6
Upon closer reading of your code it seems you tried to circumvent this by setting c = 1 outside your for loop. This is not going to work because the variables you declared outside the loop are being reassigned inside it.
ZeroDivisionError means that you were trying to divide or modulo, a number n with 0.
in your case, z = (a/(b*d)) resulted in z = (a/0)
Also, as #theB pointed out, your factorial function is incorrect.
Try fixing those.
Also, you don't really need ; in your code. It's usually the case we put ; when we want to make the code one liner.
UPDATED
a = int(input("Give a value: "))
b = int(input("Give a value: "))
c = int(input("Give a value: "))
def middle(a, b ,c) :
m = min(a,b,c)
M = max(a,b,c)
return a+b+c-m-M
This is where im at. It takes my numbers into the data. How would I get it to display the middle one?! Sorry I'm so terrible at this. Way in over my head on this intro course. #CommuSoft #Zorg #paxdiablo and everyone else
Like others mentioned, you're missing a colon, but for simplicity sake:
def middle(a, b, c):
return sorted([a, b, c])[1]
You should put a colon (:) on the first line (def) as well.
This works for the online python environment:
def input(a, b, c) :
if a <= b <= c or c <= b <= a :
return b
elif b <= a <= c or c <= a <= b :
return a
else:
return c
Furthermore it is more advisable to make use of min and max I guess. Min and max are sometimes directly supported by a CPU and there are implementations that avoid branching (if-then-else's):
def input(a, b, c) :
m = min(a,b,c)
M = max(a,b,c)
return a+b+c-m-M
or:
def input(a, b, c) :
return min(max(a,b),max(b,c),max(a,c))
The last one is also numerically stable.
In most cases if-then-else clauses should be avoided. They reduce the amount of pipelining although in interpreted languages this might not increase performance.
Based on the comments, I guess you want to write an interactive program. This can be done like:
def middle(a, b, c) : #defining a method
return min(max(a,b),max(b,c),max(a,c))
a = int(input("Give a value: "))
b = int(input("Give b value: "))
c = int(input("Give c value: "))
print("The requested value is ")
print(middle(a,b,c)) #calling a method
Defining a method will never result in Python using that method. The a, b and c in the def block are not the a, b and c in the rest of your program. These are "other variables that happen to have the same name". In order to call a method. You write the methods name and between brackets the parameters with which you wish to call your method.
Post your full syntax error (or any other full traceback) whenever you're having trouble.
And your def line needs a colon.
You could do:
def middle(a,b,c):
s={a,b,c}
s-={min(s),max(s)}
return s.pop()
What this does:
Create a set of the unduplicated values:
>>> a,b,c=1,2,3
>>> s={a,b,c}
>>> s
{1, 2, 3}
Remove the max and the min, leaving the middle:
>>> s-={min(s), max(s)}
>>> s
{2}
Pop the only remaining value:
>>> s.pop()
2
I am trying to write a program in Python, but I am stuck in this piece of code:
def function():
a=[3,4,5,2,4]
b=1
c=0
for x in range(5):
if a[x-1]>b:
c=c+1
return c
print(function())
It gives me value 1 instead of 5. Actually the function I am trying to write is a little bit more complicated, but the problem is actually the same, it doesn't give me the right result.
def result():
r=[0]*len(y)
a=2
b=an_integer
while b>0:
for x in range(len(y)) :
if y[x-1] > 1/a and b>0:
r[x-1]=r[x-1]+1
b=b-1
a=a+1
return r
print(result())
v is a list of values smaller than 1 and b has an integer as value. If some values x in v are bigger than 1/a then the values x in r should get 1 bigger, then it should repeat a=a+1 until b becomes 0. I want this function to give a result of the type for ex. [7,6,5,4,3] where the sum of the elements in this list is equal to b.
Sometimes it gives me the right value, sometimes not and when the elements in v are equal for example v=[0.33333,0.33333,0.33333] it gets stuck and doesn't give me a result.
I don't know what I am doing wrong !
Your return statements are incorrectly indented. You want to return after the loop ends, not inside the loop.
def function():
a = [3, 4, 5, 2, 4]
b = 1
c = 0
for x in range(5):
if a[x-1] > b:
c = c + 1
return c
Also, a couple of optimizations to the code:
def function(a, b):
c = 0
for x in a:
if x > b:
c += 1
return c
or further:
def function(a, b):
return sum(x > b for x in a)
return; only inside the fun in the end it.
and name the Variable v