ex10 找出藏在字符串中的“密码”

描述

题源

说明

  • 题中带有一条极长的字符串,不方便写在此随笔中
  • 字符串可以自己造一个或去上面题源复制

要求

  • 有一字符串,包含大小写英文字母与回车
  • 挑出所有左右两边均有连续的 3 个大写字母的小写字母
  • 例如 AAAAjBBBpCCCrDDmEEEyFFFqqGGG => py

程序

解法一:利用编号

  1. 找出所有小写字母的索引
  2. 若某索引与其左右的差均为 4,则该索引对应的字母为目标字母
def decrypt(string):
    lower = [i for i in range(len(string)) if string[i].islower()]
    found = []
    for i in range(1, len(lower) - 1):  # 这里没有检测头尾
        if 4 == lower[i] - lower[i - 1] == lower[i + 1] - lower[i]:
            if '\n' not in string[lower[i] - 3:lower[i] + 4]:
                found.append(string[lower[i]])
    print(''.join(found))

解法二:模拟

string = """..."""

res = []
target = -1
left = mid = right = 0
for i, s in enumerate(string):
    if s.islower():
        if right == 3:
            res.append(string[target])
            target = i
            mid, right = 1, 0
        elif 0 < right < 3:
            left = mid = right = 0
        elif left == 3:
            if not mid:
                mid = 1
                target = i
            else:
                left = mid = 0
        elif left < 3:
            left = 0
    elif s.isupper():
        if right == 3:
            left, mid, right = -1, 0, 0
        elif 0 < right < 3:
            right += 1
        elif mid:
            right = 1
        elif left == 3:
            left = -1
        elif -1 < left < 3:
            left += 1
print(''.join(res))

解法三:正则

print(''.join(__import__("re").findall("[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]", string)))
posted @ 2019-02-15 23:16  YorkFish  阅读(972)  评论(0编辑  收藏  举报