繁体   English   中英

python几何序列

[英]python geometric sequence

我正在尝试在书中解决问题,但不知道如何解决。 问题是,写函数geometry()接受一个整数列表作为输入,如果列表中的整数形成一个几何序列,则返回True。 如果比率a1 / a0,a2 / a1,a3 / a2,a4 / a3,...,序列a0,a1,a2,a3,a4,...,an-2,an-1是几何序列。 an-1 / an-2都相等。

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

老实说,我不知道如何开始,现在我完全空白了。 任何帮助,将不胜感激。

谢谢!

例如:

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

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

这应该有效地处理所有可迭代对象。

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])

查看itertools- http: //docs.python.org/2/library/itertools.html

一种简单的方法是这样的:

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)))

基本上,它计算前两个之间的比率,并使用all来确定生成器的所有成员是否为真。 生成器的每个成员都是一个布尔值,表示两个数字之间的比率是否等于前两个数字之间的比率。

这是我的解决方案。 它与pyrospade的itertools代码基本相同,但分解了生成器。 另外,我可以避免进行除法运算(在理论上可能会导致浮点舍入问题),从而坚持纯整数数学:

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

一些测试结果:

>>> 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

像这样

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

对于更具冒险精神的人

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:]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM