Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

sorting - Count the number of max consecutive "a"'s from a string. Python 3

Say that the user inputs:

"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"

How would you go about finding the highest number of consecutive "a" and how would you remove the "a"'s and leave only 2 of them instead of the large number of them before.

I was thinking of appending each letter into a new empty list but i'm not sure if that's correct or what to do after.

I really don't know where to begin with this one but this is what i'm thinking:

  1. Ask the user for input.
  2. Create an empty list
  3. Append each letter from the input into the list

What's next I have no idea.

second edit (something along these lines):

sentence = input("Enter your text: ")
new_sentance = " ".join(sentence.split())
length = len(new_sentance)
alist = []
while (length>0):
    alist
print ()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting with the input string:

input = "daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"
  • To get the max consecutive number of occurrences, you would use:

    max(len(s) for s in re.findall(r'a+', input))
    
  • To replace only the longest unbroken sequence of "a"s with 2 "a"s, you would use:

    maxMatch = max(re.finditer(r'a+', input), key= lambda m: len(m.group()))
    output = input[:maxMatch.start()] + "aa" + input[maxMatch.end():]
    

    First, I obtain an iterable of MatchObjects by testing the input string against the regex a+, then use max to obtain the MatchObject with the greatest length. Then, I splice the portion of the original string up to the start of the match, the string "aa", and the portion of the original string after the end of the match to give you your final output.

  • To replace all occurrences of more than 2 "a"s with 2 "a"s, you would use:

    output = re.sub(r'a{3,}', "aa", input)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...