Problem: Tom and String

*Difficulty: Very Easy

Tom is a Geek, he has a following string Initial which consists of the following letters in the mentioned order:“abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ”.

He also has various lists of strings, and now he wants to compute the Hash value of each list of strings.
So, the Hash is the summation of all the character values in the input:(currentIndex + (position of the character In the string initial) ). And then this hash is multiplied by the Number of strings in the list.

Let’s assume that the list of strings is: [“aA1”, “b”]. So, his answer would be:
a: 0 + 0 = 0.
A: 1 + 36 = 37.
1: 2 + 26 = 28.
b: 0 + 1 = 1

.So, 2 * (0 + 1 + 37 + 28) = 2 * (66) = 132.

 

Input:

The first line will contain number of test cases T. Then T Test cases follow. For every test case, on a single line, there will be N number of string s all of them separated by a space, denoting all the strings of that particular list of strings.

 

Output:

Print the required hash for each of the mentioned list of strings.

 

Constraints:

1 ≤ Test Cases ≤ 50
1 ≤ Length of a string ≤ 30
1 ≤ Number of strings in a list ≤ 20

 

Example:

Input           
3
aA1 b
a b c d
aa BB cc DD
Output
132
24
640

 

Explanation:

For the First Test Case
(0 + 1 + 37 + 28) = 2 * (66) = 132

For the Second Test Case

a: 0 + 0 = 0
b: 0 + 1 = 1
c: 0 + 2 = 2
d: 0 + 3 = 3

.So, 4* (0 + 1 + 3 + 4) = 4 * (6) = 24

For the Third Test Case

a: 0 + 0 = 0
a: 1 + 0 = 1

B: 0 + 37 = 37
B: 1 + 37 = 38

c: 0 + 2 = 2
c: 1 + 2 = 3

D: 0 + 39 = 39
D: 1 + 39 = 40

So, 4* (0 + 1 + 37+ 38 + 2 + 3 + 39 + 40) = 4 * (160) = 640

Implementation: Python 2.7

#code
def hashValOf(listStrings, initString="abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    hashVal = 0
    for string in listStrings:
        for index, c in enumerate(string):
            hashVal += index + initString.find(string[index]) 
    return hashVal*len(listStrings)

def main():
    t = input()
    for _ in range(t):
        listStrings = raw_input().strip().split()
        print hashValOf(listStrings)

if __name__ == '__main__':
    main()

Advertisements