# Background

My TV remote control has arrow buttons and an `OK` button.

I can use these to move a "cursor" on a logical screen keyboard to type "words"...

The screen "keyboard" layout looks like this


  #tvkb {
    width : 300px;
    border: 5px solid gray; border-collapse: collapse;
  }
  #tvkb td {
    color : orange;
    background-color : black;
    text-align : right;
    border: 3px solid gray; border-collapse: collapse;
  }


abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/


# Kata task

How many button presses on my remote are required to type a given `word`?

## Notes

* The cursor always starts on the letter `a` (top left)
* Remember to also press `OK` to "accept" each character.
* Take a direct route from one character to the next
* The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge)
* A "word" (for the purpose of this Kata) is any sequence of characters available on my virtual "keyboard" 

# Example

word = `codewars`

* c => `a`-`b`-`c`-OK = 3
* o => `c`-`d`-`e`-`j`-`o`-OK = 5
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* w => `e`-`j`-`o`-`t`-`y`-`x`-`w`-OK = 7
* a => `w`-`r`-`m`-`h`-`c`-`b`-`a`-OK = 7
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2

Answer = 3 + 5 + 4 + 2 + 7 + 7 + 6 + 2 = 36



*Good Luck!
DM.*



Series
* TV Remote
* TV Remote (shift and space)
* TV Remote (wrap)
* TV Remote (symbols)

Difficulty: introductory

Starter code:

def tv_remote(word):
	

Solutions:
KEYBOARD = "abcde123fghij456klmno789pqrst.@0uvwxyz_/"
MAP      = {c: (i//8, i%8) for i,c in enumerate(KEYBOARD)}

def manhattan(*pts): return sum( abs(z2-z1) for z1,z2 in zip(*pts))

def tv_remote(word):
    return len(word) + sum( manhattan(MAP[was], MAP[curr]) for was,curr in zip('a'+word, word))

def getlocation(letter):
    keyboard = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    return divmod(keyboard.find(letter),8)

def tv_remote(word):
    x1, y1 = 0, 0
    moves = 0
    for letter in word:
        x2, y2 = getlocation(letter)
        moves += abs(x2-x1) + abs(y2-y1) + 1
        x1, y1 = x2, y2
    return moves


def tv_remote(word):
    # Your code here!!
    pp = 0
    res = 0
    r = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    for w in word:
        p = r.find(w)
        res += abs(p//8-pp//8) + abs(p%8-pp%8) + 1
        pp = p
    return res

def tv_remote(word):
    letters = {c: (x, y)
        for y, row in enumerate((
        "abcde123",
        "fghij456",
        "klmno789",
        "pqrst.@0",
        "uvwxyz_/"))
        for x, c in enumerate(row)}
    return sum(
        abs(letters[c1][0] - letters[c2][0]) +
        abs(letters[c1][1] - letters[c2][1]) + 1
        for c1, c2 in zip("a" + word, word))

D = {v:(r, c) for r, row in enumerate(['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/']) for c, v in enumerate(row)}

def tv_remote(word):
    return sum(abs(D[a][0] - D[b][0]) + abs(D[a][1] - D[b][1]) + 1 for a, b in zip('a' + word, word))

def tv_remote(word):
# define the remote grid in a dictionary
    grid = {
        "a":[1,1],"b":[1,2],"c":[1,3],"d":[1,4],"e":[1,5],"1":[1,6],"2":[1,7],"3":[1,8],
        "f":[2,1],"g":[2,2],"h":[2,3],"i":[2,4],"j":[2,5],"4":[2,6],"5":[2,7],"6":[2,8],
        "k":[3,1],"l":[3,2],"m":[3,3],"n":[3,4],"o":[3,5],"7":[3,6],"8":[3,7],"9":[3,8],
        "p":[4,1],"q":[4,2],"r":[4,3],"s":[4,4],"t":[4,5],".":[4,6],"@":[4,7],"0":[4,8],
        "u":[5,1],"v":[5,2],"w":[5,3],"x":[5,4],"y":[5,5],"z":[5,6],"_":[5,7],"/":[5,8]}
    
    total_moves = 0
    start_pos = [1, 1]
    
    for l in word:
        v_moves = abs(grid[l][0] - start_pos[0])
        h_moves = abs(grid[l][1] - start_pos[1])
        total_moves += (v_moves + h_moves + 1)
        start_pos = grid[l]
    return total_moves
    
    


def tv_remote(word):
    pad = ["abcde123", "fghij456", "klmno789", "pqrst.@0", "uvwxyz_/"]
    index = {c: (x, y) for x, lst in enumerate(pad) for y, c in enumerate(lst)}
    res = 0
    pos = (0, 0)
    for char in word:
        res += (abs(pos[0] - index[char][0]) + abs(pos[1] - index[char][1])) + 1
        pos = index[char]
    return res

def tv_remote(word):
    k = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    P,sum = 0,0
    for c in word:
        p = k.find(c)
        sum += abs(P//8-p//8) + abs(P%8-p%8) + 1
        P = p
    return sum

from collections import namedtuple


def tv_remote(word: str):
    remote = (
        'a', 'b', 'c', 'd', 'e', '1', '2', '3',
        'f', 'g', 'h', 'i', 'j', '4', '5', '6',
        'k', 'l', 'm', 'n', 'o', '7', '8', '9',
        'p', 'q', 'r', 's', 't', '.', '@', '0',
        'u', 'v', 'w', 'x', 'y', 'z', '_', '/'
    )
    Position = namedtuple('Position', 'y x')
    
    prev = Position(0, 0)
    button_presses = 0
    for letter in word:
        cur = Position(*divmod(remote.index(letter), 8))
        button_presses += abs(prev.y - cur.y) + abs(prev.x - cur.x) + 1
        prev = cur

    return button_presses

def tv_remote(word):
    return len(word) + sum(distance(coords[a], coords[b]) for a, b in zip(f"a{word}", word))

keyboard = ("abcde123", "fghij456", "klmno789", "pqrst.@0", "uvwxyz_/")
coords = {char: (line.index(char), y) for y, line in enumerate(keyboard) for char in line}

def distance(pos1, pos2):
    return abs(pos2[0] - pos1[0]) + abs(pos2[1] - pos1[1])


def tv_remote(word):
    keys = [ '-afkpu',  '-bglqv', '-chmrw', '-dinsx', '-ejoty', '-147.z', '-258@_', '-3690/' ]
    
    index_last = first_in(word[0] , keys )
    
    ret = sum(index_last )
    
    for i in word[1:]:
        inkey = first_in(i, keys)[0]
        ret += ( abs(index_last[0] - inkey ) + abs(index_last[1] - first_in(i, keys[inkey])[0] ) )  + 1
        index_last = [ inkey, first_in(i, keys[inkey])[0] ]
        
    return ret
    
first_in = lambda l, k : [ (k.index(e), e.index(l)) for e in k if l in e ][0]

LAYOUT = """\
a   b   c   d   e   1   2   3
f   g   h   i   j   4   5   6
k   l   m   n   o   7   8   9
p   q   r   s   t   .   @   0
u   v   w   x   y   z   _   /
""".split()

def get_pos(char):
    return divmod(LAYOUT.index(char), 8)

def distance(char1, char2):
    c1x, c1y = get_pos(char1)
    c2x, c2y = get_pos(char2)
    return abs(c1x - c2x) + abs(c1y - c2y)

def tv_remote(word):
    return sum(distance(prev, curr) for prev, curr in zip("a" + word, word)) + len(word)

def tv_remote(word):
    matrix = [
             ['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
             ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
             ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
             ['p', 'q', 'r', 's', 't', '.', '@', '0'],
             ['u', 'v', 'w', 'x', 'y', 'z', '_', '/'],
             ]

    start = [0, 0]
    _dict = dict()
    actions = []
    _lambda = lambda x, y: (abs(x[0]-y[0]) + abs(x[1]-y[1]))+1

    for char in word:
        for i in range(5):
            if char in matrix[i]:
                _dict[char] = [i, matrix[i].index(char)]
        actions.append(_lambda(start, _dict[char]))
        start = _dict[char]

    return sum(actions)

def tv_remote(word):
    word, total = 'a' + word, 0
    s = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    d = {i: (s.index(i)//8, s.index(i)%8) for i in s}
    
    for a, b in zip(word, word[1:]):
        (x1, y1), (x2, y2) = d[a], d[b]
        total += abs(x1 - x2) + abs(y1 - y2)
    return total + len(word) - 1

def tv_remote(word):
    l = ['abcde123',
         'fghij456',
         'klmno789',
         'pqrst.@0',
         'uvwxyz_/',]
    a, b, s = 0, 0, 0
    for i, m in enumerate(word):
        for j, n in enumerate(l):
            if m in n:
                a1 = j
                b1 = n.index(m)
                s += abs(a-a1) + abs(b-b1) + 1
                break
        a, b = a1, b1
    return s


REMOTE = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'

def tv_remote(word):
    x, y, total = 0, 0, 0
    for char in word:
        pos = REMOTE.index(char)
        charx, chary = pos % 8, pos // 8
        total += 1 + abs(charx - x) + abs(chary - y)
        x, y = charx, chary
    return total

import numpy as np
def tv_remote(word):
    # Your code here!!
    # 1. A stupid method is to setup an table(dictionary)
    # 2. set up a 2D array
    table=np.array([["a","b","c","d","e","1","2","3"],
    ["f","g","h","i","j","4","5","6"],
    ["k","l","m","n","o","7","8","9"],
    ["p","q","r","s","t",".","@","0"],
    ["u","v","w","x","y","z","_","/"]])
    cur=[0,0]
    result=0
    for char in word:
        new=np.argwhere(char==table)
        result+=(1+sum(abs(new-cur).flat))
        cur=new
    return result


def tv_remote(word):
    remote = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    prev_pos, pres = [0, 0], 0
    for symb in word:
        pos = [remote.find(symb)//8, remote.find(symb)%8]
        pres += abs(pos[0] - prev_pos[0]) + abs(pos[1] - prev_pos[1]) +1
        prev_pos = pos
    
    return pres

keyboard = [
    'abcde123',
    'fghij456',
    'klmno789',
    'pqrst.@0',
    'uvwxyz_/',
]
positions = {ch: (r, c) for r, row in enumerate(keyboard) for c, ch in enumerate(row)}


def tv_remote(word):
    r, c = 0, 0
    presses = 0
    for ch in word:
        r2, c2 = positions[ch]
        presses += abs(r2-r) + abs(c2-c) + 1
        r, c = r2, c2
    return presses

def tv_remote(word: str):
    remote = (
        'a', 'b', 'c', 'd', 'e', '1', '2', '3',
        'f', 'g', 'h', 'i', 'j', '4', '5', '6',
        'k', 'l', 'm', 'n', 'o', '7', '8', '9',
        'p', 'q', 'r', 's', 't', '.', '@', '0',
        'u', 'v', 'w', 'x', 'y', 'z', '_', '/'
    )

    button_presses = prev_y = prev_x = 0
    for letter in word:
        y, x = divmod(remote.index(letter), 8)
        button_presses += abs(prev_y - y) + abs(prev_x - x) + 1
        prev_y, prev_x = y, x

    return button_presses

def tv_remote(word):
    l=[['a','b','c','d','e','1','2','3'],
    ['f','g','h','i','j','4','5','6'],
    ['k','l','m','n','o','7','8','9'],
    ['p','q','r','s','t','.','@','0'],
    ['u','v','w','x','y','z','_','/']];
    a=[[l.index(x) , x.index(y)] for w in word for x in l for y in x if w in y ]
    return (sum([abs(x[0]-y[0])+abs(x[1]-y[1]) for x,y in zip(a[1:],a[:-1])]) +sum(a[0]) + len(word))

def tv_remote(word):
    keyboard = {
        "a": (0, 0), "b": (0, 1), "c": (0, 2), "d": (0, 3), "e": (0, 4), "1": (0, 5), "2": (0, 6), "3": (0, 7),
        "f": (1, 0), "g": (1, 1), "h": (1, 2), "i": (1, 3), "j": (1, 4), "4": (1, 5), "5": (1, 6), "6": (1, 7),
        "k": (2, 0), "l": (2, 1), "m": (2, 2), "n": (2, 3), "o": (2, 4), "7": (2, 5), "8": (2, 6), "9": (2, 7),
        "p": (3, 0), "q": (3, 1), "r": (3, 2), "s": (3, 3), "t": (3, 4), ".": (3, 5), "@": (3, 6), "0": (3, 7),
        "u": (4, 0), "v": (4, 1), "w": (4, 2), "x": (4, 3), "y": (4, 4), "z": (4, 5), "_": (4, 6), "/": (4, 7)
    }
    total = 0
    first_point_holder = 0
    second_point_holder = 0
    for a in word:
        if a in keyboard:
            first_point, second_point = keyboard[a]
            total += abs(first_point - first_point_holder) + abs(second_point - second_point_holder) + 1
            first_point_holder, second_point_holder = first_point, second_point
    return total

def tv_remote(word):
    
    a = ['abcde123','fghij456','klmno789','pqrst.@0','uvwxyz_/']
    
    start, start_line, count = 0,0,0
    
    for i in word:
        for line in a:
            if i in line:
                count += abs(line.index(i)-start) + abs(a.index(line)-start_line)
                start, start_line = line.index(i), a.index(line)
                
    return count+len(word)

keyboard = [
    "abcde123",
    "fghij456",
    "klmno789",
    "pqrst.@0",
    "uvwxyz_/",
]


def tv_remote(word):
    current_row, current_column = 0, 0
    total_moves = 0
    
    for letter in word:
        for row, line in enumerate(keyboard):
            column = line.find(letter)
            if column != -1:
                moves = abs(current_row - row) + abs(current_column - column) + 1 # +1 for OK button
                total_moves += moves
                current_row = row
                current_column = column
    return total_moves

def tv_remote(word):
    # Your code here!!
    keyboard = [
        "abcde123",
        "fghij456",
        "klmno789",
        "pqrst.@0",
        "uvwxyz_/",
    ]
    
    cursor_position = [0, 0]
    total_moves = 0
    
    for char in word:
        for i, row in enumerate(keyboard):
            if char in row:
                new_position = [row.index(char), i]
                move = sum(abs(cursor_position[i] - new_position[i]) for i, _ in enumerate(cursor_position)) + 1
                total_moves += move
                cursor_position = new_position
    return total_moves

import numpy as np
def tv_remote(word):
    keyboard = np.array([["a","b","c","d","e","1","2","3"], ["f","g","h","i","j","4","5","6"], ["k","l","m","n","o","7","8","9"], ["p","q","r","s","t",".","@","0"],["u","v","w","x","y","z","_","/"]])
    x, y = 0, 0
    moves = 0
    for i in word:
        moves += abs(np.argwhere(keyboard == i)[0][0]-y) + abs(np.argwhere(keyboard == i)[0][1]-x) + 1
        x, y = np.argwhere(keyboard == i)[0][1], np.argwhere(keyboard == i)[0][0]
    return moves

def tv_remote(word):
    letloc = {"a":[0,0], "b":[0,1], "c":[0,2], "d":[0,3], "e":[0,4], "1":[0,5] , "2":[0,6], "3":[0,7], 
              "f":[1,0], "g":[1,1], "h":[1,2], "i":[1,3], "j":[1,4], "4":[1,5] , "5":[1,6], "6":[1,7],
              "k":[2,0], "l":[2,1], "m":[2,2], "n":[2,3], "o":[2,4], "7":[2,5] , "8":[2,6], "9":[2,7],
              "p":[3,0], "q":[3,1], "r":[3,2], "s":[3,3], "t":[3,4], ".":[3,5] , "@":[3,6], "0":[3,7],
              "u":[4,0], "v":[4,1], "w":[4,2], "x":[4,3], "y":[4,4], "z":[4,5] , "_":[4,6], "/":[4,7],
             }
    
    now = [0,0]
    path = 0
    
    for letter in word:
        path += abs(now[0] - letloc[letter][0]) + abs(now[1] - letloc[letter][1]) + 1
        now = letloc[letter]
    
    return path

def tv_remote(word):
    letloc = {"a":[0,0], "b":[0,1], "c":[0,2], "d":[0,3], "e":[0,4], "1":[0,5] , "2":[0,6], "3":[0,7], 
              "f":[1,0], "g":[1,1], "h":[1,2], "i":[1,3], "j":[1,4], "4":[1,5] , "5":[1,6], "6":[1,7],
              "k":[2,0], "l":[2,1], "m":[2,2], "n":[2,3], "o":[2,4], "7":[2,5] , "8":[2,6], "9":[2,7],
              "p":[3,0], "q":[3,1], "r":[3,2], "s":[3,3], "t":[3,4], ".":[3,5] , "@":[3,6], "0":[3,7],
              "u":[4,0], "v":[4,1], "w":[4,2], "x":[4,3], "y":[4,4], "z":[4,5] , "_":[4,6], "/":[4,7],
             }
    
    now = [0,0]
    path = 0
    
    for letter in word:
        if letloc[letter][0] > now[0]:
            path += letloc[letter][0] - now[0]
        else:
            path += now[0] - letloc[letter][0]
        if letloc[letter][1] > now[1]:
            path += letloc[letter][1] - now[1]
        else:
            path += now[1] - letloc[letter][1]
        now = letloc[letter]
        path+= 1
        print (path)
    
    return path

def tv_remote(word):
    screen_keyboard_layout = [
        ["a", "b", "c", "d", "e", "1", "2", "3"],
        ["f", "g", "h", "i", "j", "4", "5", "6"],
        ["k", "l", "m", "n", "o", "7", "8", "9"],
        ["p", "q", "r", "s", "t", ".", "@", "0"],
        ["u", "v", "w", "x", "y", "z", "_", "/"]]
    screen_keyboard_symbols = "abcde123fghij456klmno789pqrst.@0uvwxyz_/"
    if not all([ch in screen_keyboard_symbols for ch in word]):
        return -1

    button_presses = 0
    cur_position, next_position = (0, 0), (0, 0)
    for ch in word:
        for i, row in enumerate(screen_keyboard_layout):
            if ch in row:
                next_position = (i, row.index(ch))
        button_presses += abs(next_position[0] - cur_position[0]) + abs(next_position[1] - cur_position[1]) + 1     # +1 for OK
        cur_position = next_position
    return button_presses

keyboard = {
    'a' : (0,0),
    'b' : (0,1),
    'c' : (0,2),
    'd' : (0,3),
    'e' : (0,4),
    '1' : (0,5),
    '2' : (0,6),
    '3' : (0,7),
    'f' : (1,0),
    'g' : (1,1),
    'h' : (1,2),
    'i' : (1,3),
    'j' : (1,4),
    '4' : (1,5),
    '5' : (1,6),
    '6' : (1,7),
    'k' : (2,0),
    'l' : (2,1),
    'm' : (2,2),
    'n' : (2,3),
    'o' : (2,4),
    '7' : (2,5),
    '8' : (2,6),
    '9' : (2,7),
    'p' : (3,0),
    'q' : (3,1),
    'r' : (3,2),
    's' : (3,3),
    't' : (3,4),
    '.' : (3,5),
    '@' : (3,6),
    '0' : (3,7),
    'u' : (4,0),
    'v' : (4,1),
    'w' : (4,2),
    'x' : (4,3),
    'y' : (4,4),
    'z' : (4,5),
    '_' : (4,6),
    '/' : (4,7)
}


def tv_remote(word):
    current, total = (0,0), 0
    for x in word :
        next = keyboard.get(x)
        total += abs(next[0]-current[0])+abs(next[1]-current[1])+1
        current = next
    return total


from string import ascii_lowercase as buttons, digits as buttons2

remote = {}
#assign cordinates, assuming cords of a, (x,y) = (0,0)
for temp_x, button in enumerate(buttons):
    remote[button] = (temp_x % 5, temp_x // 5)
for temp_x, button in enumerate(buttons2[1::]):
    remote[button] = (temp_x % 3 + 5, temp_x // 3)
remote["."], remote["@"], remote["0"] = (5, 3), (6, 3), (7, 3)
remote["z"], remote["_"], remote["/"] = (5, 4), (6, 4), (7, 4)


def tv_remote(word):
    presses = ix = iy = 0
    for letter in word:
        x, y = remote[letter]
        presses += abs(x-ix) + abs(y-iy) +1
        ix, iy = x, y
    return presses

s = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
dx = lambda c1, c2 : abs(s.index(c1)%8  - s.index(c2)%8)
dy = lambda c1, c2 : abs(s.index(c1)//8 - s.index(c2)//8)
d  = lambda c1, c2 : 1 + dx(c1, c2) + dy(c1, c2)

def tv_remote(word, r=0):
    if r==0         : return tv_remote(word, d('a', word[0]))
    if len(word)==1 : return r
    else            : return tv_remote(word[1:], r+d(word[1], word[0]))

def tv_remote(word):
    letters = "abcde123fghij456klmno789pqrst.@0uvwxyz_/"
    steps = 0
    x, y = 0, 0
    for i in word:
        x1, y1 = (letters.find(i)%8, letters.find(i)//8)
        steps += abs(x - x1) + abs(y - y1) + 1 
        x, y = x1, y1
    return steps

def tv_remote(word):
    arrayz = [
        'abcde123',
        'fghij456',
        'klmno789',
        'pqrst.@0',
        'uvwxyz_/'
    ]
    steps = 0
    x = 0
    y = 0
    for letter in word:
        for row in arrayz:
            if letter in row:
                y1 = arrayz.index(row)
                x1 = row.find(letter)
                continue
        steps += abs(x - x1) + abs(y - y1) + 1
        x, y = x1, y1
    return steps

def tv_remote(word):
    keys = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    res, last = len(word), 0

    for c in word:
        i = keys.index(c)
        res += abs(i%8-last%8) + abs(i//8-last//8)
        last = i

    return res

def tv_remote(word):
  characters = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'

  width = 8             # keypad width
  c_x = 0               # index of cursor starting location
  c_y = 0
  total_steps = 0       # running sum of steps
  for w in word:
    # find co-ords of w
    w_index = characters.find(w)
    w_x = (w_index % width)       # column number
    w_y = (w_index // width)      # row number
    
    # compare to cursor co-ordinates
    w_x_steps = abs(w_x - c_x)
    w_y_steps = abs(w_y - c_y)
    w_steps = w_x_steps + w_y_steps + 1     # extra for 'OK' button

    # update cursor
    c_x = w_x
    c_y = w_y

    # running total
    total_steps += w_steps
    
  return total_steps

def tv_remote(word):
    c_pos = [0, 0]
    remote = ["abcde123", "fghij456", "klmno789", "pqrst.@0", "uvwxyz_/"]
    move = len(word)

    for let in word:
        y = 0
        for key in remote:
            if let in key:
                x = key.find(let)
                move += abs(y-c_pos[0]) + abs(x-c_pos[1])
                c_pos = [y, x]
            y += 1
    return move


def tv_remote(word):
    keyboard = [
        ["a", "b", "c", "d", "e", "1", "2", "3"],
        ["f", "g", "h", "i", "j", "4", "5", "6"],
        ["k", "l", "m", "n", "o", "7", "8", "9"],
        ["p", "q", "r", "s", "t", ".", "@", "0"],
        ["u", "v", "w", "x", "y", "z", "_", "/"]
    ]
    result = 0
    coordinates1 = [0, 0]
    
    for letter in word:
        coordinates2 = find_symbol_coordinates(letter, keyboard)
        result += abs(coordinates2[1] - coordinates1[1]) + abs(coordinates2[0] - coordinates1[0]) + 1
        coordinates1 = find_symbol_coordinates(letter, keyboard)        
    return result

def find_symbol_coordinates(symbol, array):
    x = 0
    y = 0
    for row in array:
        for colomn in row:
            if colomn == symbol:
                return [x, y]
            x += 1
        y += 1
        x = 0

def tv_remote(word):
    keyboard = ['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/']
    
    pos = (0, 0)
    count = 0
    for i in word:
        nextrow = None
        for row in keyboard:
            if i in row:
                nextrow = row
    
        newpos = (keyboard.index(nextrow), nextrow.index(i))
        count += abs(pos[0]-newpos[0]) + abs(pos[1]-newpos[1]) + 1
        pos = newpos
        
    return count


def tv_remote(word): #there are more efficient ways to do it, but I want to try it manually
    keyboard = ["abcde123","fghij456","klmno789","pqrst.@0","uvwxyz_/"]
    x = 0
    y = 0
    steps = 0
    for c in word:
        while keyboard[y][x] != c:
            steps += 1
            print(keyboard[y][x])
            if c in keyboard[y]: #if you're at the right row
                if keyboard[y].find(c) < x: #if c is to the left of the current position
                    x -= 1 #press left
                else:
                    x += 1 #press right
            else:
                if "".join(keyboard).find(c) < y*8+x: #this was the shortest way I could think of if you include numbers and chars
                    y -= 1 #press up
                else:
                    y += 1 #press down
        steps += 1 #press ok
    return steps

import numpy

def tv_remote(word):
    initial = (0,0)
    current = ()
    final = ()
    total = 0
    count = 0
    screen = numpy.array([['a','b','c','d','e','1','2','3'],
                          ['f','g','h','i','j','4','5','6'],
                          ['k','l','m','n','o','7','8','9'],
                          ['p','q','r','s','t','.','@','0'],
                          ['u','v','w','x','y','z','_','/']])

    for i in word:
      current = numpy.argwhere(screen == word[count])
      final = abs(current - initial)
      total += final[0][0]+final[0][1]
      count += 1
      initial = current
      
    return total+len(word)

def tv_remote(word):
    # Your code here!!
    kBoard = {'a': (0,0), 'b':(0,1), 'c':(0,2), 'd':(0,3), 'e':(0,4), '1':(0,5), '2':(0,6), '3':(0,7), 'f':(1,0), 'g':(1,1), 'h':(1,2), 'i':(1,3), 'j':(1,4), '4':(1,5), '5':(1,6), '6':(1,7),'k':(2,0), 'l':(2,1), 'm':(2,2), 'n':(2,3), 'o':(2,4), '7':(2,5), '8':(2,6), '9':(2,7),'p':(3,0), 'q':(3,1), 'r':(3,2), 's':(3,3), 't':(3,4), '.':(3,5), '@':(3,6), '0':(3,7),'u':(4,0), 'v':(4,1), 'w':(4,2), 'x':(4,3), 'y':(4,4), 'z':(4,5), '_':(4,6), '/':(4,7)}
    pos = [0,0]
    ans = 0
    
    for char in word:
        y = abs(kBoard[char][0] - pos[0])
        x = abs(kBoard[char][1] - pos[1])
        pos = [kBoard[char][0],kBoard[char][1]]
        ans += (x + y + 1)
    return ans


remote_grid = [
['a','b','c','d','e','1','2','3'],
['f','g','h','i','j','4','5','6'],
['k','l','m','n','o','7','8','9'],
['p','q','r','s','t','.','@','0'],
['u','v','w','x','y','z','_','/'],
]
rem_x = 8
rem_y = 5
remote_map = {}
for y in range(rem_y):
    for x in range(rem_x):
        remote_map[ remote_grid[y][x] ] = (x,y)
def tv_remote(word):    
    currpos = (0,0)
    clicks = 0
    for c in word:
        nextpos = remote_map[c]
        clicks += abs(nextpos[0]-currpos[0]) + abs(nextpos[1]-currpos[1])
        currpos = nextpos
    return clicks+len(word)


def tv_remote(word):
    keys = ['abcde123','fghij456','klmno789','pqrst.@0','uvwxyz_/']
    p,c = (0,0),0
    for s in word:
        for i,row in enumerate(keys):
            for j,v in enumerate(row):
                if v==s:
                    c += abs(p[0]-i) + abs(p[1]-j) + 1
                    p = (i,j)
    return c

def tv_remote(word):
    display = [['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
               ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
               ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
               ['p', 'q', 'r', 's', 't', '.', '@', '0'],
               ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']]
    rows = [0]
    columns = [0]
    for letter in word:
        for row in display:
            if letter in row:
                rows.append(display.index(row))
                for cell in row:
                    if letter == cell:
                        columns.append(row.index(letter))
    moves = 0
    for n in range(1, len(rows)):
        moves += abs(rows[n] - rows[n - 1])
    for n in range(1, len(columns)):
        moves += abs(columns[n] - columns[n - 1])
    return moves + len(word)

def tv_remote(word):
    result = 0
    alpha = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    nxt = [0, 0]
    for c in word:
        i = alpha.index(c)
        where  = [i // 8, i % 8]
        result += abs(where[0] - nxt[0]) + abs(where[1] - nxt[1]) + 1
        nxt = where
    return result

from itertools import chain
def tv_remote(word):
    locs=list(chain.from_iterable([(j,i) for j in range(0,8)] for i in range(0,5)))
    lookup=dict(zip("abcde123fghij456klmno789pqrst.@0uvwxyz_/",locs))
    prev_loc=lookup[word[0]]
    dist=sum(prev_loc)
    for l in word[1:]:
        loc=lookup[l]
        dist+=abs(loc[0]-prev_loc[0])+abs(loc[1]-prev_loc[1])
        prev_loc=loc
    
    return dist+len(word)

KEYBOARD_STRING = "a    b   c   d   e   1   2   3 \
                    f   g   h   i   j   4   5   6 \
                    k   l   m   n   o   7   8   9 \
                    p   q   r   s   t   .   @   0 \
                    u   v   w   x   y   z   _   /"

keyboard_list = list(KEYBOARD_STRING.split())

keyboard_dictionary = {}

n = 0
for i in keyboard_list:
    row = n // 8
    col = (n + 8) % 8
    keyboard_dictionary[i] = [row, col]
    n += 1

def tv_remote(word):
    word_list = list(word)
    count = 0
    row = 0
    col = 0
    for i in word_list:
        col_dist = abs(col - keyboard_dictionary[i][1])
        row_dist = abs(row - keyboard_dictionary[i][0])
        col = keyboard_dictionary[i][1]
        row = keyboard_dictionary[i][0]
        count += col_dist + row_dist + 1
    return count

def tv_remote(word):
    arr = ['abcde123', 'fghij456', 'klmno789', 'pqrst.@0', 'uvwxyz_/']
    res = 0
    start_i = 0
    start_j = 0
    for x in word:
        fin_i = 0
        for y in arr: 
            if x in y:
                fin_i = arr.index(y)
                break
        
        res += abs(fin_i - start_i) + abs(arr[fin_i].index(x) - start_j) + 1
        start_i = fin_i
        start_j = arr[fin_i].index(x)
    return res

def tv_remote(word):
    mydict ={"a":(0,0),"b":(1,0),"c":(2,0),"d":(3,0),"e":(4,0),"1":(5,0),"2":(6,0),"3":(7,0),
             "f":(0,-1),"g":(1,-1),"h":(2,-1),"i":(3,-1),"j":(4,-1),"4":(5,-1),"5":(6,-1),"6":(7,-1),
             "k":(0,-2),"l":(1,-2),"m":(2,-2),"n":(3,-2),"o":(4,-2),"7":(5,-2),"8":(6,-2),"9":(7,-2),
             "p":(0,-3),"q":(1,-3),"r":(2,-3),"s":(3,-3),"t":(4,-3),".":(5,-3),"@":(6,-3),"0":(7,-3),
             "u":(0,-4),"v":(1,-4),"w":(2,-4),"x":(3,-4),"y":(4,-4),"z":(5,-4),"_":(6,-4),"/":(7,-4)}
    sum = 0
    sum+= mydict[word[0]][0]+abs(mydict[word[0]][1])+1
    for i in range(len(word)-1):
        sum+= abs(mydict[word[i]][0]-mydict[word[i+1]][0])
        sum+= abs(mydict[word[i]][1]-mydict[word[i+1]][1]) +1
    return sum

def tv_remote(word):
    keyboard = [
        'a','b','c','d','e','1','2','3',
        'f','g','h','i','j','4','5','6',
        'k','l','m','n','o','7','8','9',
        'p','q','r','s','t','.','@','0',
        'u','v','w','x','y','z','_','/'
    ]
    
    prev_y, prev_x = 0, 0
    strokes = 0
    
    for char in word:
        x, y = keyboard.index(char)%8, keyboard.index(char)//8
        dist = abs(prev_x - x) + abs(prev_y - y) + 1;
        prev_x, prev_y = x, y
        strokes += dist
        
    return strokes
            
            


score = [
    ['a','b','c','d','e','1','2','3'],
    ['f','g','h','i','j','4','5','6'],
    ['k','l','m','n','o','7','8','9'],
    ['p','q','r','s','t','.','@','0'],
    ['u','v','w','x','y','z','_','/']
]

def getCoordinate(letter):
    x = [l.index(letter) for l in score if letter in l]
    y = [c for c in range(len(score)) if letter in score[c]]
    return [x[0],y[0]]

def tv_remote(word):
    res = 0
    pos = [0,0]
    for let in word:
        newPos = getCoordinate(let)
        res += abs(pos[0] - newPos[0]) + abs(pos[1] - newPos[1])+1
        pos[0] = newPos[0]
        pos[1] = newPos[1]
    return res


def tv_remote(word):
    t = ['abcde123','fghij456','klmno789','pqrst.@0','uvwxyz_/']
    r = 0
    pos = (0,0)
    for x in word:
        for i in range(5):
            if x in t[i]:
                r += abs(pos[1]-(t[i].index(x))) + 1 + abs(pos[0]-i)
                pos = (i,t[i].index(x))
    return r


def tv_remote(word):
    remote = [['a','b','c','d','e','1','2','3'],  # 0, 3 = 3
              ['f','g','h','i','j','4','5','6'],  # 2, 4 = 6
              ['k','l','m','n','o','7','8','9'],  # 0, 4 = 4
              ['p','q','r','s','t','.','@','0'],  # 3, 3 = 6
              ['u','v','w','x','y','z','_','/']]
    x, y = 0, 0
    enter = 1
    moves = 0
    for char in word:
        for row in range(len(remote)):
            for column in range(8):
                if remote[row][column] == char:
                    moves += abs(x - row) + abs(y - column) + enter
                    x = row
                    y = column
    return moves
    
    


grid = ["abcde123", "fghij456", "klmno789", "pqrst.@0", "uvwxyz_/"]

def tv_remote(word):
    steps = 0
    pos = (0, 0)
    for c in word:
        index = next((grid.index(x), x.index(c)) for x in grid if c in x)
        steps += abs(index[0] - pos[0]) + abs(index[1] - pos[1]) + 1
        pos = index
    return steps

keyboard = {
    'a': [0, 0],'b': [0,1],'c': [0,2],'d': [0,3],'e': [0,4],'1': [0,5],'2': [0,6],'3': [0,7],
    'f': [1, 0],'g': [1,1],'h': [1,2],'i': [1,3],'j': [1,4],'4': [1,5],'5': [1,6],'6': [1,7],
    'k': [2, 0],'l': [2,1],'m': [2,2],'n': [2,3],'o': [2,4],'7': [2,5],'8': [2,6],'9': [2,7],
    'p': [3, 0],'q': [3,1],'r': [3,2],'s': [3,3],'t': [3,4],'.': [3,5],'@': [3,6],'0': [3,7],
    'u': [4, 0],'v': [4,1],'w': [4,2],'x': [4,3],'y': [4,4],'z': [4,5],'_': [4,6],'/': [4,7],}
def tv_remote(word):
    moves = sum([abs(keyboard[word[0]][i]-keyboard['a'][i]) for i in range(2)])+1
    for l in range(1,len(word)):
        moves += sum([abs(keyboard[word[l]][i]-keyboard[word[l-1]][i]) for i in range(2)])+1
    return moves

import numpy as np
def tv_remote(word):
    answer = 0
    remote = np.array([['a','b','c','d','e','1','2','3'], 
            ['f','g','h','i','j','4','5','6'], 
            ['k','l','m','n','o','7','8','9'], 
            ['p','q','r','s','t','.','@','0'], 
            ['u','v','w','x','y','z','_','/']])
    row = 0
    col = 0
    for i in word:
        current_pos = np.where(remote == i)
        answer += abs(row - current_pos[0][0]) + abs(col - current_pos[1][0])
        row = current_pos[0][0]
        col = current_pos[1][0]
    answer += len(word)
    return(answer)

def tv_remote(word):
    import numpy as np
    i,j,s=0,0,0
    remote = np.array([['a','b','c','d','e','1','2','3'],
                       ['f','g','h','i','j','4','5','6'],
                       ['k','l','m','n','o','7','8','9'],
                       ['p','q','r','s','t','.','@','0'],
                       ['u','v','w','x','y','z','_','/']])
    for char in word:
        s += abs(np.where(remote==char)[0][0]-i)+abs(np.where(remote==char)[1][0]-j)+1
        i=np.where(remote==char)[0][0]
        j=np.where(remote==char)[1][0]
    return s

def tv_remote(word):
    keyboard = [
        ['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
        ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
        ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
        ['p', 'q', 'r', 's', 't', '.', '@', '0'],
        ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']
    ]
    x, y = 0, 0
    count = 0
    for char in word:
        for i in range(len(keyboard)):
            if char in keyboard[i]:
                y2 = i
                x2 = keyboard[i].index(char)
                count += 1 + abs(y2 - y) + abs(x2 - x)
                x, y = x2, y2
    return count

def tv_remote(word):
    remote = ['abcde123',
              'fghij456',
              'klmno789',
              'pqrst.@0',
              'uvwxyz_/',
              ]
    position = [0, 0]
    pressings = 0

    def find_key(key):
        for i in range(len(remote)):
            if key in remote[i]:
                return [i, remote[i].find(key)]

    for letter in word:
        pressings += 1 + abs(find_key(letter)[0] - position[0]) + abs(find_key(letter)[1] - position[1])
        position = find_key(letter)
    return pressings

def tv_remote(word):
    keyboard = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    horizontal_s = 0
    vertical_s = 0
    presses = 0
    for i in word:
        i_position = keyboard.find(i)
        horizontal = i_position % 8
        vertical = i_position // 8
        presses += (abs(horizontal - horizontal_s) + abs(vertical - vertical_s) + 1)
        horizontal_s = horizontal
        vertical_s = vertical
    return presses


import numpy as np

def tv_remote(word):
    keys = np.array([
        ['a','b','c','d','e','1','2','3'],
        ['f','g','h','i','j','4','5','6'],
        ['k','l','m','n','o','7','8','9'],
        ['p','q','r','s','t','.','@','0'],
        ['u','v','w','x','y','z','_','/']])
    [x1,y1]=[0,0]
    totdist = 0
    for i in range (0,len(word),1):
        [x2,y2]=np.where(keys == word[i])
        dist = abs(x1-x2)+abs(y1-y2)
        totdist += dist +1
        [x1,y1] = [x2,y2]
    return totdist

def tv_remote(word):
    print(word)
    remote = [['a','b','c','d','e','1','2','3'],
              ['f','g','h','i','j','4','5','6'],
              ['k','l','m','n','o','7','8','9'],
              ['p','q','r','s','t','.','@','0'],
              ['u','v','w','x','y','z','_','/']]
    second = find(remote, word[0])
    clicks = second[0] + second[1] + 1
    for i in range(len(word)-1):
        first = find(remote, word[i])
        second = find(remote, word[i+1])
        clicks += abs(second[0] - first[0])
        clicks += abs(second[1] - first[1]) + 1
    return clicks
        

def find(list, v):
    for i, x in enumerate(list):
        if v in x:
            return (i, x.index(v))
    

    
    


def dist(a,b):
    return abs(b[1]-a[1]) + abs(b[0]-a[0])

def pos(a): 
    if a in '123456789': return [(int(a)-1)%3 + 5, (int(a)-1)//3]
    d = {'.': [5, 3], '@': [6, 3], '0': [7,3], 'z': [5,4], '_': [6,4], '/': [7,4]}
    if a in list(d.keys()): return d[a]
    return [(ord(a)-97)%5, (ord(a)-97)//5]

def tv_remote(word):
    word = 'a'+word
    res = 0
    for i in range(len(word)-1):
        print((word[i], pos(word[i]), word[i+1], pos(word[i+1])))
        res += dist(pos(word[i]), pos(word[i+1]))
        
    return res+len(word)-1


class TvRemote():
    def __init__(self,words):
        self.x, self.y = (0, 0)
        self.presses = 0
        self.mode = 1
        self.modes = ["",
                      "abcde123fghij456klmno789pqrst.@0uvwxyz_/æ øøøøøø", 
                      "ABCDE123FGHIJ456KLMNO789PQRST.@0UVWXYZ_/æ øøøøøø",
                    """^~?!'"()-:;+&%*=<>€£$¥¤\[]{},.@§#¿¡øøø_/æ øøøøøø"""]
    
        words = words.replace("\u00a1","¡")
        words = words.replace("\u00a3","£")
        words = words.replace("\u00a4","¤")
        words = words.replace("\u00a5","¥")
        words = words.replace("\u00a7","€")
        words = words.replace("\u00bf","¿")
        words = words.replace("\u20ac","€")
        self.words = words
        print(words)
    
    def buttonPresses(self):
        for letter in self.words:
            self.presses += self.taxiCabDist(letter)
            print(self.presses,"\n")
            
        return self.presses
    
    
    def switchMode(self):
        print("EEROROROROROROR")
        self.mode += 1
        if self.mode > 3:
            self.mode = 1
            
        return self.taxiCabDist("æ")
    
    def taxiCabDist(self,letter):
        #SwitchMode
        modeSwitch = 0
        if letter not in self.modes[self.mode]:
            modeSwitch += self.switchMode()
            if letter not in self.modes[self.mode]:
                modeSwitch += self.switchMode()
                
        #Letter coord 
        index = self.modes[self.mode].index(letter)
        x, y = index % 8, index // 8
        
        #Absolute difference coord
        dx = abs(self.x-x)
        dy = abs(self.y-y)
        
        #log
        print(letter,(dx,dy),dx + dy + modeSwitch + 1)
        
        #Set New Cursor Position
        self.x = x
        self.y = y
        
        return dx + dy + modeSwitch + 1 # The OK Press
    
def tv_remote(word):
    return TvRemote(word).buttonPresses()

keyboard = [["a", "b", "c", "d", "e", "1", "2", "3"], \
            ["f", "g", "h", "i", "j", "4", "5", "6"], \
            ["k", "l", "m", "n", "o", "7", "8", "9"], \
            ["p", "q", "r", "s", "t", ".", "@", "0"], \
            ["u", "v", "w", "x", "y", "z", "_", "/"]] 

def tv_remote(word):
    current_point = [0, 0]
    
    ret_val = 0
    
    for i in word:
        x = [x for x in keyboard if i in x][0]
        ret_val += abs(current_point[0]-keyboard.index(x))+abs(current_point[1]-x.index(i))+1
        current_point = [keyboard.index(x), x.index(i)]
    
    return(ret_val)

def tv_remote(word):
    keyboard = [
        'abcde123',
        'fghij456',
        'klmno789',
        'pqrst.@0',
        'uvwxyz_/'
    ]
    total = 0
    r_start = 0
    c_start = 0
    for i in word:
        for j in range(len(keyboard)):
            if i.lower() in keyboard[j]:
                total += abs(j - r_start) + abs(keyboard[j].index(i.lower()) - c_start) + 1
                r_start = j
                c_start = keyboard[j].index(i.lower())
    return total

def tv_remote(word):
    keypad = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    list(keypad)
    list(word)
    indices = [keypad.index(letter) for letter in word]
    coord_x = [ind % 8 for ind in indices]
    coord_x.insert(0,0)
    coord_y = [int(ind/8) for ind in indices]
    coord_y.insert(0,0)
    
    steps_x = [abs(coord_x[i+1] - coord_x[i]) for i in range(len(coord_x) - 1)]
    steps_y = [abs(coord_y[i+1] - coord_y[i]) for i in range(len(coord_y) - 1)]
    
    presses = [steps_x[i] + steps_y[i] + 1 for i in range(len(steps_x))]
    
    return sum(presses)

def tv_remote(word):
    # Your code here!!
    string = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
    mydict = {letter: dict() for letter in string}
    visited = set()
    
    for i in range(5):
        for j in range(8):

            board = [list(string[x*8:x*8+8]) for x in range(5)]
            base = board[i][j]
            queue = [(i,j,0)]
            while queue:
                
                x,y,dist = queue.pop(0)
                if board[x][y] in visited: continue
                if board[x][y] == -1: continue
            
                letter = board[x][y]
                board[x][y] = -1
                
                mydict[base][letter] = dist
                mydict[letter][base] = dist
                
                for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
                    if 0<=x+dx<len(board) and 0<=y+dy<len(board[0]):
                        queue.append((x+dx, y+dy,dist+1))
            
            visited.add(base)
    
    base = 'a'
    nums = 0
    for letter in word:
        nums += mydict[base][letter]
        base = letter
    
    return nums + len(word)

def split(string):
    return [char for char in string]

layout = [split("abcde123"),
     split("fghij456"),
     split("klmno789"),
     split("pqrst.@0"),
     split("uvwxyz_/")]

position = dict((j,(x, y)) for x, i in enumerate(layout) for y, j in enumerate(i))

def tv_remote(word):
    presses = 0
    current = 'a'
    for i, char in enumerate(word):
        target = char
        distance = abs(position[current][0] - position[target][0]) + abs(position[current][1] - position[target][1])
        presses += distance + 1
        current = char
    return presses

def make_move(layout, start, end):
    x = [x for x in layout if start in x][0]
    index = (layout.index(x), x.index(start))
    y = [y for y in layout if end in y][0]
    index2 = (layout.index(y), y.index(end))
    move = abs(index[0] - index2[0]) + abs(index[1] - index2[1])
    return move + 1

def tv_remote(word):
    count = 0
    word = 'a' + word
    layout = [['a', 'b', 'c', 'd', 'e', '1', '2', '3'], ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
              ['k', 'l', 'm', 'n', 'o', '7', '8', '9'], ['p', 'q', 'r', 's', 't', '.', '@', '0'],
              ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']]
    for i in range(len(word)-1):
        count += make_move(layout, word[i], word[i+1])
    return count

def tv_remote(word):
    total_moves = 0
    start_pos = [1, 1]
    grid = {
        "a":[1,1],"b":[1,2],"c":[1,3],"d":[1,4],"e":[1,5],"1":[1,6],"2":[1,7],"3":[1,8],
        "f":[2,1],"g":[2,2],"h":[2,3],"i":[2,4],"j":[2,5],"4":[2,6],"5":[2,7],"6":[2,8],
        "k":[3,1],"l":[3,2],"m":[3,3],"n":[3,4],"o":[3,5],"7":[3,6],"8":[3,7],"9":[3,8],
        "p":[4,1],"q":[4,2],"r":[4,3],"s":[4,4],"t":[4,5],".":[4,6],"@":[4,7],"0":[4,8],
        "u":[5,1],"v":[5,2],"w":[5,3],"x":[5,4],"y":[5,5],"z":[5,6],"_":[5,7],"/":[5,8]}
    
    
    for l in word:
        v_moves = abs(grid[l][0] - start_pos[0])
        h_moves = abs(grid[l][1] - start_pos[1])
        total_moves += (v_moves + h_moves + 1)
        start_pos = grid[l]
    return total_moves

def tv_remote(word):
    kboard = ['a','b','c','d','e','1','2','3',
            'f','g','h','i','j','4','5','6',
           'k','l','m','n','o','7','8','9',
           'p','q','r','s','t','.','@','0',
           'u','v','w','x','y','z','_','/']
    
    start = 'a'
    count = 0;
    
    for c in word:
        pos1 = kboard.index(start)
        pos2 = kboard.index(c)
        count += max(pos1//8,pos2//8) - min(pos1//8,pos2//8)
        count += max(pos1%8,pos2%8) - min(pos1%8,pos2%8)
        count += 1 # accept character with 'OK'
        start = c
    return count

import string
def tv_remote(word):
    let = 0   
    numbers = "123456789.@0z_/"
    keyboard = { (i,j):0 for i in range(1,6) for j in range(1,9) }
    for i in range(1,6):
        for j in range(1,6):
            keyboard[i,j] = string.ascii_lowercase[let]
            let += 1
    let = 0
    for i in range(1,6):
        for j in range(6,9):
            keyboard[i,j] = numbers[let]
            let += 1
    print(keyboard)
    keys = list(keyboard.keys()) 
    vals = list(keyboard.values()) 
    cursor = [1,1]
    moves = 0
    for i in word:
        moves += 1 + (abs((keys[vals.index(i)][0]) - cursor[0]) + abs((keys[vals.index(i)][1]) - cursor[1]))
        cursor = keys[vals.index(i)]
    return moves


import numpy as np

    
def tv_remote(word):
    num_oks = len(word)
    word = 'a' + word
    anum = 97
    m_ay = n_ay = 5
    m_num = n_num = 3
    
    posdict_ay = {chr(num) : np.asarray(np.divmod(num-anum, n_ay)) for num in np.arange(anum, anum + 25)}
    posdict_num = {str(num+1) : np.divmod(num, n_num) + np.array([0, n_ay]) for num in range(0,9)}
    posdict_rest = {val : np.divmod(idx, n_num) + np.array([m_num, n_ay]) for idx, val in enumerate('.@0z_/')}
    
    posdict = {**posdict_ay, **posdict_num, **posdict_rest}
    distlist = [np.linalg.norm(posdict[pair[0]] - posdict[pair[1]], ord = 1) for pair in zip(word[1:], word[:-1])]
    
    return sum(distlist) + num_oks

def tv_remote(word):
    kb = {char:(pos//8, pos%8) for pos, char in enumerate('abcde123fghij456klmno789pqrst.@0uvwxyz_/')}
    presses, current = 0, (0, 0)
    for char in word:
        presses += 1 + abs(current[0] - kb[char][0]) + abs(current[1] - kb[char][1])
        current = kb[char]
    return presses

import numpy as np

board = np.array(list('abcde123fghij456klmno789pqrst.@0uvwxyz_/')).reshape(5,8)
board = {v:i for i,v in np.ndenumerate(board)}

def tv_remote(word):
    '''I'm not happy with this messy stuff'''
    x,y = (0,0)
    result = 0
    for letter in word:
        x1,y1 = board[letter]
        result += abs(x-x1) + abs(y-y1) + 1
        x,y = x1,y1
    return result

import numpy as np


def tv_remote(word):
    keyboard = np.array([['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
                         ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
                         ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
                         ['p', 'q', 'r', 's', 't', '.', '@', '0'],
                         ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']])
    x1, y1, sum = 0, 0, 0
    for letter in word:
        x2, y2 = np.argwhere(keyboard == letter)[0][:]
        sum += 1 + abs(x2 - x1) + abs(y2 - y1)
        x1, y1 = x2, y2
    return sum

def tv_remote(word):
    kb = ['abcde123','fghij456','klmno789','pqrst.@0','uvwxyz_/']
    kb_d = {}
    for i, row in enumerate(kb):
        for j, char in enumerate(row):
            kb_d[char] = (i, j)
            
    x, y = 0, 0
    counter = 0
    
    for letter in word:
        dx, dy = kb_d[letter]
        counter += abs(dx-x) + abs(dy-y) + 1
        x, y = dx, dy
    
    return counter   

import numpy as np, pandas as pd

def tv_remote(word):
    print(word)
    screen = np.array([['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
                          ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
                       ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
                       ['p', 'q', 'r', 's', 't', '.', '@', '0'],
                       ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']])



    screen_col = 0
    screen_row = 0
    start = screen[screen_row,screen_col]
    count = 0
    word = word
    lst = [x for x in word]
                          
    for x in lst:
        if x in screen[screen_row]:
            result = np.where(screen == x)
            if result[1][0] > screen_col:
                count += (result[1][0] - screen_col) +1
            elif result[1][0] < screen_col:
                count += (screen_col - result[1][0]) +1
            else:
                count+=1
            screen_row = result[0][0]
            screen_col = result[1][0]

            print('Done with {}'.format(x))
            print(count)

        else:
            result = np.where(screen == x)
            if result[0][0] > screen_row:
                count += (result[0][0] - screen_row)
                if result[1][0] > screen_col:
                    count += (result[1][0] - screen_col) +1
                elif result[1][0] < screen_col:
                    count += (screen_col - result[1][0]) +1
                else:
                    count+=1
                
            elif result[0][0] < screen_row:
                count += (screen_row - result[0][0])
                if result[1][0] > screen_col:
                    count += (result[1][0] - screen_col) +1
                elif result[1][0] < screen_col:
                    count += (screen_col - result[1][0]) +1
                else:
                    count+=1

            
            screen_row = result[0][0]
            screen_col = result[1][0]
            print('Done with {}'.format(x))
            print(count)
            
    return count

keyboard="abcde123fghij456klmno789pqrst.@0uvwxyz_/"
def manhattan(x1, y1, x2, y2):
    return abs(y2 - y1) + abs(x2 - x1)
def index_2d(index_1d):
    return index_1d % 8, index_1d // 8
def tv_remote(word):
    c_x, c_y = 0, 0
    distance = 0
    for char in word:
        new_x, new_y = index_2d(keyboard.index(char))
        distance+= manhattan(c_x, c_y, new_x, new_y) + 1
        c_x, c_y = new_x, new_y
    return distance

def tv_remote(word):
    keyboard = {
        'a':[0, 0], 'b':[0, 1], 'c':[0, 2], 'd':[0, 3], 'e':[0, 4], '1':[0, 5], '2':[0, 6], '3':[0, 7],
        'f':[1, 0], 'g':[1, 1], 'h':[1, 2], 'i':[1, 3], 'j':[1, 4], '4':[1, 5], '5':[1, 6], '6':[1, 7],
        'k':[2, 0], 'l':[2, 1], 'm':[2, 2], 'n':[2, 3], 'o':[2, 4], '7':[2, 5], '8':[2, 6], '9':[2, 7],
        'p':[3, 0], 'q':[3, 1], 'r':[3, 2], 's':[3, 3], 't':[3, 4], '.':[3, 5], '@':[3, 6], '0':[3, 7],
        'u':[4, 0], 'v':[4, 1], 'w':[4, 2], 'x':[4, 3], 'y':[4, 4], 'z':[4, 5], '_':[4, 6], '/':[4, 7],}
    clicks = 0
    pos = [0, 0]
    pos1 = [0, 0]
    for char in word:
        pos1 = keyboard.get(char)
        clicks += abs(pos1[0] - pos[0]) + abs(pos1[1] - pos[1])
        pos = pos1
    return clicks + len(word)

def tv_remote(word):
    keypad = [['a','b','c','d','e','1','2','3'],
              ['f','g','h','i','j','4','5','6'],
              ['k','l','m','n','o','7','8','9'],
              ['p','q','r','s','t','.','@','0'],
              ['u','v','w','x','y','z','_','/']]
    sum = 0
    coords = [(0,0)]
    for char in list(word):
        for index, row in enumerate(keypad):
            if char in row:
                coords.append((index,row.index(char)))
    for c,point in enumerate(coords,0):
        if c == 0:
            continue
        a, b = point
        sum += abs(coords[c][0] - coords[c-1][0])
        sum += abs(coords[c][1] - coords[c-1][1])
        sum += 1
        print(sum)
    return sum

keydict={'a':'00','b':'01','c':'02','d':'03','e':'04','1':'05','2':'06','3':'07',
         'f':'10','g':'11','h':'12','i':'13','j':'14','4':'15','5':'16','6':'17',
         'k':'20','l':'21','m':'22','n':'23','o':'24','7':'25','8':'26','9':'27',
         'p':'30','q':'31','r':'32','s':'33','t':'34','.':'35','@':'36','0':'37',
         'u':'40','v':'41','w':'42','x':'43','y':'44','z':'45','_':'46','/':'47'}
def tv_remote(word):
    step = 0
    start = '00'
    for i in word:
        step+= (abs(int(keydict.get(i)[0])-int(start[0]))+abs(int(keydict.get(i)[1])-int(start[1]))+1)
        start = keydict.get(i)
    return step

def tv_remote(word):

    keyboard = {"a":[1,1], "b":[1,2], "c":[1,3], "d":[1,4], "e":[1,5], "1":[1,6], "2":[1,7], "3":[1,8],
                "f":[2,1], "g":[2,2], "h":[2,3], "i":[2,4], "j":[2,5], "4":[2,6], "5":[2,7], "6":[2,8],
                "k":[3,1], "l":[3,2], "m":[3,3], "n":[3,4], "o":[3,5], "7":[3,6], "8":[3,7], "9":[3,8],
                "p":[4,1], "q":[4,2], "r":[4,3], "s":[4,4], "t":[4,5], ".":[4,6], "@":[4,7], "0":[4,8],
                "u":[5,1], "v":[5,2], "w":[5,3], "x":[5,4], "y":[5,5], "z":[5,6], "_":[5,7], "/":[5,8]}

    cursor_count = 0

    word_in_num = [[1,1]]

    count_list = []

    cursor_count = []

    for char in word:

        word_in_num.append(keyboard[char])

    for index, num in enumerate(word_in_num):

        if index == 0:
            continue

        cursor_count = (abs(word_in_num[index][0] - word_in_num[index-1][0])) + (abs(word_in_num[index][1] - word_in_num[index-1][1])) + 1

        count_list.append(cursor_count) 

        cursor_count = 0
            
    count_list = sum(count_list)

    return count_list


def tv_remote(word):
    count = 0
    index = 0
    remote_dict = {'a' : (1,1), 'b': (2,1), 'c' : (3,1), 'd' : (4,1), 'e' : (5,1), '1' : (6,1), '2' : (7,1), '3' : (8,1),
                   'f' : (1,2), 'g': (2,2), 'h' : (3,2), 'i' : (4,2), 'j' : (5,2), '4' : (6,2), '5' : (7,2), '6' : (8,2),
                   'k' : (1,3), 'l': (2,3), 'm' : (3,3), 'n' : (4,3), 'o' : (5,3), '7' : (6,3), '8' : (7,3), '9' : (8,3),
                   'p' : (1,4), 'q': (2,4), 'r' : (3,4), 's' : (4,4), 't' : (5,4), '.' : (6,4), '@' : (7,4), '0' : (8,4),
                   'u' : (1,5), 'v': (2,5), 'w' : (3,5), 'x' : (4,5), 'y' : (5,5), 'z' : (6,5), '_' : (7,5), '/' : (8,5)}
    
    Xdist = abs(remote_dict[word[index]][0] - remote_dict['a'][0])
    Ydist = abs(remote_dict[word[index]][1] - remote_dict['a'][1])
    count += (Xdist + Ydist + 1)
    
    for index in range(len(word) -1):
        Xdist = 0
        Ydist = 0
        Xdist = abs(remote_dict[word[index]][0] - remote_dict[word[index + 1]][0])
        Ydist = abs(remote_dict[word[index]][1] - remote_dict[word[index + 1 ]][1])
        count += (Xdist + Ydist + 1)
    print(count)
    return count


def ind(w):
    a = [['a', 'b', 'c', 'd', 'e', '1', '2', '3'],
    ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],
    ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],
    ['p', 'q', 'r', 's', 't', '.', '@', '0'],
    ['u', 'v', 'w', 'x', 'y', 'z', '_', '/']]

    for i in range(len(a)):
        for j in range(len(a[0])):
            if a[i][j] == w: return (i, j)

def tv_remote(word):
    press = sum(ind(word[0])) + len(word) 
    for i in range(len(word)-1):
        f_i, f_j = ind(word[i])
        s_i, s_j = ind(word[i+1])
        press += abs(f_i - s_i) + abs(f_j - s_j)
    return press

def tv_remote(word):
    keyboard = "abcde123fghij456klmno789pqrst.@0uvwxyz_/"
    presses = 0
    pointer_pos = (0, 0)
    for i in word:
        letter_pos = keyboard.index(i)
        letter_pos = (letter_pos % 8, letter_pos // 8)
        presses += abs(letter_pos[0] - pointer_pos[0]) + abs(letter_pos[1] - pointer_pos[1]) + 1
        pointer_pos = letter_pos
    return presses

remote = ["abcde123", "fghij456", "klmno789", "pqrst.@0", "uvwxyz_/"]
def tv_remote(word):
    current = find_char("a")
    result = 0
    for character in word:
        new = find_char(character)
        result += sum([abs(current[0]-new[0]), abs(current[1]-new[1])])+1
        current = new
    return result

def find_char(char):
    for col in range(0, len(remote)):
        if char in remote[col]:
            return [col, remote[col].find(char)]

def tv_remote(word):
    
    dic = {'a':[1,1],'b':[1,2],'c':[1,3],'d':[1,4],'e':[1,5],'1':[1,6],'2':[1,7],'3':[1,8], \
           'f':[2,1],'g':[2,2],'h':[2,3],'i':[2,4],'j':[2,5],'4':[2,6],'5':[2,7],'6':[2,8], \
           'k':[3,1],'l':[3,2],'m':[3,3],'n':[3,4],'o':[3,5],'7':[3,6],'8':[3,7],'9':[3,8], \
           'p':[4,1],'q':[4,2],'r':[4,3],'s':[4,4],'t':[4,5],'.':[4,6],'@':[4,7],'0':[4,8], \
           'u':[5,1],'v':[5,2],'w':[5,3],'x':[5,4],'y':[5,5],'z':[5,6],'_':[5,7],'/':[5,8]}
    
    buttons_pressed = len(word)
    pos1 = dic['a']
    
    for i in range(0,len(word)):
        pos2 = dic[word[i]]
        buttons_pressed += abs(pos2[0]-pos1[0]) + abs(pos2[1]-pos1[1])
        pos1 = pos2
        
    return buttons_pressed

keyboard = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'
MAP = {c: (i//8, i % 8) for i, c in enumerate(keyboard)}


def tv_remote(word):
    cur = (0, 0)
    steps = 0
    for c in word:
        steps += 1 + abs(cur[0]-MAP[c][0])+abs(cur[1]-MAP[c][1])
        cur = MAP[c]
    return steps

keyboard='abcde123fghij456klmno789pqrst.@0uvwxyz_/'
MAP={c:(i//8,i%8) for i,c in enumerate(keyboard)}

def tv_remote(word): ###
    cur=(0,0)
    steps=0
    for c in word:
        steps+= 1 + abs(cur[0]-MAP.get(c)[0])+abs(cur[1]-MAP.get(c)[1])
        cur=MAP.get(c)
    return steps

keyboard = {
    "a": (0,0),
    "b": (0,1),
    "c": (0,2),
    "d": (0,3),
    "e": (0,4),
    "1": (0,5),
    "2": (0,6),
    "3": (0,7),

    "f": (1,0),
    "g": (1,1),
    "h": (1,2),
    "i": (1,3),
    "j": (1,4),
    "4": (1,5),
    "5": (1,6),
    "6": (1,7),

    "k": (2,0),
    "l": (2,1),
    "m": (2,2),
    "n": (2,3),
    "o": (2,4),
    "7": (2,5),
    "8": (2,6),
    "9": (2,7),
    
    "p": (3,0),
    "q": (3,1),
    "r": (3,2),
    "s": (3,3),
    "t": (3,4),
    ".": (3,5),
    "@": (3,6),
    "0": (3,7),

    "u": (4,0),
    "v": (4,1),
    "w": (4,2),
    "x": (4,3),
    "y": (4,4),
    "z": (4,5),
    "_": (4,6),
    "/": (4,7),
}


def tv_remote(word):
    n = 0
    current = "a"

    for key in word:
        n += abs(keyboard[key][0] - keyboard[current][0])
        n += abs(keyboard[key][1] - keyboard[current][1])
        n += 1
        current = key
        
    return n