New to python - trying to figure out my mistake with my code

This is the place for queries that don't fit in any of the other categories.

New to python - trying to figure out my mistake with my code

Postby Greggles » Thu Oct 17, 2013 8:29 pm

Hi,
I'm trying to figure out why my code is giving me an error. Any help is appreciated. Apologies if I am posting this in the wrong place. Very new to python so my code may seem novice to many of you.
Thanks.

Code: Select all
def only_evens(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers.
   
    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """

    even_lists = []
    sublist = 0
    for sublist in lst:
        value = 0
        even_sublist = True
        while value in range(len(lst[sublist])):
            if lst[sublist][value] % 2 == 0:
                value = value + 1
            else:
                even_sublist = False
        if even_sublist == True:
            even_lists.append(lst[sublist])
    return even_lists
Last edited by stranac on Thu Oct 17, 2013 8:40 pm, edited 1 time in total.
Reason: Added code tags. Locked.
Greggles
 
Posts: 1
Joined: Thu Oct 17, 2013 8:24 pm

Re: New to python - trying to figure out my mistake with my

Postby stranac » Thu Oct 17, 2013 8:58 pm

What error are you getting?
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 891
Joined: Thu Feb 07, 2013 3:42 pm

Re: New to python - trying to figure out my mistake with my

Postby micseydel » Thu Oct 17, 2013 10:36 pm

You seem to be confused about how for loops work. My recommendation (besides stranac's fabulous one) is that you revisit a tutorial on for loops, don't try to use a while loop, and don't try to use range() or xrange() either.

I can write this function as one simple line, a list comprehension with a sum() call at the end passing a generator to it. Without doing anything too fancy, I did it in 9 lines. (Ok, it was a little fancy but you should be able to do it in a couple more at the most.) My point is: if you find yourself writing a ton of code, you're overcomplicating things.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 929
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: New to python - trying to figure out my mistake with my

Postby MaliZeko » Thu Oct 17, 2013 11:15 pm

Well, the error you are talking about occurs here:
Code: Select all
while value in range(len(lst[sublist])):

You defined sublist as an integer here:
Code: Select all
sublist = 0

But then you use sublist as an item to iterate through lst:
Code: Select all
for sublist in lst:

So sublist changes to whatever list in lst you are currently looping through.
The error is that you use a list (sublist) as an index for lst:
Code: Select all
while value in range(len(lst[sublist])):

And list indices cannot be lists.
To avoid that, you should have written:
Code: Select all
for sublist in range(len(lst)):

instead of
Code: Select all
for sublist in lst:

Now your code shouldn't be crashing anymore, BUT:
It's still not working the way you want it to.
The problem with your code is that your while loop never ends; this is due to a "fatal" mistake you made :P
You increment value ONLY in your if-clause:
Code: Select all
 if lst[sublist][value] % 2 == 0:
    value = value + 1

However, if the first number is odd - value remains 0!
So
Code: Select all
while value in range(len(lst[sublist])):

is always true, and your loop won't progress.
Increment value outside of your if-clause like this:
Code: Select all
while value in range(len(lst[sublist])):
    if lst[sublist][value] % 2 == 1:
        even_sublist = False;
    value += 1

and it should be working.

P.S.:
There is a significantly easier way to do it - as pointed out by micseydel, you have unnecessary loops and variables. However, this should work for now.
MaliZeko
 
Posts: 2
Joined: Thu Oct 17, 2013 10:40 pm

Re: New to python - trying to figure out my mistake with my

Postby hrs » Fri Oct 18, 2013 9:36 am

MaliZeko wrote:To avoid that, you should have written:
Code: Select all
for sublist in range(len(lst)):

instead of
Code: Select all
for sublist in lst:

No. Noone should ever do that.
I think that "should work for now"-style code isn't an objective of this forum.
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

Re: New to python - trying to figure out my mistake with my

Postby MaliZeko » Sat Oct 19, 2013 9:52 pm

hrs wrote:
MaliZeko wrote:To avoid that, you should have written:
Code: Select all
for sublist in range(len(lst)):

instead of
Code: Select all
for sublist in lst:

No. Noo
ne should ever do that.
I think that "should work for now"-style code isn't an objective of this forum.


Terrific answer.
I'm sure Greggles' question is resolved by your helpful response, lacking neither quality nor depth.
Just a side note:
Why not elaborate why "noone should ever do that" and how your answer has helped anyone here?
And if you're not too busy, why not give the asker a better alternative for his code?
Thank you.
MaliZeko
 
Posts: 2
Joined: Thu Oct 17, 2013 10:40 pm

Re: New to python - trying to figure out my mistake with my

Postby micseydel » Sat Oct 19, 2013 10:14 pm

You should never iterate over the indexes, and instead over the elements themselves. To iterate over the indexes is error prone and harder to read. Typically, you don't need the index, and you do want the element, so iterating over the indexes is very misleading. When you do need the indexes, you can use enumerate()
Code: Select all
for index, element in enumerate(iterable):
    print element, "is at index", index

Even when I need the index and not the element, I prefer to use enumerate so that people can see explicitly that that code is doing what it is meant to
Code: Select all
for index, _ in enumerate(iterable):

(People know to ignore a _ variable.)
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 929
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests