Skip to content
Advertisement

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

I already know how to count down and up using reccurssive function but I cant figure out how to define another function to have spaces in a pattern like this: Desired output

My code for counting down and up:

def f(n):
if n==0:
    print (n)  
    return
print (n) 
f(n-1)  
print (n)  

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement