python - 使用python的字符串中最接近的字符

标签 python python-3.x

我对 Python 比较陌生;我编写了以下代码来查找字符串中与 queries 中的索引最接近的字符,我想找到一种优化代码的方法:

示例:

输入字符串: s = 'adarshravi'

queries = [2, 4](这些是要查找重复字符的索引,输出应该有最接近重复的索引,如果没有重复字符,那么它的输出将为 -1)

上述查询的输出将是: [0, -1]

输出说明:

对于索引 2,字符串中的字符是 a 字符串中还有另外两个 a,一个在 0 索引处,另一个一个在索引 7,所以两者之间最接近的是在 0th 位置的那个,而在 4th 索引的字符是s 在字符串中不重复 所以 -1

def closest(s, queries):

    s = s.lower()
    listIdx = []

    for i in queries:
        foundidx = []
        srchChr = s[i]

        for j in range(0, len(s)):
            if s[j] == srchChr:
                foundidx.append(j)

        if len(foundidx) < 2:
            listIdx.append(-1)
        else:
            lastIdx = -1
            dist = 0
            foundidx.remove(i)
            for fnditem in foundidx:
                if dist == 0:
                    lastIdx = fnditem
                    dist = abs(fnditem - i)
                else:
                    if abs(fnditem - i) < dist:
                        lastIdx = fnditem
                        dist = abs(fnditem - i)
            listIdx.append(lastIdx)
    return listIdx

最佳答案

我们可以构造一个索引列表,如:

from itertools import zip_longest

def ranges(k, n):
    for t in zip_longest(range(k-1, -1, -1), range(k+1, n)):
        yield from filter(lambda x: x is not None, t)

因此生成的索引如下:

>>> list(ranges(3, 10))
[2, 4, 1, 5, 0, 6, 7, 8, 9]

我们可以使用上面的方法来检查最接近的字符:

def close(text, idx):
    ci = text[idx]
    return next(filter(lambda i: ci == text[i], ranges(idx, len(text))), -1)

这会产生:

>>> close('adarshravi', 0)
2
>>> close('adarshravi', 1)
-1
>>> close('adarshravi', 2)
0
>>> close('adarshravi', 3)
6
>>> close('adarshravi', 4)
-1

closest 只是 close 函数在列表上的“映射”:

from functools import partial

def closest(text, indices):
    return map(partial(close, text), indices)

例如:

>>> list(closest('adarshravi', range(5)))
[2, -1, 0, 6, -1]

关于python - 使用python的字符串中最接近的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795707/

相关文章:

python - import 是否在路径之前先查找当前工作目录?或者cwd的路径?

python - 可以在 python 3.7 中以编程方式定义 Unicode 字符吗?

python - 正则表达式提取整数或浮点值后跟一个单位,Python

javascript - 清除链接的相关下拉组合框选择中选定(子)类别的所有子类别

python - 使用scrapy从xml中提取链接

python - 查找前面没有其他字符串的字符串

python - Python 脚本必须将函数定义为 main 吗?

python - Bash 使用来自 Anaconda 的 Python,即使它已被停用

python - Pygame:允许点击穿过窗口

python-3.x - 获取 Boto3 中具有特定标签和值的 EC2 实例列表