Consecutive letters in python

2019-04-17 14:36发布

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?

2条回答
甜甜的少女心
2楼-- · 2019-04-17 15:22

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)
查看更多
够拽才男人
3楼-- · 2019-04-17 15:25
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)
查看更多
登录 后发表回答