美丽的字符串算法不能正确倍增

时间:2016-11-17 12:22:37

标签: python python-2.7

我在做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

如何以有效的pythonic方式完成上述操作?到目前为止,我只会将总数乘以,它不会计算字符串中的字符数。例如:

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

3 个答案:

答案 0 :(得分:1)

为什么你需要所有这些字符串剥离等等,如果你只计算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?)

答案 1 :(得分:1)

sum(BEAUTIFICATION.get(c.lower(), 0) for c in "ABbCcc")

答案 2 :(得分:0)

您正在计算缩减中total中元素的乘积。 reduce(lambda x, y: x*y, total)相当于((total[0] * total[1]) * total[2])...。如果您想要总和,可以使用lambda x, y: x + y替换缩减,或使用sum内置函数。