I was trying to write a letter repetition counting function but it is not working

I was trying to write a letter repetition counting function but it is not working



The function is supposed to take a string like:


'kkikkd'



and return a list of the letters and their repetitive values i.e.


[[k,2],[i,1],[k,2],[d,1]]



but it isn't working. Any ideas?


def chnum(xtrr):
lis2 =
for n in xtrr:
if lis2[0][0] == n:
continue
lis1 = [n]
for m in xtrr:
if n == m:
i += 1
lis1 += [i]
lis2 += [lis1]
return lis2





Please post your code as text, not as an image. It makes it easier to debug.
– Loocid
Aug 29 at 7:48





@kgemp, welcome on stackoverflow :) In order to help you, we need to see your code and your attempts to solve your problem. If you are unsure, how to ask a good question, help is provided here.
– Jones1220
Aug 29 at 7:53





3 Answers
3



If I have got your question correctly then you are trying to keep count of each character in a string and store the result in a list. The brute force way of doing is using a dictionary to keep track of character and number of times it has appeared.
Here is the code:


st= "kkikkd"
l=
temp=1
for i in range(1,len(st)):
if st[i-1] == st[i]:
temp += 1
else:
l.append([st[i-1],temp])
temp= 1
if st[i] == st[i-1]:
temp += 1
l.append([st[i],temp])



output: [['k', 2], ['i', 1], ['k', 2], ['d', 1]]





If you set string = "kkikkd"in your answer code and run it, you will notice that it does not produce the required result.
– jpeg
Aug 29 at 8:43


string = "kkikkd"





@jpeg I think I didn't get the question correctly could you please explain the question?
– Akhilesh Pandey
Aug 29 at 9:01





I'm not sure I can explain the question better, it has actually been clearly asked: the OP seeks [[k,2],[i,1],[k,2],[d,1]] as a result for 'kkikkd', i.e. counting consecutive repetitions of a letter in the string, not the overall count of a letter in the string.
– jpeg
Aug 29 at 9:08



[[k,2],[i,1],[k,2],[d,1]]


'kkikkd'





@jpeg thanks I got it. Kindly check the new code that I have just edited and tell me if something is not correct.
– Akhilesh Pandey
Aug 29 at 9:29





You're welcome. Your code seems to produce the required answer now. Still, I would recommend to use the original example in your answer code: st= "kkikkd". That helps the OP and anyone else testing.
– jpeg
Aug 29 at 9:40


st= "kkikkd"



You can use itertools.groupby


itertools.groupby


>>> from itertools import groupby
>>> s = 'kkikkd'
>>> [[k, len(list(v))] for k,v in groupby(s)]
[['k', 2], ['i', 1], ['k', 2], ['d', 1]]



Alternatively you can also use re.findall to do this


re.findall


>>> import re
>>> [[k, len(v)] for v,k in re.findall(r'((.)2*)', s)]
[['k', 2], ['i', 1], ['k', 2], ['d', 1]]



To begin with, there are 2 problems in your code


def chnum(xtrr):
lis2 =
for n in xtrr:
if lis2[0][0] == n: # lis2 is empty. It does not have 0th element, much less another nested list.
# this will only check if n is in the first element of lis2, what about all the other elements?
continue
lis1=[n]
i = 0
for m in xtrr:
if n== m:
i+=1
lis1 += [i]
lis2 += [lis1]
return lis2
print(chnum('kkidduus'))



But instead of fixing it I would advise to use the power of python. In particular its dictionaries
like so:


def chnum(xtrr):
d = n:0 for n in xtrr # create a dict where keys are letters from input string
for n in xtrr:
d[n] += 1
# for each letter from input increment the dict's value for that letter
return d

print(chnum('kkidduus'))



You will see how much more concise and readable this code is.
if you are really adamant about getting results as nested lists then this dictionary is also a good starting point. Just dol = [list(t) for t in chnum('kkidduus').items()] afterwards


l = [list(t) for t in chnum('kkidduus').items()]



EDIT:
the OP wants to see counts at every repetition of the letter, so the code above can be modified to accomodate that


def chnum(xtrr):
d = n:0 for n in xtrr # create a dict where keys are letters from input string
for n in xtrr:
d[n] += 1
# for each letter from input increment the dict's value for that letter
l = [[n, d[n]] for n in xtrr]
return l

print(chnum('kkidduus'))



using a dictionary still has merit here as dict keys are hashed and thus will have speed advantages when counting letter occurence





If you run print(chnum('kkikkd')) with your answer code, you will notice that it does not produce the required result.
– jpeg
Aug 29 at 8:59


print(chnum('kkikkd'))





Thanks it works but here's the problem if you input the string 'kkikkd' it returns 'k':4, 'i':1, 'd':1 when it is supposed to return 'k':2, 'i':1, 'k':2, 'd':1 , and I am trying not to use libraries.
– kgemp
Aug 29 at 9:13





@kgemp no libraries are used in my answer apart from the Standard Library
– Ilia Gilmijarow
Aug 29 at 11:14






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ