JGrazza
JGrazza

Reputation: 75

python geometric sequence

I'm trying to do a problem in my book but I have no idea how. The question is, Write function geometric() that takes a list of integers as input and returns True if the integers in the list form a geometric sequence. A sequence a0,a1,a2,a3,a4,...,an-2,an-1 is a geometric sequence if the ratios a1/a0,a2/a1,a3/a2,a4/a3,...,an-1/an-2 are all equal.

def geometric(l):
for i in l:
    if i*1==i*0:
        return True
else:
    return False

I honestly have no idea how to start this and I'm completely drawing a blank. Any help would be appreciated.

Thanks!

For example:

geometric([2,4,8,16,32,64,128,256])
>>> True

geometric([2,4,6,8])`
>>> False

Upvotes: 1

Views: 7765

Answers (4)

Blckknght
Blckknght

Reputation: 104712

Here's my solution. It's essentially the same as pyrospade's itertools code, but with the generators disassembled. As a bonus, I can stick to purely integer math by avoid doing any division (which might, in theory, lead to floating point rounding issues):

def geometric(iterable):
    it = iter(iterable)
    try:
        a = next(it)
        b = next(it)
        if a == 0 or b == 0:
            return False
        c = next(it)
        while True:
            if a*c != b*b: # <=> a/b != b/c, but uses only int values
                return False
            a, b, c = b, c, next(it)
    except StopIteration:
        return True

Some test results:

>>> geometric([2,4,8,16,32])
True
>>> geometric([2,4,6,8,10])
False
>>> geometric([3,6,12,24])
True
>>> geometric(range(1, 1000000000)) # only iterates up to 3 before exiting
False
>>> geometric(1000**n for n in range(1000)) # very big numbers are supported
True
>>> geometric([0,0,0]) # this one will probably break every other code
False

Upvotes: 1

Ric
Ric

Reputation: 8805

Like this

def is_geometric(l):
    if len(l) <= 1: # Edge case for small lists
        return True
    ratio = l[1]/float(l[0]) # Calculate ratio
    for i in range(1, len(l)): # Check that all remaining have the same ratio
        if l[i]/float(l[i-1]) != ratio: # Return False if not
            return False
    return True # Return True if all did

And for the more adventurous

def is_geometric(l):
    if len(l) <= 1:
        return True
    r = l[1]/float(l[0])
    # Check if all the following ratios for each
    # element divided the previous are equal to r
    # Note that i is 0 to n-1 while e is l[1] to l[n-1]
    return all(True if e/float(l[i]) == r else False for (i, e) in enumerate(l[1:]))

Upvotes: 0

pyrospade
pyrospade

Reputation: 8078

This should efficiently handle all iterable objects.

from itertools import izip, islice, tee

def geometric(obj):
    obj1, obj2 = tee(obj)
    it1, it2 = tee(float(x) / y for x, y in izip(obj1, islice(obj2, 1, None)))
    return all(x == y for x, y in izip(it1, islice(it2, 1, None)))

assert geometric([2,4,8,16,32,64,128,256])
assert not geometric([2,4,6,8])

Check out itertools - http://docs.python.org/2/library/itertools.html

Upvotes: 3

AI Generated Response
AI Generated Response

Reputation: 8835

One easy method would be like this:

def is_geometric(a):
    r = a[1]/float(a[0])
    return all(a[i]/float(a[i-1]) == r for i in xrange(2,len(a)))

Basically, it calculates the ratio between the first two, and uses all to determine if all members of the generator are true. Each member of the generator is a boolean value representing whether the ratio between two numbers is equal to the ratio between the first two numbers.

Upvotes: 1

Related Questions