【问题标题】:Python: Find distinct abreviations of stringsPython:查找字符串的不同缩写
【发布时间】:2018-04-17 19:41:58
【问题描述】:

我有一个字符串列表,我想缩写为最短的不同形式。

原始字符串:

topology
track
translate
trunk
tunnel
ucse
udp
usb
user-group

缩写字符串:

to
trac
tran
tru
tu
uc
ud
usb
use

我将如何在 python (3) 中做到这一点?

【问题讨论】:

  • 太宽泛了,你试过什么?你遇到了什么错误? SO 不是代码编写服务,抱歉。
  • 快乐编码。 SO 是关于修复你的代码——而不是实现你的想法。请再次查看how to askon-topic,如果您有任何问题,请提供您的代码mvce
  • 所以最短的唯一前缀。这可以通过一个 trie 来完成,只需构建一个,然后沿着每个分支走,并报告每个分支的前缀都有一个子节点。
  • 那么为什么拓扑没有缩写为“t”?
  • to 是一个唯一的前缀。 t 不是。

标签: python


【解决方案1】:
from collections import Counter

words = """\
topology
track
translate
trunk
tunnel
ucse
udp
usb
user-group""".splitlines()


def prefixes(word):
    for i in range(1, len(word) + 1):
        yield word[:i]


def main():
    prefix_counts = Counter()
    for word in words:
        prefix_counts.update(prefixes(word))
    for word in words:
        for prefix in prefixes(word):
            if prefix_counts[prefix] == 1:
                print(prefix)
                break
        else:
            # word is a prefix of another word
            print(word)


main()

【讨论】:

    【解决方案2】:

    不是最有效的,但这里有一种使用列表理解的方法:

    myList = [
        'topology',
        'track',
        'translate',
        'trunk',
        'tunnel',
        'ucse',
        'udp',
        'usb',
        'user-group'
    ]
    
    abbrevs = [
        next(
             word[:k] for k in range(1, len(word)+1) 
             if k==len(word) or not any(other.startswith(word[:k])
                                        for other in myList if word!=other)
        )
        for word in myList
    ]
    
    print(abbrevs)
    #['to', 'trac', 'tran', 'tru', 'tu', 'uc', 'ud', 'usb', 'use']
    

    【讨论】:

    • 不错。我将通过用word != other 替换i != j 并删除next((...)) 中的额外括号来简化代码
    • @AlexHall 这是一个很好的观点。除了更简单之外,检查word != other 也更健壮,因为它会处理列表中重复单词的情况。
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2023-02-10
    • 2012-10-24
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多