Prime numbers in letters a-z A-Z in python

1

In this problem you should read a set of words, where each word is composed only of letters in the range a-z and A-Z. Each letter has a specific value, the letter a is worth 1, the letter b is worth 2, and so on up to the letter z, which is 26. Likewise, the letter A is 27, the letter B is 28, and the letter Z is 52.

You should write a program to determine whether a word is a word or not. A word is a word if the sum of its letters is a prime number.

I'm in doubt how to do it, I've already created the variables, a = []

for i in range(ord('a'), ord('z')+1):
    a.append(chr(i))
    
asked by anonymous 28.03.2018 / 03:22

1 answer

1

Simply define a function that returns the number that represents each letter:

def get_ord_of_char(char):
  if 'a' <= char <= 'z':
    return ord(char) - ord('a') + 1
  else:
    return ord(char) - ord('A') + 27

Then, calculate the sum of the numbers that represent the word:

soma = sum(get_ord_of_char(char) for char in palavra)

And, finally, check that soma is a prime number. It would look like this:

palavra = 'teste'
soma = sum(get_ord_of_char(char) for char in palavra)
print('A palavra é prima' if is_prime(soma) else 'A palavra não é prima')

You only need to implement the is_prime function that receives an integer as a parameter.

    
28.03.2018 / 03:35