Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Code not running!! Please help

nested loop

  • Please log in to reply
3 replies to this topic

#1 king_koder

king_koder

    CC Lurker

  • Just Joined
  • Pip
  • 7 posts

Posted 24 October 2010 - 07:52 AM

Hi,
I tried running the following code in IDLE (3.1.2) and it just closed after running some time. Could you guys help me out with this. I also tried running the program in Geany and there was the same problem.

a=100
b=100
great=0
multiples=[]
palin=[]

#create nested loops to create list of multiples of all three digit numbers.

while a<1000:
    while b<1000:
        multiples.append(a*b)
    b+=1
a+=1

for n in  multiples:
    if str(n)==str(n)[::-1]:
        palin.append(n)

for a in  palin:
    if a>great:
        great=a

print(great)

The code is supposed to find the greatest palindromic number formed by the multiplication of two 3-digit numbers.
  • 0

#2 Vswe

Vswe

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1989 posts
  • Programming Language:Java, C#, PHP, Python, JavaScript, PL/SQL, Visual Basic .NET, Lua, ActionScript

Posted 24 October 2010 - 08:05 AM

You've made two infinite loops, b will always be < 1000 and a will always be < 1000. You have to move the increasing part one step further to the right.
  • 0

#3 Vladimir

Vladimir

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 79 posts

Posted 05 November 2010 - 01:30 PM

Instead of using while loop, which is unpythonic and slow for some reason, you have to use this construction in Python:

for a in range(1000):
    print(a)

This will make your code more clear and prevent from typical mistakes (infinitive loop in your case).
  • 0

#4 BrockyL

BrockyL

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 13 December 2010 - 10:21 AM

if str(n) == str(n)[::-1]:
this is to say compare a string (ex:'abc') to itself backwards which looking up the first bit which is probably a palindrome itself stored on the harddrive. is not going to ever equal itself backwards.
simply multiplex the two lists like you did in the first loop, or even more tricky there is a list lookup feature of python eg:
if (str(n)[::-1] in otherlist):
print str(n)+" and "+str(otherlist[otherlist.index(str(n)[::-1])])+" are palindromes."
requiring only one loop. :)
  • 0





Also tagged with one or more of these keywords: nested loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download