简体   繁体   中英

A Function take 'N' as argument, performs an Increase N times of Elements then decrease (N-1) times and then return as a list in the Python

The problem is, suppose I pass 'N' = 9 to the function,

So the list will be list = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]. At first, the list elements increased to (1-9) then it decreased to reversed order (8-1)

Please suggest the easiest way to achieve this. Thank You in advance.

list(range(1, 1+N)) + list(range(N-1, 0, -1))

You can use list comprehension to achieve in one line. First we have the list comprehension which has a simple loop that appends the number from 1 to n . The second is a list comprehension where the numbers in the for loop are passed through the equation (n+1)-i . This is to calculate the difference between the current value of i and n+1 . This gives us the pattern of descending numbers. Finally, both lists are added and stored in the variable r .

r = [x for x in range(1,n+1)] + [n+1-i for i in range(2, n+1)]

When r is printed out it produces the following output.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]

A simple way would be to use a range from -8 to 8 and output the difference from 9 (ignoring the sign):

N = 9

print([N-abs(i) for i in range(1-N,N)])

[1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]

the range(1-N,N) will generate:

-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8

in absolute value this will be:

8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8

difference from 9

9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9
8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8 -
-------------------------------------------------
1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1

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