0

How to remove the last "add -->" from the output when using end, i am not using sep here, bcoz sep will not have any effect here , as the print statement prints just 1 item at a time here and ends with incr of i

def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end=' add -> ')

my output

0 add -> 1 add -> 1 add -> 2 add -> 3 add -> 5 add -> 8 add -> 13 add -> 21 add -> 34 add -> 

3 Answers3

2

you can use an if statement to check if its the last number:

def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end='')
    if i != N-1:
        print(' add -> ', end='')
Grant Williams
  • 1,469
  • 1
  • 12
  • 24
  • Using Sep is better in every way, but if you aren't allowed to use that for some reason (maybe a class?) Then this works fine – Grant Williams Apr 20 '18 at 21:12
  • @GrantWilliams: Is `sep` better in every way, or might it be less scalable? Wouldn't the call using `*map()` expand the whole list into memory, whereas the `if` method would not? – Jeff Learman Apr 20 '18 at 21:16
  • 1
    @JeffLearman, hard to say as far as performance goes. I was mostly talking about ease of use/readability. It would be interesting to test it though. I would guess the best performance would come from using a list comprehension with sep, but im also too lazy to test it – Grant Williams Apr 20 '18 at 21:26
  • 1
    Using a quick test with a generator, *args caused the whole list to be created, so in some cases it's not the best solution. But not in the case of printing, so `sep` is definitely better here. – Jeff Learman Apr 20 '18 at 22:02
2

The inevitable pythonic one-liner:

print(*map(fibonaci_num, range(N)), sep=' add -> ')
fferri
  • 18,285
  • 5
  • 46
  • 95
0

Here I've simplified answer using ternary operator. May it will be helpful and better.

def fib(n):    
    a, b = 0, 1
    while a < n:
        endstatement = '-' if (b < n) else ''
        print(a, end=endstatement)
        a, b = b, a+b
    print()


# Now call the function:
fib(1000)

Result: 0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987

Krunal
  • 77,632
  • 48
  • 245
  • 261