Issue
In my program, I am printing an extra space after the last number. How can I remove that?
def fibonacci(n):
a = 0
b = 1
if n == 1:
print(a, end=' ')
else:
print(a, end=' ')
print(b, end=' ')
for i in range(2, n):
c = a + b
a = b
b = c
print(c, end=' ')
fibonacci(int(input()))
Input: 5
Output: 0 1 1 2 3
I'm printing an extra space after the last number.
Solution
Separate the process of generating the numbers, from the process of printing them. (This is something you should do anyway, but it also happens in this case to make it easier to solve the problem.) For example, we can use a generator to yield
multiple values. Notice that we don't need to handle any special cases, and we can also use the pack-unpack idiom for multiple assignments:
def fibonacci(n):
a, b = 1, 1
for i in range(n):
yield a
a, b = b, a + b
Now we can display these values separated by spaces by using the sep
arator for print
rather than the end
, and passing each of the values as a separate argument. To do that, we need explicit unpacking with *
. It looks like:
print(*fibonacci(10), sep=' ')
And we get the desired result, with no trailing space:
1 1 2 3 5 8 13 21 34 55
Answered By - Karl Knechtel Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.