相关疑难解决方法(0)

检测未知来源的时间段

如何检测无限序列中的重复数字?我试过Floyd&Brent检测算法,但什么都没有......我有一个生成器,产生0到9(含)的数字,我必须认识到它的一个时期.

示例测试用例:

import itertools

# of course this is a fake one just to offer an example
def source():
    return itertools.cycle((1, 0, 1, 4, 8, 2, 1, 3, 3, 1))

>>> gen = source()
>>> period(gen)
(1, 0, 1, 4, 8, 2, 1, 3, 3, 1)
Run Code Online (Sandbox Code Playgroud)

python algorithm math floyd-cycle-finding

7
推荐指数
1
解决办法
4844
查看次数

功能python - 为什么这些生成器中只有一个需要list()才能工作?

在从元组向量(残差,模数)计算中国剩余定理时,以下代码失败:

c = ((1,5),(3,7),(11,13),(19,23))

def crt(c):
        residues, moduli = zip(*c)
        N = product(moduli)
        complements = (N/ni for ni in moduli)
        scaled_residues = (product(pair) for pair in zip(residues,complements))
        inverses = (modular_inverse(*pair) for pair in zip(complements,moduli))
        si = (product(u) for u in zip(scaled_residues,inverses))
        result = sum(si) % N
        return result
Run Code Online (Sandbox Code Playgroud)

将结果赋予0(我猜生成的iterables为空).但以下代码完美运行:

def crt(c):
        residues, moduli = zip(*c)
        N = product(moduli)
        complements = list((N/ni for ni in moduli)) # <-- listed
        scaled_residues = (product(pair) for pair in zip(residues,complements))
        inverses = (modular_inverse(*pair) …
Run Code Online (Sandbox Code Playgroud)

python functional-programming chinese-remainder-theorem

5
推荐指数
1
解决办法
254
查看次数

Python3的内置zip功能问题

Python 3.4.2 (default, Oct  8 2014, 13:44:52) 
[GCC 4.9.1 20140903 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> gen = (x for x in range(10)) ## Need to wrap range into ()'s to create a generator, next(range(10)) is invalid
>>> list(zip(gen, [1,2,3])) ## zip will "eat up" the number 3
[(0, 1), (1, 2), (2, 3)]
>>> next(gen) ## Here i need next to return 3
4
>>> 
Run Code Online (Sandbox Code Playgroud)

问题是我在拉链电话后丢失了一个值.如果gen不是纯粹的代码,这将是一个更大的问题.

我不知道是否可以创建一个行为类似的函数,如果zip函数的一个参数只是一个生成器,其余的是"正常"迭代器,其中所有的值都是已知,并存储在内存中.如果是这种情况,您可以最后检查发电机.

基本上我想知道的是,如果python标准库中有任何函数,就像我在这种情况下需要的那样.

当然,在某些情况下,人们可以做类似的事情

xs …
Run Code Online (Sandbox Code Playgroud)

python zip

5
推荐指数
1
解决办法
910
查看次数