找到你要的答案

Q:Counting consecutive repeats in a string and returning a value in python

Q:在一个字符串在Python返回值连续重复计数

Asked my friend to give me an assignment for me to practice. It is:

If a user enters a string "AAABNNNNNNDJSSSJENDDKEW" the program will return "3AB6NDJ2SJEN2DKEW" and vice versa.

This what I tried so far:

from collections import Counter
list_user_input =[]
list_converted_output=[]
current_char = 0 #specifies the char it is reading
next_char = 1
cycle = 0 # counts number of loops
char_repeat = 1
prev_char=""
count = 1
user_input = input("Enter your string: ")
user_input_strip = user_input.strip()
user_input_striped_replace = user_input_strip.replace(" ", "").lower()
list_user_input.append(user_input_striped_replace[0:len(user_input_striped_replace)])
print(list_user_input)
print(user_input_striped_replace)

I have "cleaned" the code so it removes white spaces and keeps it in low cap

Here is where I am stuck - the logics. I was thinking to go the through the string one index at a time and compare the next on to the other. Is this the wright way to go about it? And I'm not even sure about the loop construction.

#counter = Counter(list_user_input)
#print(counter)


#while cycle <= len(user_input_striped_replace):
for letter in user_input_striped_replace:
    cycle+=1
    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1

    if letter[0:1] == letter[1:2]:
        print("match")


    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1

让我的朋友给我布置作业。它是:

If a user enters a string "AAABNNNNNNDJSSSJENDDKEW" the program will return "3AB6NDJ2SJEN2DKEW" and vice versa.

这就是我尝试过的:

from collections import Counter
list_user_input =[]
list_converted_output=[]
current_char = 0 #specifies the char it is reading
next_char = 1
cycle = 0 # counts number of loops
char_repeat = 1
prev_char=""
count = 1
user_input = input("Enter your string: ")
user_input_strip = user_input.strip()
user_input_striped_replace = user_input_strip.replace(" ", "").lower()
list_user_input.append(user_input_striped_replace[0:len(user_input_striped_replace)])
print(list_user_input)
print(user_input_striped_replace)

我已经“清理”的代码,所以它删除白色空间,并保持在低上限

这里是我坚持-逻辑。我想一次通过字符串一个索引,比较下一个到另一个。这是赖特的方法吗?我甚至不确定循环建设。

#counter = Counter(list_user_input)
#print(counter)


#while cycle <= len(user_input_striped_replace):
for letter in user_input_striped_replace:
    cycle+=1
    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1

    if letter[0:1] == letter[1:2]:
        print("match")


    print("index nr {}, letter: ".format(current_char)+letter +" and cycle : " + str(cycle))
    current_char+=1
answer1: 回答1:

Counter is a good choice for such task but about the rest you can use sorted to sort the items of Counter then use a list comprehension to create the desire list then concatenate with join :

>>> from collections import Counter
>>> c=Counter(s)
>>> sor=sorted(c.items(),key=lambda x:s.index(x[0]))
>>> ''.join([i if j==1 else '{}{}'.format(j,i) for i,j in sor])
'3AB7N3D2J3S2EKW'

计数器是一个不错的选择,但这样的任务,其余的可以使用排序的排序反然后项目使用列表理解创造的欲望清单,然后再连接的连接:

>>> from collections import Counter
>>> c=Counter(s)
>>> sor=sorted(c.items(),key=lambda x:s.index(x[0]))
>>> ''.join([i if j==1 else '{}{}'.format(j,i) for i,j in sor])
'3AB7N3D2J3S2EKW'
answer2: 回答2:

I'd do it with regular expressions. Have a look at those.

Spoiler:

import re
def encode(s):
    return re.sub(r'(.)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
def decode(e):
    return re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), e)

s = "AAABNNNNNNDJSSSJENDDKEW"
e = encode(s)
print(e, decode(e) == s)

Prints:

3AB6NDJ3SJEN2DKEW True

Your "and vice versa" sentence sounds like the program needs to detect itself whether to encode or to decode, so here's that (proof of correctness left as an exercise :-)

def switch(s):
    e = re.sub(r'(\D)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
    d = re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), s)
    return e if e != s else d

我会用正则表达式。看看那些。

Spoiler:

import re
def encode(s):
    return re.sub(r'(.)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
def decode(e):
    return re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), e)

s = "AAABNNNNNNDJSSSJENDDKEW"
e = encode(s)
print(e, decode(e) == s)

版画:

3AB6NDJ3SJEN2DKEW True

你的“反之亦然”的句子听起来像程序需要检测自己是否编码或解码,所以在这里(证明的正确性离开作为一个练习::)

def switch(s):
    e = re.sub(r'(\D)\1+', lambda m: str(len(m.group(0)))+m.group(1), s)
    d = re.sub('(\d+)(.)', lambda m: int(m.group(1))*m.group(2), s)
    return e if e != s else d
python  python-3.x