Cerinta completa

James found a love letter that his friend Harry has written to his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.

To do this, he follows two rules:

  1. He can only reduce the value of a letter by , i.e. he can change d to c, but he cannot change c to d or d to b.
  2. The letter may not be reduced any further.

Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.

Example

The following two operations are performed: cdecddcdc. Return .

Function Description

Complete the theLoveLetterMystery function in the editor below.

theLoveLetterMystery has the following parameter(s):

  • string s: the text of the letter

Returns

  • int: the minimum number of operations

Input Format

The first line contains an integer , the number of queries.
The next lines will each contain a string .

Constraints


| s |
All strings are composed of lower case English letters, ascii[a-z], with no spaces.

Sample Input

STDIN   Function
-----   --------
4       q = 4
abc     query 1 = 'abc'
abcba
abcd
cba

Sample Output

2
0
4
2

Explanation

  1. For the first query, abc → abb → aba.
  2. For the second query, abcba is already a palindromic string.
  3. For the third query, abcd → abcc → abcb → abca → abba.
  4. For the fourth query, cba → bba → aba.

Limbajul de programare folosit: python3

Cod:

#!/bin/python3

def theLoveLetterMystery(s):
    ans = 0
    i, j = 0, len(s) - 1
    while i < j:
        ans += abs(ord(s[i]) - ord(s[j]))
        i += 1
        j -= 1
    return ans

if __name__ == '__main__':
    q = int(input().strip())
    out = []
    for _ in range(q):
        out.append(str(theLoveLetterMystery(input().strip())))
    print(*out, sep='\n')

Scor obtinut: 1.0

Submission ID: 464590730

Link challenge: https://www.hackerrank.com/challenges/the-love-letter-mystery/problem

The Love-Letter Mystery