https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-loops
I’m working on Python Code Challenges: Loops (#3. Delete Starting Even Numbers).
The instructions are:
This function will repeatedly remove the first element of a list until it finds an odd number or runs out of elements. It will accept a list of numbers as an input parameter and return the modified list where any even numbers at the beginning of the list are removed.
My solution was:
def delete_starting_evens(my_list):
for num in my_list:
if num % 2 == 0:
my_list.remove(num)
else:
return my_list
In my mind, my second line of code addresses the looping through from “the first element of a list”. My third line of code addresss the “until it finds an odd number”. My fourth line of code addresses the “even numbers at the beginning of the list are removed”.
The output is None
and I don’t understand why. Also, my function body is completely different from the Codecademy Solution (see below):
def delete_starting_evens(my_list):
while (len(my_list) > 0 and my_list[0] % 2 == 0):
my_list = my_list[1:]
return my_list
Is there any way to work with my code (including my for
and if
and else
statements to solve the question? Or is my thinking completely off?
for loop or while loop doesn’t matter.
Your solution doesn’t guarantee the function will return something with every input (hence the None). The other issue is you just want to make it so that the list only has the first element as odd (the rest don’t matter). The other issue is that you’re iterating an object you’re modifying mid loop, which is a bit unsafe and hard to reason about.
Codecademy solution is also a bit off
while (len(my_list) > 0 and my_list[0] % 2 == 0):
my_list = my_list[1:]
The problem with this is that list splicing makes a copy of the list (so it will iterate again under the hood). At first that’s going to be size n-1, then n-2, etc all the way down to 1. That summation is famously known as the triangular number (or n choose 2) which is O(n^2) (not ideal). (this is assuming a worst case scenario, which is typical for interviews). The worst case of course is a list with almost all even numbers to start and one final one is odd. It has to repeatedly make copies that get discarded.
Alternative solution
def delete_starting_evens(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 != 0:
return numbers[i:]
return []
@fedegl you might want to have this reviewed.
PS:
There’s a nice visual intuition about why the summation n+n-1+ … +2 + 1 is O(n^2). If you draw it out in blocks it forms a right triangle with equal sides that meet at the right angle. Half of a square… and in big O we drop constants. so 0.5n^2 = O(n^2)
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
3 Likes