python中的连续字母

2024-05-15 23:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在输入的字符串中找到连续的字母:

如果一个字符串包含三个基于UK QWERTY键盘布局的连续字母,则每三个字符集给一个变量5分。

例如,asdFG将包含三个连续的集合。大小写无关紧要。

你能帮忙吗?因为你不知道从哪里开始?


Tags: 字符串字母布局键盘uk字符集qwertyasdfg
2条回答
qwerty = 'qwertyuiopasdfghjklzxcvbnm'

inp = 'ASdfqazfghZZxc'
inp_lower = inp.lower()

points = 0

for idx in range(0, len(inp_lower) - 2):
    test_seq = inp_lower[idx:idx + 3]
    if test_seq in qwerty:
        points += 5
        print(test_seq, '->', points)
    else:
        print(test_seq)

最简单的方法是首先生成所有可能的三元组:

lines = ["`1234567890-=", "qwertyuiop[]", "asdfghjkl;'\\", "<zxcvbnm,./"]
triples = []
for line in lines:
    for i in range(len(line)-2):
        triples.append(line[i:i+3])

如果只需要字符而不需要数字和括号等,请用上面的lines替换

lines = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]

现在我们有了所有的三元组,您可以使用count检查三元组在输入字符串中出现的次数。

input_string = input().strip().lower()
score = 0
for triple in triples:
    number_of_occurrences = input_string.count(triple)
    score += 5 * number_of_occurrences
print(score)

砰,给你。它的作用是计算每个三元组在一个字符串中出现的次数,这样你就知道要加5个点需要多少次。我们使用str.lower()将所有字符转换为小写,因为正如您所说,大写并不重要。

如果字符串包含某个三元组一次还是三次是相同的,则可以执行以下操作:

input_string = input().strip().lower()
score = 0
for triple in triples:
    if triple in input_string:
        score += 5
print(score)

相关问题 更多 >