1 Replies - 330 Views - Last Post: 09 October 2012 - 12:53 AM Rate Topic: -----

#1 Catcher128  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-October 12

Trouble with "While" and "For" Loop

Posted 09 October 2012 - 12:19 AM

Dear All,
In the process of coding a problem. I had a trouble with "While" and "Loop". This is my code (written in script):
def countSubStringMatch(target,key):
    ctr = 0
    for x in key:
        n = 0
        while n <= len(target) and x==target[n]:
            ctr +=1
            n +=1
        while n<=len(target) and x != target[n]:
            n +=1
    print (ctr)


When calling the "countSubStringMatch" function in IDLE (I have called "countSubStringMatch('abcdaaa','a')" and expected the output would be 4) , the output was 1. I was really stuck at this. Could you help me explain clearly why the error occured? Thank you in advance

Best Regrads

Son Nguyen

Is This A Good Question/Topic? 0
  • +

Replies To: Trouble with "While" and "For" Loop

#2 fromTheSprawl  Icon User is offline

  • Monomania
  • member icon

Reputation: 513
  • View blog
  • Posts: 2,056
  • Joined: 28-December 10

Re: Trouble with "While" and "For" Loop

Posted 09 October 2012 - 12:53 AM

There should only be one while method and change your extra conditions to ifs. Also, just use equal on your while loop.

The error occurs since when you do your first while loop it will count the first appearance of 'a' then on the next run it is evaluated false, we move to the next loop where we check if the current character isn't equal to 'a', and we increment the counter. This evaluates true and loops until we encounter the next 'a', which then ends the while execution, ending the whole program.

x: a
First while:
target[n]:  a
n:  1
ctr:  1
Second while:
target[n]:  b
n:  2
ctr:  1
target[n]:  c
n:  3
ctr:  1
target[n]:  d
n:  4
ctr:  1
Final count: 1



Also, with your current code you will not be able to count something with multiple characters.

If you're curious here's the edited version of your program where I made the output of above:
def countSub(target,key):
    ctr,a,b = 0,0,0
    for x in key:
            n = 0
            print "x:",x
            print "First while:"
            while n <= len(target) and x == target[n]:
                    print "target[n]: ", target[n]
                    ctr += 1
                    n += 1
                    print "n: ", n
                    print "ctr: ", ctr
            print "Second while:"
            while n <= len(target) and x != target[n]:
                    print "target[n]: ", target[n]
                    n += 1
                    print "n: ", n
                    print "ctr: ", ctr
    print "Final count:",ctr


Someone please teach me how to use the Python debugger! ^^

Also, the variables a and b are strays from my first attempt to debug your code, just ignore them.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1