0
def recur(n):
    print(n)
    if n>1:
        recur(n-1)

How can this be converted to just line. I can not find a way to use the logic as recur = lambda x: print(x) if.......

I can not even use

func = lambda x: [print(i) for i in range(x,0,-1)]
Deshwal
  • 3,436
  • 4
  • 35
  • 94
  • 3
    Does this answer your question? [Can a lambda function call itself recursively in Python?](https://stackoverflow.com/questions/481692/can-a-lambda-function-call-itself-recursively-in-python) – dangee1705 May 08 '20 at 14:51

3 Answers3

2

If you want the numbers printed on the same line, you can use the end= parameter of the print function:

printDown = lambda n: print(n,end=" ") or printDown(n-1) if n>1 else print(n)

printDown(10)

10 9 8 7 6 5 4 3 2 1

If you want them on separate lines:

printDown = lambda n: print(n) or (printDown(n-1) if n>1 else None)

printDown(10)

10
9
8
7
6
5
4
3
2
1
Alain T.
  • 40,517
  • 4
  • 31
  • 51
2

One possible recursive lambda:

recur = lambda n: [print(n), recur if n>1 else lambda x: None][1](n-1)

recur(10)

Prints:

10
9
8
7
6
5
4
3
2
1
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

In Python >= 3.8, you can do it in one line entirely:

print(*(x := lambda n: [n]+x(n-1) if n else [])(10), sep='\n')
10
9
8
7
6
5
4
3
2
1

Note that this also does not abuse a comprehension or expression for side effects. x can still be used to create a common list now:

x(5)
# [5, 4, 3, 2, 1]
user2390182
  • 72,016
  • 6
  • 67
  • 89