0
votes

I need to receive a string from the user, present it in list so each organ in the list contains [the letter, the number it repeat in a row].

I thought my code is good but it doesn't work. I used http://pythontutor.com and I saw that one the problem is that my var.next and current stay with the same value all the time.

somone have an idea?

Here is my code:

    string = raw_input("Enter a string:")
    i=0
    my_list=[]
    current=string[i]
    next=string[i+1]
    counter=1
    j=0
    while i<range(len(string)) and next<=range(len(string)):

        if i==len(string)-1:
            break
        j+=1
        i+=1
        if current==next:
            counter+=1

        else:
            print my_list.append([string[i],counter])
            counter=1

output:

Enter a string: baaaaab
As list: [['b', 1], ['a', 5], ['b', 1]]
3
Note that there is a module named string. You should not use that name for variables. - moooeeeep

3 Answers

3
votes

Use itertools.groupby() here:

>>> from itertools import groupby
>>> [[k, len(list(g))] for k, g in groupby("baaaaab")]
[['b', 1], ['a', 5], ['b', 1]]

Or without using libraries:

strs = raw_input("Enter a string:")
lis = []
for x in strs:
   if len(lis) != 0:
      if lis[-1][0] == x:
         lis[-1][1] += 1
      else:
         lis.append([x, 1])
   else:
       lis.append([x, 1])         
print lis                   

output:

Enter a string:aaabbbcccdef
[['a', 3], ['b', 3], ['c', 3], ['d', 1], ['e', 1], ['f', 1]]
1
votes

Simpler variant of Aswini's code:

string = raw_input("Enter a string:")
lis = []
for c in string:
    if len(lis) != 0 and lis[-1][0] == c:
        lis[-1][1] += 1
    else:
        lis.append([c, 1]) 

print lis  
0
votes

You can do this very easily using defaultdict:

import collections

defaultdict=collections.defaultdict
count=defaultdict(int)
string="hello world"
for x in string:
    count[x]+=1

To show it in a list you can do:

count.items()

which in this case would return:

[(' ', 1), ('e', 1), ('d', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]