Count to zero then Count up

前端 未结 2 1241
长发绾君心
长发绾君心 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:02

    If you can use range, I would do it like this in Python 2.7:

    f = lambda x : map(abs, range(-x,x+1))
    for x in f(4):
        print x,
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题