473,326 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

While and If messing up my program?

CJ

Hey, I'm new to the Python world, but I do have experience in several
other languages. I've been running through a tutorial, and I decided that
I'd make a program that runs through a list, finds if there are any
duplicates. The program, doesn't work, but since its a first build I
wasn't too worried about it. I'd be highly impressed if I got the program
to run correctly in the first build, I want to debug it myself later.

What does worry me, is that I can't seem to get the program by a
certain spot. It keeps giving me the same error, and I don't know why.

The code:

ttllst=[4,3,45,3]
cnto=0
cntt=1
rept=-1

print cnto
print cntt
print ttllst[cnto]
print ttllst[cntt]
choice=raw_input("Begin? ")
if choice == "yes" or choice == "y":
while cnto<>len(ttllst)+1:
if ttllst[cnto]==ttllst[cntt]:
rept=rept+1
if cntt==len(ttllst):
print ttllst[cnto],"appears in the list",rept,"times."
cntt=-1
cnto=cnto+1
rept=-1
cntt=cntt+1
print "done."

After running the program I get error:

Traceback (most recent call last):
File "C:\Python24\Projects\repeatfinderlist", line 13, in -toplevel-
if ttllst[cnto]==ttllst[cntt]:
IndexError: list index out of range
Now, if I remove the while, and the If/choice lines like so:
ttllst=[4,3,45,3]
cnto=0
cntt=1
rept=-1

print cnto
print cntt
print ttllst[cnto]
print ttllst[cntt]
if ttllst[cnto]==ttllst[cntt]:
rept=rept+1
if cntt==len(ttllst):
print ttllst[cnto],"appears in the list",rept,"times."
cntt=-1
cnto=cnto+1
rept=-1
cntt=cntt+1
print "done."
I get no errors. The program doesn't work, granted, but I get no errors.
Can anyone tell me what I'm missing?

Thanks!
-CJ

Oct 5 '05 #1
6 1390
hi,

to get howmany element list appear you can code:
ttllst=[4,3,45,3]
for x in ttllst:
print x, ttllst.count(x)
pass

to get non duplicate element list you can code:
ttllst=[4,3,45,3]
print list(set(ttllst))

Cheers,
pujo

Oct 5 '05 #2
"CJ" wrote:
What does worry me, is that I can't seem to get the program by a
certain spot. It keeps giving me the same error, and I don't know why.
quite often, exception messages means exactly what they say; if
you get an index error, it's because you're trying to fetch an item
that doesn't exist.

for simple debugging, the "print" statement is your friend:
ttllst=[4,3,45,3]
cnto=0
cntt=1
rept=-1

print cnto
print cntt
print ttllst[cnto]
print ttllst[cntt]
choice=raw_input("Begin? ")
if choice == "yes" or choice == "y":
while cnto<>len(ttllst)+1:
print cnto, cntt, len(ttllst)
if ttllst[cnto]==ttllst[cntt]:
rept=rept+1
if cntt==len(ttllst):
print ttllst[cnto],"appears in the list",rept,"times."
cntt=-1
cnto=cnto+1
rept=-1
cntt=cntt+1
print "done."


with that in place, I get

Begin? y
0 1 4
0 2 4
0 3 4
0 4 4
Traceback (most recent call last):
File "test.py", line 14, in ?
if ttllst[cnto]==ttllst[cntt]:
IndexError: list index out of range

which means that your second list index (cntt) is too large.

figuring out how to fix that is left as an etc etc.

</F>

PS. when you've sorted this out, you might wish to check out the
"count" method on list objects:
help(list.count)

Help on method_descriptor:

count(...)
L.count(value) -> integer -- return number of occurrences of value

Oct 5 '05 #3
The specific error in your code, is that when cnto == len(ttllst), then
doing ttllst[cnto] will give you that error.

The list is indexed from 0 to len-1, which means that doing
list[len(list)] will give that error.

Oct 5 '05 #4
On Wed, 05 Oct 2005 00:10:12 -0700, aj****@gmail.com wrote:
hi,

to get howmany element list appear you can code:
ttllst=[4,3,45,3]
for x in ttllst:
print x, ttllst.count(x)
pass

to get non duplicate element list you can code:
ttllst=[4,3,45,3]
print list(set(ttllst))


These are excellent things to use in Python, but for learning programming
skills, they are terrible because they rely on black boxes to do
everything.

I remember once having to code a matrix division algorithm in "the
language of your choice" for a comp sci course. So of course, being a
smart arse, I programmed it in the HP-28S calculator programming language,
which just happened to have matrices as a native object type, complete
with division.

I answered the question exactly, and learnt absolutely nothing from the
exercise. (For the record, I failed that course.)

It is good to tell the original poster how he should be implementing the
code he is trying to write, but that is not as important as helping him
work out where the code is going wrong.

In this case, the problem is that C.J. carefully checks that his indexes
are within the valid range for the list, but (s)he makes that check
*after* attempting to use the indexes. So the code fails before it reaches
the test.

--
Steven.
Oct 5 '05 #5
On Wed, 05 Oct 2005 06:48:59 +0000, CJ wrote:

Hey, I'm new to the Python world, but I do have experience in several
other languages. I've been running through a tutorial, and I decided that
I'd make a program that runs through a list, finds if there are any
duplicates. The program, doesn't work, but since its a first build I
wasn't too worried about it. I'd be highly impressed if I got the program
to run correctly in the first build, I want to debug it myself later.

What does worry me, is that I can't seem to get the program by a
certain spot. It keeps giving me the same error, and I don't know why.


Here are some techniques for tracking down this sort of bug. The best
thing is, these techniques will help you write better code in the first
place, as well as easier to debug.
Firstly, encapsulate your code. Instead of writing one big lump of code,
break it into small digestible functions.

def run_test():
choice=raw_input("Begin? ")
return choice == "yes" or choice == "y"
# or better still:
# choice.lower() in ("yes", "y", "begin"):
def do_test(ttllst):
# initialise variables
cnto=0
cntt=1
rept=-1
# loop through the list, counting duplicates
while cnto<>len(ttllst)+1:

print "debugging...", cnto, cntt

if ttllst[cnto]==ttllst[cntt]:
rept=rept+1
if cntt==len(ttllst):
print ttllst[cnto],"appears in the list",rept,"times."
cntt=-1
cnto=cnto+1
rept=-1
cntt=cntt+1
print "done."
def main():
if run_test():
ttllst=[4,3,45,3]
do_test(ttllst)

if __name__ == "__main__":
# only happens when *running* the file,
# not when *importing* it
main()
Now you have separated your user interface from the business end of your
code, and you can isolate more simply where the error lies.

Continue to encapsulate your code: the while loop is a good candidate. It
runs through the list comparing each character to one known character. So
I would change do_test to look like this:

def do_test(L):
"""Run our item-counting test on list L."""
# loop through the list, counting duplicates
for index in range(len(L)):
current_item = L[index]
item_count = item_counter(L, current_item)
print current_item, "appears in the list", item_count, "times."
# or better still
# print "%s appears in the list %d times." % (current_item,item_count)
print "done"
def item_counter(L, obj):
"""Return the number of times obj is in list L."""
counter = 0
for item in L:
if item == obj:
counter = counter + 1
return counter

Now that you (hopefully) have bug-free code, you can continue to improve
and optimize your program. For example, instead of creating your own
item_counter function, you will soon learn that Python lists have their
own much quicker version.

In general, you want to make your code as general as practical, without
being too specific. You started with the problem "How can I count the
number of times each item in list ttllst exists in ttllst?" A more general
question is "How do I count the number of items *any* object exists in
*any* list?", and then use that code to answer your first question.
Hope this helps,

--
Steven.

Oct 5 '05 #6
CJ

CJ <cj@nowhere.com> wrote in
news:Xn**************************@127.0.0.1:

Thanks! I think I've nailed it. I appreciate all the input!

Oct 8 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: D. Alvarado | last post by:
Hi, I have these files /include/db_info.inc /html_root/util_fns.inc /html_root/home_page.php /html_root/admin/admin_home.php The page "util_fns.inc" contains the line
7
by: Jon Perez | last post by:
When you run an empty while loop under Python , it slows down the rest of the system. Is this normal? And should it be something that needs to be corrected?
4
by: muser | last post by:
I have a logical error in my program, I have submitted the program and my tutor hasn't listed the other problems with the code, but said that the program won't run because of a while statement....
3
by: Anders K. Jacobsen [DK] | last post by:
I simple can't get visual studio 2003 to stop messing with my HTML code. I have unchecked all formating options under Tools / Options / Text editor / HTML/XML / Format I have even tried to...
3
by: Steve Richfie1d | last post by:
Now that it finally works, I'm in the process of converting my large rapid-prototyped Access app into production VB, one DDE-linked piece at a time. One piece now already in VB takes ~2 seconds to...
8
by: MrNobody | last post by:
If I have a control like say a drop down list and I have some kind of onSelectItem change event, is there a way to temporarily suspend the event handling (without removing the event and then...
2
by: Richard Tobin | last post by:
Is the following program legal? (I think it is, though it relies on the existence of intptr_t.) #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> int...
19
Sheepman
by: Sheepman | last post by:
I still messin' around with functions. This is a variant of the program I was messing up early. I'm trying to reduce the amount of work each function is doing. I figured if could get this to work I...
3
by: strangetorpedo | last post by:
The problem lies under where if (choice == '2') is...I need the program to keep prompting for num and den values as long as the user enters values less than or equal to 0. Once they are values...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.