Skip to main content
 首页 » 编程设计

python之漂亮的字符串算法不能正确相乘

2024年10月17日30zlslch

我正在做 Beautiful Strings challenge .我已经知道该怎么做,并且已经在脑海中制定了解决方案。一切都是正确的,如果我能得到正确加法和乘法的方法,这应该会按预期工作,但是,我很难让它正确加法和乘法。我需要的是:

  • 统计字符串中有多少个相同的字母
  • 保存那个号码
  • 将字符串中数字的数量乘以字母的值
  • 返回总数

到目前为止我做了什么:

import string 
 
BEAUTIFICATION = { 
    "a": 24, "b": 25, "c": 26, 
    "d": 1, "e": 2, "f": 3, 
    "g": 4, "h": 5, "i": 6, 
    "j": 7, "k": 8, "l": 9, 
    "m": 10, "n": 11, "o": 12, 
    "p": 13, "q": 14, "r": 15, 
    "s": 16, "t": 17, "u": 18, 
    "v": 19, "w": 20, "x": 21, 
    "y": 22, "z": 23, 
} 
 
def strip_string(start_string): 
    exclude = set(string.punctuation) 
    new_string = ''.join(ch for ch in start_string if ch not in exclude) 
    return new_string.replace(" ", "") 
 
def calculate_sum(beautiful_string): 
    total = [] 
    for c in beautiful_string.lower(): 
        total.append(BEAUTIFICATION[c]) 
    return reduce(lambda x, y: x*y, total) 
 
if __name__ == '__main__': 
    use_string = strip_string("Good luck in the Facebook Hacker Cup this year!") 
    print(calculate_sum(use_string)) # Output: 13826822726371628751954609438720000000 
                                     # Expected output: 754 

如何以高效的 p​​ythonic 方式完成上述任务?到目前为止,我只会将总数相乘,不会计算字符串中的字符数。例如:

Actualy algorithm: ABbCcc == 1*24 + 2*25 + 3*36 = 152 
My algorithm: ABbCcc == 24 * 25 * 25 * 26 * 26 * 26 = 263640000 

请您参考如下方法:

如果只计算 BEAUTIFICATION 中的字母,为什么需要所有这些字符串剥离等?

我建议如下:

BEAUTIFICATION = { ... 
} 
 
 
def calculate_sum(beautiful_string): 
    # letter value * count of this letters in string for each letter you count 
    return sum(BEAUTIFICATION[c] * beautiful_string.lower().count(c) for c in BEAUTIFICATION) 
 
 
if __name__ == '__main__': 
    use_string = 'ABbCcc' 
    print(calculate_sum(use_string)) # Output: 152 
 
    use_string = 'Good luck in the Facebook Hacker Cup this year!' 
    print(calculate_sum(use_string)) # Output: 487 (Are you sure the 754 is correct or you BEAUTIFICATION is absolutely correct?)