python - 如何在python中实现这个算法?

标签 python algorithm

<分区>

这是某种类型的笛卡尔乘积,它从初始固定长度的整数系列生成,使用符号规定的规则生成附加系列,该符号指示必须添加的附加系列的 n 数量跟随。

例如(^ 产生额外的 1 个系列,* 产生额外的 3 个系列)

1 0^ 1* 1

产生

1 0 2 1
1 0 3 1
1 0 4 1 (we stop here because we have produced 3 additional series)

1 1 1* 1 (we have produced an additional series from the `^` symbol. still have the `*`)

1 1 2 1
1 1 3 1 
1 1 4 1

另一个示例,现在具有更大长度的系列和附加规则。

1 0^ 1* 0^ 1

产生

1 0 2 0 1
1 0 3 0 1
1 0 4 0 1

1 0^ 1* 1 1

1 0 2 1 1 
1 0 3 1 1 
1 0 4 1 1 

1 1 1* 1 1 

1 1 2 1 1 
1 1 3 1 1 
1 1 4 1 1 

我只是觉得无聊,开始在纸上写下这样一整串数字,并且很想知道是否已经有一种算法或实现可以生成这样的整数序列。请注意,系列之间有新的一行,可以生成额外的系列以使其更易于理解。

最佳答案

您可以使用 itertools.product对于一般的笛卡尔积。具体来说,我将分两步实现您的算法:

  1. 将输入字符串(例如 "1 0^ 1* 0^ 1")解析为整数列表的列表;和
  2. 产生列表列表的产品。

一个相对简单的基于生成器的实现,为了清晰起见,带有一个辅助函数,看起来像:

def algorithm(input_):
    # Step 1
    instructions = []
    for s in input_.split():
        try:
            instructions.append([int(s)])
        except ValueError:
            instructions.append(list(values(s)))
    # Step 2
    for prod in itertools.product(*instructions):
        yield prod

def values(s):
    RULES = {'*': 4, '^': 2}
    n = int(s[:-1])
    for x in range(RULES[s[-1]]):
        yield n + x

例如:

>>> print("\n".join(" ".join(map(str, t)) for t in algorithm("1 0^ 1* 1")))
1 0 1 1
1 0 2 1
1 0 3 1
1 0 4 1
1 1 1 1
1 1 2 1
1 1 3 1
1 1 4 1

您将不得不修改它以获得您正在寻找的精确顺序(您似乎有一个运算符,而不是从左到右的优先级)和格式(例如组之间的空格)。

关于python - 如何在python中实现这个算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23709247/

相关文章:

python - 通过列表值迭代有限但任意次数的最Pythonic方法

python - GData Youtube api 慢

python - 运行时错误 : module compiled against API version a but this version of numpy is 9

c++ - 为 Prim 在 c++ 中的实现设计数据结构

ruby - Rabin Karp 在 Ruby 中的实现太慢

python - 将列表字典写入 csv,指定列顺序

python - Marshmallow Parent Schema - 如何在子模式之间共享验证装饰器?

algorithm - 随机搜索算法的复杂性

"pick the number up game"的算法

PHP 更快的素数生成器