【问题标题】:“Is there a way to get sequence of most consecutive alphabet?”“有没有办法获得最连续字母的序列?”
【发布时间】:2019-05-08 14:17:17
【问题描述】:

我正在处理一个 python 问题,它有一个字符串,如“aaabbcc”和一个数字 n(整数)。 我必须显示恰好出现 n 次的任意字母字符序列。

我已经尝试过代码

import collections
str1 = 'aaabbcc'
d = collections.defaultdict(int)
for c in str1:
    d[c] += 1

for c in sorted(d, key=d.get, reverse=True):
  if d[c] > 1:
      print(c, d[c])

但我得到的输出是

a 3
b 2
c 2

我期待输出作为整数输入3 是从用户那里获取的输入。

integer= 3 
sequence= aaa

有没有其他解决方案?

【问题讨论】:

  • 这是作业吗?

标签: string python-3.6 sequence


【解决方案1】:

基于itertools.groupby 的方法:

from itertools import groupby

str1 = 'aaabbcc'
n = 3

for key, group in groupby(str1):
    if len(tuple(group)) == n:
        print(f'integer: {n} sequence: {n*key}')

没有key groupby 将按身份对序列进行分组 - 即,每次str1 中的字母发生变化时,都会产生该字母及其出现次数。

【讨论】:

  • 我明白了!考虑到了基于集合的方法,但不是迭代的。我也可以从用户那里获取字符串和整数输入吗?
  • 是的,但没有运气,控制台正在接受输入但没有返回输出
  • str1 = input('str1? '); n = int(input('n? '))(或类似的东西)不起作用?那么您可能必须将其作为新问题发布;在 cmets 中很难处理。
  • 是的,明白了!忘了把int放在n前面
【解决方案2】:

这是一种基于正则表达式的方法,似乎可行:

input = "ddaaabbbbbbbbccceeeeeee"
n = 3
for match in re.finditer(r'(.)(?!\1)(.)\2{' + str(n-1) + r'}(?!\2)', input):
print(match.group(0)[1:])

aaa
ccc

在上面的确切示例中使用的正则表达式模式是这样的:

(.)(?!\1)(.)\2{2}(?!\2)

这说明:

(.)     match and capture any single character
(?!\1)  assert that the next character is different
(.)     then match and capture that next character
\2{2}   which is then followed by that same character exactly twice (total of 3)
(?!\2)  after three instances, the character that follows is NOT the same

【讨论】:

    【解决方案3】:

    基于循环的方法(应该非常简单):

    str1 = 'aaabbcc'
    n = 3
    
    count = 1
    last = None
    for char in str1:
        if last == char:
            count += 1
        else:
            if count == n:
                print(f'integer: {n} sequence: {n*last}')
            last = char
            count = 1
    if count == n:
        print(f'integer: {n} sequence: {n*last}')
    

    如果找到包含 str1 的最后一个字符的解决方案,则最后一个 if 语句用于打印解决方案。

    【讨论】:

    • 我得到的输出是integer= 3 sequence=bbb 而不是sequence=aaa
    • 我的输入是:“aaabbcc”
    • 哎呀!这是一个错误:我打印的是char 而不是last。修好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多