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.
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
A @Carcigenicate suggested you can use a list,
In the following code have just replaced the print
statements with list.append()
def fibonacci(n):
l1=[]
a = 0
b = 1
if n == 1:
print(a, end=' ')
l1.append(str(a))
else:
l1.append(str(a))
l1.append(str(b))
for i in range(2, n):
c = a + b
a = b
b = c
l1.append(str(c))
tr=" ".join(l1)
print(tr,end='')
print('h',end='')
fibonacci(int(input()))
output:
8
0 1 1 2 3 5 8 13h
as you can see in the output there is no extra space after last number 13
and i have printed h
after 13
.
hope this helps you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.