PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] how to remove the extra space after last number

 August 18, 2022     output, printing, python, python-3.x     No comments   

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 separator 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing