Python重叠子字符串

Python重叠子字符串,python,Python,好的,我想做的是计算给定密码的幂,每个cddd给20幂,CDD10和CD5。问题是它们不能重叠。所以如果我们使用字符串cdddd,它将有20次幂,而不是35次幂 我的解决方案是可行的,但太难看了,我一点也不喜欢。它应该更通用,而不是只匹配一个特定的dict:/ 我只是对dict进行排序,让它从最长的子字符串开始,在dict上迭代,然后从原始密码中删除子字符串。我想知道我还能怎么做 谢谢你的建议: import re import collections def passwordCalculato

好的,我想做的是计算给定密码的幂,每个cddd给20幂,CDD10和CD5。问题是它们不能重叠。所以如果我们使用字符串cdddd,它将有20次幂,而不是35次幂

我的解决方案是可行的,但太难看了,我一点也不喜欢。它应该更通用,而不是只匹配一个特定的dict:/

我只是对dict进行排序,让它从最长的子字符串开始,在dict上迭代,然后从原始密码中删除子字符串。我想知道我还能怎么做

谢谢你的建议:

import re
import collections
def passwordCalculator(password):

    passwordPower = 0

    initialDict = {"cddd": 20, "cdd": 10,"cd": 5}
    phrases = collections.OrderedDict(sorted(initialDict.items(), key=lambda t: len(t[0]), reverse=True))

    for phrase in phrases.keys():
        count = (len(re.findall(phrase, password)))
        passwordPower += phrases.get(phrase) * count
        password = str.replace(password, phrase, '')

    return passwordPower

一种可能性是使用递归:

initialDict = {"cddd": 20, "cdd": 10,"cd": 5}
def calc_power(password, score=0):
   if any(i in password for i in initialDict):
       options = filter(lambda x:x in password, initialDict)
       return calc_power(password[:password.index(max(options))]+password[password.index(max(options))+len(max(options)):], score + initialDict[max(options)])
   return score

passwords = ['cdddd', 'cddd', 'cd', 'cdd'] 
final_results = {i:calc_power(i) for i in passwords}
输出:

{'cdd': 10, 'cddd': 20, 'cdddd': 20, 'cd': 5}

您可以创建一个正则表达式,其中包含按长度降序排列的所有短语,以|分隔。因此,您的代码直到您拥有短语列表时都可以保持原样:

def passwordCalculator(password):
    initialDict = {"cddd": 20, "cdd": 10,"cd": 5}
    phrases = collections.OrderedDict(sorted(initialDict.items(), key=lambda t: len(t[0]), reverse=True))
    regex = '|'.join(re.escape(phrase) for phrase in phrases)
    return sum(initialDict[match] for match in re.findall(regex, password))

使用正则表达式怎么样?它解决了你的问题,还是一定要把它拴起来 初始化键

import re

password = 'ccdddddvvvvvdcd'
p = re.compile(r'cd{1,3}')
result = sum(initialDict.get(x, 0) for x in p.findall(password))

你可以找到每个c,然后数一数D,我很困惑。为什么cdddd算作重叠,而其他的都不算作重叠?这意味着分数是20,而不是20+10+5。同样的理由是cdd得分为10,而不是10+5。