Search code examples
pythonpython-3.xfunctionoptional-arguments

Using optional arguments in a function to reverse a range python 3


I need to use an optional argument to take a range and reverse it by using a main function to call the function containing the arguments. My output needs to have the original range, followed by the same list in reverse. I cannot figure out how to put the reversal as an argument to get the output I need. I just end up with the range printed twice in sequential order. I have been playing around with this for hours so any help would be greatly appreciated. The reversal has to be done through the optional argument given to a_range so any answers saying not to do that won't help me.

Immediately below is how I am getting the range in sequential order:

def a_range(max, step):
  return list(range(0,max,step))

def main():
  result = a_range(55,2)
  print(result)

main()

Which gives me the output (sorry if formatting is wrong):

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 
40, 42, 44, 46, 48, 50, 52, 54]

When I try to add a 3rd argument that reverses the same list:

def a_range(max, step, opt_arg = list(range(0,55,2))[::-1]):
    return list(range(0,max,step))
    return list(range(0,max,step,opt_arg)


def main():
    result = a_range(55,2)
    opt_arg = list(range(0,55,2))[::-1]
    print(result)
    other_result = a_range(55,2,opt_arg)
    print(other_result)


main()

I get the output:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 
40, 42, 44, 46, 48, 50, 52, 54]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38,  
42, 44, 46, 48, 50, 52, 54]

This is exactly how I need the output to be printed, but the 2nd repeat needs to be in reverse.


Solution

  • There are a few errors in your code, the main one being that your optional argument should be a boolean flag.

    Here is how you could implement it.

    def prange(start, stop, step=1, reverse=False):
        fst = list(range(start, stop, step))
        if reverse:
            return (fst, list(reversed(fst)))
        else:
            return (fst,)
    
    print(*prange(3, 6, reverse=True))
    

    Output

    [3, 4, 5] [5, 4, 3]