简体   繁体   中英

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.

After a return you leave the function, additional returns do nothing.

You can append lists before returning:

def a_range(maxx, step, reverse = False):
    k = list(range(0,maxx,step))
    return k+k[::-1] if reverse else k


print(a_range(10,2))

print(a_range(10,2,True))

The last element of k occures twice if you set reverse to True :

[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8, 8, 6, 4, 2, 0]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM