help finding loop problem?

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

help finding loop problem?

Postby newb1 » Tue Mar 05, 2013 3:27 am

I am a complete newbie. I am slowly going through some tutorials and have tried to write some code. I have been able to fix most of my errors in other programs, but this code is not giving me an error. It seems to be stuck in an endless loop, but I cannot figure out why. Would someone please point out my error? Thank you!!!!!

Code: Select all
#This program is supposed to populate the empty string key
# with the unique characters from the string statement

statement = "xyz123<><><><>x3"
max=len(statement)
key=""
x=0
while x<max:
    if statement[x] in key == False:
        key = key+statement[x]
        x = x+1
        print("1")
        print (key)
        print (statement)
    if statement[x] in key == True:
        x = x+1
        print("2")
        print (key)
        print (statement)
print("3")
print (key)
print (statement)
newb1
 
Posts: 5
Joined: Tue Mar 05, 2013 3:17 am

Re: help finding loop problem?

Postby micseydel » Tue Mar 05, 2013 4:42 am

Just do
Code: Select all
if statement[x] in key:
    # ...
else:
    # ...
x += 1

Don't explicitly compare to True and False. Also, since you're incrementing either way, pull it out of the if/else.

Also, since the number you're using it just an index, it would be cleaner to write
Code: Select all
for char in statement:
    # use char

instead of incrementing an index variable and then constantly checking the index in Python.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: help finding loop problem?

Postby setrofim » Tue Mar 05, 2013 5:40 am

@OP:

Just FYI, your code never terminates because of how Python handles comparison chaining.
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, ...
...
Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

So in your case,
Code: Select all
if statement[x] in key == True:
    ...

is equivalent to
Code: Select all
if (statement[x] in key) and (key == True):
    ...

Since key does not equal to True (or False), neither if suite will execute, so x never gets incremented and your while check always passes.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: help finding loop problem?

Postby micseydel » Tue Mar 05, 2013 7:36 am

Thanks for clarifying that setrofim! I was wondering, but couldn't figure it out (and hoped casevh would answer actually).

By the way, welcome back!
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: help finding loop problem?

Postby newb1 » Tue Mar 05, 2013 11:25 am

Thanks guys!

Setrofim: it's nice to know why it's doing something. Your explanation was perfect and thanks for pointing me to the documentation.

Micseydel: Thanks for showing me how I could clean it up. Being a newbie I don't always think of some of the better solutions.

FYI with your help it works like a charm. I guess I need to read the documentation more. Thanks!!

I left python a little over year ago out of frustration with things like this, like how python 2.xx handled range statements. If the range was too large it would error out due to how it handled the range and running out of memory or something like that. Little handling issues like that drive me up the wall, but I guess I have to get used to it as any language will be that way and programming really is pretty fun.

The working, but not cleaned up version is:
Code: Select all
#This program is supposed to populate the empty string key
# with the unique characters from the string statement

statement = "xyz123<><><><>x3"
max=len(statement)
key=""
x=0
while x<max:
    if statement[x] not in key:
        key = key+statement[x]
        x = x+1
    else:
        x = x+1
print ("key is %s" % key)
print ("statement is %s" % statement)
newb1
 
Posts: 5
Joined: Tue Mar 05, 2013 3:17 am

Re: help finding loop problem?

Postby micseydel » Tue Mar 05, 2013 8:24 pm

Could you give an example of for loops failing? It sounds like you were just using them wrong, and if you learn the proper way you'll start to love them. Below I will show incremental improvement over your current code

Remove two unnecessary lines, use += operator
Code: Select all
while x<max:
    if statement[x] not in key:
        key += statement[x]
    x += 1


Switched to for loop; this will not ever get an index error (no indexing, yay!) and won't get a memory error unless key grows too large (unlikely). This gets rid of three lines, one in the body of the loop, the x indexing variable and the max variable
Code: Select all
for char in statement:
    if char not in key:
        key += char

We like for loops because we can know exactly what the loop is going over by just looking at the head (not checking the body to see how the counter gets incremented, by one or two or something else) and when we look at the body we're not bothered with the details in the header.

Appending to a string in a loop in Python is not guaranteed to be efficient, and so it is considered bad style to do so. Building a list and then using str.join() is preferred. Here is a complete example
Code: Select all
statement = "xyz123<><><><>x3"
key_contents = []

for char in statement:
    if char not in key_contents:
        key_contents.append(char)

print ("key is %s" % ''.join(key_contents))
print ("statement is %s" % statement)


If order doesn't matter, you can skip the loop and let Python do it for you
Code: Select all
key = ''.join(set(statement))

You could use sorted() on the set, too.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: help finding loop problem?

Postby newb1 » Tue Mar 05, 2013 10:49 pm

Honestly, I don't have any of those old examples as it was over a year ago, but I know that it was while I was working through the ProjectEuler problems. I think it was the 10001st prime challenge (#7). Range apparently is limited by the size of the list and I had to use xrange, if I am remembering correctly. It bugged me because on the face of it range should have worked, but had I read the documentation I probably would have found out that limitation of range in Python 2.xx.

I probably was using them wrong as I really am ridiculously new and have very limited time to dedicate to learning. But, I am wanting to learn, so whatever it takes.

Thanks for that walk-through in the ways my code could be improved! I hadn't thought about joining a set.
newb1
 
Posts: 5
Joined: Tue Mar 05, 2013 3:17 am

Re: help finding loop problem?

Postby micseydel » Wed Mar 06, 2013 2:46 am

I know I've gotten MemoryErrors from PE problems but that was never the fault of for loops. Any decent Python 2 tutorial tells you to use xrange() instead of range(), and you won't have a problem.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1390
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 6 guests