检查键盘上相邻字符的字符串

Checking a string for adjacent characters on the keyboard

我正在尝试检查字符串中的连续字符以查看它们在键盘上是否相邻。这是我正在编写的用于评估密码强度的程序的一部分。

我有将键盘初始化为数组的代码:

KeyboardRow1 = ["`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", ""]
KeyboardRow2 = ["", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", ""] 
KeyboardRow3 = ["", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "", "", ""] 
KeyboardRow4 = ["", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/", "", "", ""]
KeyboardRow1S = ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", ""]
KeyboardRow2S = ["", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "|"]
KeyboardRow3S = ["","A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "", "", ""] 
KeyboardRow4S = ["", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "", "", ""]
Rows = [KeyboardRow1, KeyboardRow2, KeyboardRow3, KeyboardRow4, \
        KeyboardRow1S, KeyboardRow2S, KeyboardRow3S, KeyboardRow4S]

然后我有这个函数将输入的密码的每个字符转换为键盘数组内的坐标:

def ConvertToCoordinates(Password):

    Coordinates = []
    for c in Password:
        for i, r in enumerate(Rows):
            try:
                Coordinates.append((i % 4, r.index(c)))
            except:
                pass
    return Coordinates

最后,这是检查邻接的函数 - 我需要帮助的地方:

def CheckForAdjacency(Coordinates):

    Adjacent = 0
    for pairs in combinations(Coordinates, 2):
        if (abs(pairs[0][0] - pairs[1][0]) == 1) \
           and (abs(pairs[0][1] - pairs[1][1]) == 1):
            Adjacent += 1
    return Adjacent

上述函数检查字符串中每个字符的相互关系,而不是仅检查字符串中相邻的字符。

例如,我希望 qwerty 为 return 5 个相邻字符,而 qetwr 为 return 0。如果 qwerty 是密码,该函数确实 return 5。但是,如果 qetwr 是密码,它也是 returns 5;它检查所有字符而不是相邻的字符。

如何让它只检查字符串中相邻的字符?我知道问题出在 "for pairs in combinations" 的使用上,我认为它会检查所有可能的配置和配对。

我认为您判断两个键是否相邻的逻辑不太正确。如果两个键相邻(或相同),则它们的 x 或 y 坐标不能大于 1。

同样itertools.combinations生成坐标的所有组合,但你只想计算相邻的坐标。

例如password = 'ABCD' 组合给你 'AB AC AD BC BD CD'

def isAdjacent(Coord1, Coord2):
    if abs(Coord1[0] - Coord2[0]) > 1 or abs(Coord1[1] - Coord2[1]) > 1:
        return False
    else:
        return True

def CheckForAdjacency(Coordinates):
    Adjacent = 0
    for i in range(len(Coordinates) - 1):
        if isAdjacent(Coordinates[i], Coordinates[i +1]):
            Adjacent += 1
    return Adjacent