2

I want to take a string and then do computation based on the characters in that string.

a =1
b =2
c =3

test = 'cab'
test_sum= [?]

How can I make it so that I make "test_sum" equal to 6?

ashleybee97
  • 1,205
  • 3
  • 11
  • 8
  • 1
    What are the values? Are they only defined for a-z? What if you come across a character without a value? – jsfan Feb 19 '16 at 07:12
  • What jsfan said. Do you want to assign the values 1-26 to a-z? If so, there are compact ways to do that. What do you want to do about upper-case letters, and other characters? Please add these details to your question so that people can give you more useful answers. – PM 2Ring Feb 19 '16 at 07:29

1 Answers1

2

You can hold a dictionary of character values.

values = {
    'a': 1,
    'b': 2,
    'c': 3,
}

test = 'cab'
test_sum = sum([values[c] for c in test]) # 6
Nick Frost
  • 490
  • 2
  • 12
  • FWIW, `sum` can consume a generator expression, so there's no need to build a temporary list, you can just do `sum(values[c] for c in test)`. In general, a generator expression takes a tiny bit more setup time than a list comprehension, but it consumes less RAM. Of course, in this particular case the amount of RAM used is insignificant. – PM 2Ring Feb 19 '16 at 07:26