简体   繁体   中英

how to print a string showing the number of times each character is repeated in a string?

Given a string S, how to print a string containing number of times the character is repeated?

for example: input: aaabbbbccaa
output: a3b4c2a2

my approach:

s = input()

len_string = ''
cur_char = s[0]
cur_counter = 0
for i in range(len(s)):
    if s[i] == cur_char:
        cur_counter += 1
    if s[i] != cur_char or i == len(s) - 1:
        len_string += cur_char + str(cur_counter)
        cur_char = s[i]
        cur_counter = 1

print(len_string)

Because you have shared your code, here is one concise way using groupby :

from itertools import groupby

s = 'aaabbbbccaa'

print(''.join([k + str(len(list(g))) for k, g in groupby(s)]))
# a3b4c2a2

I would use collections.Counter https://docs.python.org/2/library/collections.html#counter-objects

Init signature: collections.Counter(*args, **kwds)
Docstring:
Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string

>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15

>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0

>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9

>>> c.clear()                       # empty the counter
>>> c
Counter()

Note:  If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]

I think there is a way to do this much more easy:

x='aaabbbbccaa'
noreplist = list(dict.fromkeys(x))
countstring=''
for i in noreplist:
   z=z+i+str(x.count(i))
print(countstring)

First, you have x that is your string. Then you make a list with every char from that string, but without repeating any char. And last, just counts how many times is that char repeated on the original string, and concatenate in a 'count string'.

#y is a list that contains every character in the string
#z is a list parallel to y but it contains the number of times each element in list y #has 
x=input("Input string: ")
y=[]
z=[]
acc=0
for i in range(len(x)):
    if(x[i] not in y):
        y.append(x[i])
for i in range(len(y)):
    for j in range(len(x)):
        if(y[i]==x[j]):
            acc=acc+1
    z.append(acc)
    acc=0

for k in range(len(y)):
    print(str(y[k])+str(z[k]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM