hi,

i have a function that returns a string. For eg: 11111 or 11011.
1 is Pass and 0 is Fail. i want my code to scan the string from right to left side and also look for 0 and indicate its location. Below is my code. But i'm having problem:
1. It scans from left to right.
2. It scans the string bit by bit and so goes into the except part of the code.

c=('01101')

i=-1
try:
    while i<len(c):
        i=c.index('0',i+1)
        print "Lane fail",i        
except ValueError:    
    print "All Lanes PASS"
    pass

Result:
>>>
Lane fail 0
Lane fail 3
All Lanes PASS

What i want the Result to show:
>>>
Lane fail 0
Lane fail 3

thanks

You're working too hard, and you should avoid using an exception for a 'normal' circumstance. The 'Ask for forgiveness, not permission' Pythonic rule of thumb is intended for actually exceptional conditions. The tool you probably want is the built in function enumerate([I]asequence[/I]) The other key is to use a counter to count failures. Then all lanes pass if the counter is still 0. So, here's my solution:

c='01101'

misses = 0
for index,value in enumerate(c):
    # do something useful here
if misses:
    print("There were %d lane fails"%misses)
else:
    print("All lanes PASS")

I have deliberately left you to do a bit of coding. My version tests value and if appropriate does two things.

hintMy first effort had all lanes passing because I forgot that iterating a string gives characters, not numbers.

Looks good.
the code works:

s='00101'
found = False
for i,c in enumerate(s):
    if c == '0':
        print 'Lane fail',i
        found = True
    if not found: print 'All lanes PASS

Result:
>>>
Lane fail 0
Lane fail 1
Lane fail 3
>>>

the enumerate is checking from left to right. is it possible check from right to left?
for eg:s='00101'

Will give below result:
Lane fail 1
Lane fail 3
Lane fail 4

Posting the solutions here:

s='11100101'
found = False
for i,c in enumerate(reversed(s)):
    if c == '0':
        print 'Lane fail',i
        found = True
        if not found: print 'All lanes PASS'

Try this:

s='11011'
t=s[::-1]
found = False
for i,c in enumerate(t):
    if c == '0':
        print 'Lane fail',i
        found = True
if not found: print 'All lanes PASS'

Great, your code also works! :)

This is marked solved, but here is my style of solution also:

s= '00101'
res = tuple('Lane fail {place}.'.format(place =index) for index, value in enumerate(reversed(s)) if value == '0')
print '\n'.join(res) if res else 'All lanes pass'
""" Output:
Lane fail 1.
Lane fail 3.
Lane fail 4.
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.