-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
  • 176,452
  • 29
  • 245
  • 321
  • it starts with a very large number so using xrange gives me the error OverflowError: Python int too large to convert to C long – Padraic Cunningham Oct 11 '13 at 16:59
  • 1
    This does not sound like an effective way to compute GCDs. Why not use the Euclidean algorithm? – user2357112 Oct 11 '13 at 17:05
  • @MartijnPieters, the question is not about the error, it is asking how to create a generator that counts backwards from n, i have coded a generator that increments without any error, I just wondered if there was a way to do it in reverse. – Padraic Cunningham Oct 11 '13 at 17:09
  • @user2357112, You are correct, it was just a thought I had and wondered if it were possible, it is for my own curiosity more than anything. – Padraic Cunningham Oct 11 '13 at 17:11
  • @PadraicCunningham: that post gives you a generic generator that will count down. Generators *only go forward* but forward can mean producing numbers in decreasing order. – Martijn Pieters Oct 11 '13 at 17:11
  • @PadraicCunningham: Why not show us your code for your forward generator? – Martijn Pieters Oct 11 '13 at 17:12
  • @PadraicCunningham: and using `i = end`, `while i > -1:` and `i -= 1` is not an obvious adjustment? – Martijn Pieters Oct 11 '13 at 17:26
  • You can write a generator and are not able to use subtraction instead of addition? Truly, this world is full of wonders. – Matthias Oct 11 '13 at 17:34

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,498
  • 23
  • 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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
  • 62,056
  • 18
  • 131
  • 204