-2

For example my list is l=[1113213211] and I want the program to print how many "characters" are in first consecutive repetition of ones, I say ones because they are the the first but it can be any number. For example if list is l=[1113213211] I want my program to print: there are 3 ones then 1 three then 1 two then 1 one then 1 three then 1 two then 2 ones. How can I do that in Python3?

P.S. That list I mentioned before can be different. It can be l=[12325228961112333] or something else.

4 Answers4

2

You could use itertools.groupby like,

>>> x = [1113213211]
>>> import itertools
>>> g = itertools.groupby(''.join(str(v) for v in x))
>>> for k,grp in g:
...   print(f'{k} is present {len(list(grp))} times consequitively')
... 
1 is present 3 times consequitively
3 is present 1 times consequitively
2 is present 1 times consequitively
1 is present 1 times consequitively
3 is present 1 times consequitively
2 is present 1 times consequitively
1 is present 2 times consequitively
han solo
  • 6,390
  • 1
  • 15
  • 19
0

What you want is to iterate over the number and check if it is the same as the last one and do something accordingly. The following code should do it:

number = 1113213211 
number = [int(d) for d in str(number)] # split number into digits

list = [] # to store lists that represent (number, times seen)
lastSeen = None
for i in number: # iterate over all digits
    if lastSeen == None: # initial case
        lastSeen = [i,1]
    else:
        if i == lastSeen[0]: # if the same: add 1
            lastSeen[1] +=1
        else: # if not the same, add it to the list 
            list.append(lastSeen)
            lastSeen = [i,1]
print (list)
# [[1, 3], [3, 1], [2, 1], [1, 1], [3, 1], [2, 1]]
Vasco Lopes
  • 141
  • 9
0

itertools groupby was made for this job:

from itertools import groupby

x = [1,1,1,1,2,2,2,3,3,2,2,1,1]
[(k,len(list(g))) for k,g in groupby(x)]

[(1, 4), (2, 3), (3, 2), (2, 2), (1, 2)]
0

Was this the sort of thing you were looking for?

l = '12325228961112333'


def count_characters(s):
    answer = "There are "
    count = 0
    character = s[0]
    for ch in s:
        if(ch == character):
            count += 1
        else:
            answer += ("{} {}s ").format(count, character)
            character = ch
            count = 1
    answer += ("{} {}s ").format(count, character)
    return answer


print(count_characters(l))

Richard Price
  • 482
  • 4
  • 13