I need to print out the array in reverse order without using the reverse(). The output of my code just printed 13. Is there something missing in my code? Still new to python so I’m stumbling about just to figure out how things works.
This is my code:
arr = [1, 3, 5, 7, 9, 11, 13]
def oddNumberReverse(arr):
i = len(arr) - 1
while i < len(arr):
if arr[i] % 2 == 1:
print (arr[i])
i += 1
return (arr)
oddNumberReverse(arr)
The output should be the full array in reverse order but my output is 13.
>Solution :
There are quite a few problems in your attempt:
1.Keep the return outside the while loop
2.Take an empty list lst to append values
3.while should go greater than 0
4.append values arr([i]) to lst
arr = [1, 3, 5, 7, 9, 11, 13]
def oddNumberReverse(arr):
i = len(arr) - 1
lst = []
while i > 0:
if arr[i] % 2 == 1:
lst.append(arr[i])
i -= 1
return lst
oddNumberReverse(arr)
#output
[13, 11, 9, 7, 5, 3]