好的,所以我想要做的是计算给定密码的权力。每个“cddd”给出20次方,“cdd”10和“cd”5.事情是他们不能重叠。所以如果我们把字符串“ cdddd“,它将有20个电源而不是35个电源。
我的解决方案有效,但它太丑了,我不喜欢它。它应该是更一般的,而不是只匹配一个特定的字典:/
我只是对字典进行排序,所以它从最长的子字符串开始,遍历字典,然后从原始密码中删除子字符串。我想知道如何解决这个问题。
感谢您的任何建议:)
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 passwordPowerOk, so what I want to do is to calculate the power of given password.Each "cddd" gives 20 power, "cdd" 10 and "cd" 5. The thing is they can't overlap.So if we take string "cdddd", it will have 20 power instead of 35.
My solution works but it's soooo ugly, I don't like it at all.It should be more general instead of matching only one specific dict:/
I just sort the dict so It starts with the longest substring, iterate over dict and then cut the substring out from the original password.I was wondering how else could I approach this.
Thanks for any advice :)
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}One possibility is to use recursion:
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}Output:
{'cdd': 10, 'cddd': 20, 'cdddd': 20, 'cd': 5}更多推荐
发布评论