The signature of range
is:
range(start, stop[, step])
If you want to list all odd numbers in the range [0, n], you just have to analyze that the first odd number is 1 and always the next one will be two positions away; in other words, pick the numbers every two starting at 1:
impares = range(start=1, stop=n, step=2)
Therefore, to display them in reverse, simply:
n = int(input('Valor de n: '))
impares = list(range(1, n, 2))
print(impares[::-1])
Thus:
>>> Valor de n: 10
[9, 7, 5, 3, 1]
Inclusive, the value of step
can be negative and you generate the sequence already in reverse order. Just remember that the value of start
belongs to the range generated by range
, then you’ll need to decide if n
should appear in the result or not if it is odd.
n = int(input('Valor de n: '))
# Se n é par, inicia em n-1, se ímpar inicia em n-2
n = n-1 if n % 2 == 0 else n-2
print( list(range(start=n, stop=0, step=-2)) )
Thus:
>>> Valor de n: 10
[9, 7, 5, 3, 1]
Alex, I strongly suggest you read the documentation and seek to understand what the function
range
makes and what are its parameters. Your solution is practically ready, just need to set the proper values.– Woss
Brother I think the most appropriate was the
filter()
I’ll try to rewrite my code– user141036
No, just the
range
does what you want, use thefilter
will be unnecessary. But try to use it too.– Woss
and thus only use the
range
?– user141036
You used the range in the code you posted. You didn’t get the result you wanted. Study the function, analyze the values you passed as parameter along with the result you got and see what you did wrong. You literally only need to change 2 values in your code to work. Understanding exactly what you did will know where to fix.
– Woss