0

I understand that this is the easiest and most simplest way to check:

if val == val[::-1]:
    print "yes"
else:
    print "no"

but just for practice, I wanted to test it with nested for loops (using the reversed() function -- I spent hours but couldn't quite figure where to continue and break to get it right:

for i in val:
    for j in reversed(val):
        if i == j:
            break
    break
eozzy
  • 66,048
  • 104
  • 272
  • 428

3 Answers3

3

this should do it:

for i, j in zip(val, reversed(val)):
    if i != j:
        print 'no'
        break
else:
    print 'yes'

EDIT: many thanks to @jamylak for pointing out the else clause on for loops. I keep forgetting that!

But then, I'd probably just do:

print 'yes' if list(val) == list(reversed(val)) else 'no'
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
2
for i in range(len(val)/2):
    if val[i] != val[-i-1]:
        return False
return True
gefei
  • 18,922
  • 9
  • 50
  • 67
0

This is not a usecase of nested loops. Nested loops are useful when you want to compare each element of something with each element of something else. In your case you only want to compare the first position with the last, the second with the second last and so on. You need to do this:

for i in range(len(val)/2):
    if val[i] != val[-i-1]:
        continue
    else:
        break
acid_crucifix
  • 362
  • 2
  • 12
  • It is the same as the above answer and that should be given preference as the correct answer.. I have simply used it to show continue and break and also explain why nested loops are not apt – acid_crucifix May 18 '12 at 09:17