Count to zero then Count up

前端 未结 2 1242
长发绾君心
长发绾君心 2020-12-22 14:20

Since im fairly new to python and programming i have a question of a very basic nature. I want to make a iteration function and a recursive function that does this:

2条回答
  •  粉色の甜心
    2020-12-22 15:15

    Iterative implementation:

    >>> def bounce(num):
    ...     limit, delta = num + 1, -1
    ...     while(num != limit):
    ...         print num
    ...         num += delta
    ...         if num == 0:
    ...             delta = 1
    

    Recursive implementation:

    >>> def bounce(num):
    ...     print num
    ...     if num: 
    ...         bounce(num - 1)
    ...         print num
    ...         
    ... 
    

    Output in both the cases:

    >>> bounce(4)
    4
    3
    2
    1
    0
    1
    2
    3
    4
    

提交回复
热议问题