The simplified question is:
Given a list of numbers, write a Python script that will remove the last odd number from the list.
One of the challenges is if the last odd number appears multiple times, some approaches will remove the first occurrence of that number, rather than the last.
One solution that I have is to find the max index for the odd numbers and then pop that number from the list:
def remove_last_odd(numbers):
count = 0
for num in numbers:
if num%2 == 1:
max = count
count += 1
print max
numbers.pop(max)
def run():
numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22, 93, 48, 76, 15, 7]
print numbers
remove_last_odd(numbers)
print numbers
run()
This works, but I feel like there's got to be a better way. I've thought about reversing the list, removing the first odd number and then re-reversing:
# use this instead of remove_last_odd function
def remove_backwards(numbers):
rev_num = numbers[::-1]
for num in rev_num:
if num % 2 == 1:
rev_num.remove(num)
numbers = rev_num[::-1]
return numbers
This also works, and feels cleaner, but if anyone can provide advice on preferred methods/more Pythonic approaches, it'd be much appreciated!
run
function could be made into a doctest forremove_last_odd
. \$\endgroup\$