function that prints counding down numbers and up but in a pattern

I am posting this to contrast the other answers provided here –

def f(n, s = ""):
  if n <= 0:
    print(s, n)
  else:
    print(s, n)
    f(n - 1, s + " ")
    print(s, n)

f(5)
 5
  4
   3
    2
     1
      0
     1
    2
   3
  4
 5

The program could be further simplified, if desired –

def f(n, s = ""):
  print(s, n)
  if n > 0:
    f(n - 1, s + " ")
    print(s, n)

f(5)

Default parameter s could be an integer instead of a string, if desired –

def f(n, s = 0):
  print(" "*s, n)
  if n > 0:
    f(n - 1, s + 1)
    print(" "*s, n)

f(5)

Output is the same.


print adds a space between the printed arguments. To remove this, we can print a single formatted value –

def f(n, s = ""):
  print(s + str(n))          # <- single value
  if n > 0:
    f(n - 1, s + " ")
    print(s + str(n))        # <- single value

Or you can use a formatted string literal

def f(n, s = ""):
  print(f"{s}{n}")     # <- formatted string
  if n > 0:
    f(n - 1, s + " ")
    print(f"{s}{n}")   # <- formatted string

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top