views:

57

answers:

3

Hi

Why am i getting an "invalid syntax" when i run below code. Python 2.7

from string import *

def countSubStringMatch(target,key):
    counter=0
    fsi=0 #fsi=find string index
    while fsi<len(target):
        fsi=dna.find(key,fsi)      
        if fsi!=-1:
           counter+=1
        else:
            counter=0
            fsi=fsi+1
        fsi=fsi+1
    #print '%s is %d times in the target string' %(key,counter)

def countSubStringMatch("atgacatgcacaagtatgcat","atgc")
+5  A: 

In the line:

def countSubStringMatch("atgacatgcacaagtatgcat","atgc")

You should remove the def. def is used when defining a function, not when calling it.

interjay
apologies for asking such a simple question, beginner's mistake...thanks
Baba
+3  A: 

Other things wrong with your code:

  1. You don't use and don't need anything in the string module. Don't import from it.

  2. Don't do from somemodule import * unless you have a very good reason for it.

  3. Your code rather slowly and pointlessly struggles on after the first time that find returns -1 ... your loop should include

    if fsi == -1: return counter

    so that you return immediately with the correct count.

  4. Be consistent: you use counter += 1 but fsi = fsi + 1

  5. ... which reminds me: find 'PEP 8' (style guide) at www.python.org, and read it -- your space bar must be feeling unloved ;-)

HTH
John

John Machin
Hi John, thanks for pointintg this out to me!
Baba
@Baba: (1) see my edit; in problem #3, should return `counter`, not `0` (2) problem #6: calculate `len(dna)` ONCE, before entering `while` loop
John Machin
+3  A: 

for string count you could just do:

target = "atgacatgcacaagtatgcat"
s = 'atgc'
print '%s is %d times in the target string' % (s, target.count(s))
killown