-5

I am trying to find a highest common factor and want to start at the upper end, How can I create a generator in python that starts at n and decrements by -1?

def drange(end):
   i = 1
   while  i > end:
      yield i
      i += 1
4

3 回答 3

1

您的发电机很容易适应:

def drange(end):
    i = end
    while i > 0:
        yield i
        i -= 1

这从 1 开始倒计时end

>>> def drange(end):
...     i = end
...     while i > 0:
...         yield i
...         i -= 1
... 
>>> for n in drange(3):
...     print n
... 
3
2
1

如果要倒数到 0,请测试i > -1.

于 2013-10-11T17:27:27.273 回答
1

在 Python 3 中,您可以使用

reversed(range(1000000000000000000000))

这是有效的,因为范围对象有一个__reversed__方法。

Python 2 的 xrange 不能处理那么大的数字,所以你需要一个生成器函数:

def downrange(n):
    while n > 0:
        yield n
        n -= 1

for i in downrange(n):
    print i
于 2013-10-11T17:09:39.120 回答
0

我能想到的最简单的答案是使用itertools.count

>>> from itertools import count
>>> p = count(10**10,-1)
>>> next(p) # Gives you the reverse decremented generator
于 2013-10-11T17:14:20.353 回答