-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
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312

3 Answers3

1

In Python 3 you can use

reversed(range(1000000000000000000000))

This works because the range object has a __reversed__ method.

Python 2's xrange can't handle numbers that big, so you'll need a generator function:

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

for i in downrange(n):
    print i
deltab
  • 2,350
  • 21
  • 28
1

Your generator is easily adapted:

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

This counts down from end to 1:

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

If you want to count down to 0, test for i > -1.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
0

The simplest answer I can think of is to use itertools.count

>>> from itertools import count
>>> p = count(10**10,-1)
>>> next(p) # Gives you the reverse decremented generator
Abhijit
  • 59,056
  • 16
  • 119
  • 195