算法在Python中的实现

发布于 2024-12-15 10:16:00 字数 1303 浏览 1 评论 0原文

我有某些算法需要实现。基本上规则是:

  1. 一行上的第一个空格分隔的标记将是正在定义的单词。
  2. 后面的标记将是定义。如果定义是“.”,则该词是原语,即没有定义的词。
  3. 输出是一个以逗号分隔的文本行,其中包含字典中的每个单词一次。每个单词只能在其定义中的所有单词之后打印。请注意,对于某些输入集,可能有多个有效输出。

例如输入:

Civic        Honda Car
Honda        Manufacturer
VW           Manufacturer
Manufacturer .
Car          .
Beetle       VW Car

一些可能的输出:

Car, Manufactor, Honda, VW, Beetle, Civic
Manufacturer, VW, Car, Beetle, Honda, Civic
Manufacturer, Honda, VW, Car, Beetle, Civic

我的实现:

def defIt(pre, cur):
    # If previous and current strings are the same, no action take
    if pre == cur:
        return pre

    # Split two strings to list
    l_pre = pre.split()
    l_cur = cur.split()

    # If previous string length is shorter than the current string     length, then swap two lists
    if len(l_pre) < len(l_cur):
        l_pre, l_cur = l_cur, l_pre

    found = False


    for j, w_cur in enumerate(l_cur):
        for i, w_pre in enumerate(l_pre):
            if w_pre == w_cur:
                found = True
                return ' '.join(l_cur[j:] + l_cur[:j] + l_pre[:i] + l_pre[(i + 1):])


    if not found:
        return ' '.join(l_cur[1:] + [l_cur[0]] + l_pre)

只是无法正确执行。我缺少什么?多谢。

I have certain algorithm need to implement. Basically the rules are:

  1. The first whitespace-separated token on a line will be the word being defined.
  2. The later tokens will be the definition. If the definition is “.”, that word is a primitive, i.e., a word with no definition.
  3. The output is a single comma-separated line of text containing each word in the dictionary exactly once. Each word is only to be printed after all of the words in its definition. Note that for certain input sets, there may be multiple valid outputs.

For example the input:

Civic        Honda Car
Honda        Manufacturer
VW           Manufacturer
Manufacturer .
Car          .
Beetle       VW Car

Some Possible Outputs:

Car, Manufactor, Honda, VW, Beetle, Civic
Manufacturer, VW, Car, Beetle, Honda, Civic
Manufacturer, Honda, VW, Car, Beetle, Civic

My implementation:

def defIt(pre, cur):
    # If previous and current strings are the same, no action take
    if pre == cur:
        return pre

    # Split two strings to list
    l_pre = pre.split()
    l_cur = cur.split()

    # If previous string length is shorter than the current string     length, then swap two lists
    if len(l_pre) < len(l_cur):
        l_pre, l_cur = l_cur, l_pre

    found = False


    for j, w_cur in enumerate(l_cur):
        for i, w_pre in enumerate(l_pre):
            if w_pre == w_cur:
                found = True
                return ' '.join(l_cur[j:] + l_cur[:j] + l_pre[:i] + l_pre[(i + 1):])


    if not found:
        return ' '.join(l_cur[1:] + [l_cur[0]] + l_pre)

Just cannot get it right. What do I missing? Thanks a lot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清秋悲枫 2024-12-22 10:16:01
def read_graph(lines):
    g = {}
    for line in lines:
        words = line.split()
        if words[1] == '.':
            words = words[:1]
        g[words[0]] = words[1:]
    return g

def dump_graph(g):
    out = []
    def dump(key):
        for k in g[key]:
            dump(k)
        if key not in out:
            out.append(key)
    for k in g:
        dump(k)
    return out

用法:

>>> data = """Civic        Honda Car
... Honda        Manufacturer
... VW           Manufacturer
... Manufacturer .
... Car          .
... Beetle       VW Car
... """
>>> g = read_graph(data.splitlines())
>>> g
{'VW': ['Manufacturer'], 'Civic': ['Honda', 'Car'], 'Car': [],
'Honda': ['Manufacturer'], 'Beetle': ['VW', 'Car'], 'Manufacturer': []}
>>> dump_graph(g)
['Manufacturer', 'VW', 'Honda', 'Car', 'Civic', 'Beetle']
>>>

结果列表中的每个单词都位于其所有“定义”单词之后。

def read_graph(lines):
    g = {}
    for line in lines:
        words = line.split()
        if words[1] == '.':
            words = words[:1]
        g[words[0]] = words[1:]
    return g

def dump_graph(g):
    out = []
    def dump(key):
        for k in g[key]:
            dump(k)
        if key not in out:
            out.append(key)
    for k in g:
        dump(k)
    return out

Usage:

>>> data = """Civic        Honda Car
... Honda        Manufacturer
... VW           Manufacturer
... Manufacturer .
... Car          .
... Beetle       VW Car
... """
>>> g = read_graph(data.splitlines())
>>> g
{'VW': ['Manufacturer'], 'Civic': ['Honda', 'Car'], 'Car': [],
'Honda': ['Manufacturer'], 'Beetle': ['VW', 'Car'], 'Manufacturer': []}
>>> dump_graph(g)
['Manufacturer', 'VW', 'Honda', 'Car', 'Civic', 'Beetle']
>>>

Every word in the resulting list comes after all its "definition" words.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文