papasmurf - 2 months ago 13

Python Question

I'm doing the beautiful strings challenge. I already know how to do it, and have worked out the solution in my head. Everything is correct and if I can get the method to add and multiply correctly this should work as expected, however, I'm having a tough time getting it to add, and multiply correctly. What I need is this:

- Count how many of the same letters are in the string
- Save that number
- Multiply the amount of numbers that are in the string by the value of the letter
- Return the total

What I've done so far:

`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

How can I accomplish the above in an efficient pythonic manner? What I have so far will only multiply the total together, it will not count the amount of characters in the string. For example:

`Actualy algorithm: ABbCcc == 1*24 + 2*25 + 3*36 = 152`

My algorithm: ABbCcc == 24 * 25 * 25 * 26 * 26 * 26 = 263640000

Answer

You are calculating the product of the elements in `total`

in your reduction. `reduce(lambda x, y: x*y, total)`

is equivalent to `((total[0] * total[1]) * total[2])...`

. If you want the sum, you can replace the reduction with `lambda x, y: x + y`

or use the `sum`

built-in function.