3 consecutive letters: DRY and better algo

This is the place for queries that don't fit in any of the other categories.

3 consecutive letters: DRY and better algo

Postby lovecodecakes » Tue Apr 09, 2013 2:17 pm

The code is here and it returns 3 straight consecutive non repetitive combinations of a letter if found in a string. However, today I could come up with the turd-iest code. I need expertise help on solution with a smarter python code.
Code: Select all
def three_cons(thelist):
   major=0
   for word in thelist:
      #print word
      store=[]
      count=0
      i=0
      j=0
      while i < (len(word.strip())-1):
         if word[i] == word[i+1]:
            #print word[i],word[i+1]
            count+=1
            if count==2:
               count=0
               store.extend([word[i-1],word[i],word[i+1]])
               major+=1
               i+=2
               print word,store,major
               del store
               store=[]
            else:
               i+=1
         else:
            i+=1


Code: Select all
>>> three_cons(['aaaa','aaaaaa','bb','califooornia','california'])
aaaa ['a', 'a', 'a'] 1
aaaaaa ['a', 'a', 'a'] 2
aaaaaa ['a', 'a', 'a'] 3
califooornia ['o', 'o', 'o'] 4
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: 3 consecutive letters: DRY and better algo

Postby setrofim » Tue Apr 09, 2013 2:34 pm

You could use a regular expression:
Code: Select all
In [1]: import re

In [2]: [a.group(0) for a in re.finditer(r'([a-z])\1\1', 'aaaaaa')]
Out[2]: ['aaa', 'aaa']

In [3]: [a.group(0) for a in re.finditer(r'([a-z])\1\1', 'califooornia')]
Out[3]: ['ooo']
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: snippsat and 3 guests