Consecutive letters in python

落花浮王杯 提交于 2019-12-06 17:32:21

问题


I am trying to find consecutive letters in an entered string:

if a string contains three consecutive letters based on the layout of a UK QWERTY keyboard then a variable is given 5 points for each set of three.

e.g. asdFG would contain three consecutive sets. upper and lowercase do not matter.

can you please help as don't know where to begin with this?


回答1:


The easiest way would be to first generate all possible triples:

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

If you only want the characters and not numbers and brackets etc., substitute the lines above with

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

Now that we have all the triples, you can check with count how many times a triple occurs in inputed string.

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)

Bam, there you go. What this does is it counts for each triple how many times it occurs in a string so you know how many times to add 5 points. We use str.lower() to convert all characters to lowercase because as you said, capitalization does not matter.

If it is the same whether a string contains a certain triple once or three times, then you can do this:

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



回答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)


来源:https://stackoverflow.com/questions/45999367/consecutive-letters-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!