繁体   English   中英

Python中的算术或几何序列

[英]arithmetic or geometric sequence in python

您知道我们如何用Python编写代码,其中包括一个带有列表的函数,并找出它是算术还是几何? 我写了一个代码,但是它只是布尔值,没有说它的算术或几何形状,并且还有额外的输出。

L=[int(x) for x in input("please enter a list:").split()]

def Arithemetic(L):
  i=1
  if(L[0]+L[i]==L[i+1]):
    return True
  i+=1

def Geometric(L):
  i=1
  if(L[0]*L[i]==L[i+1]):
    return True
  i+=1

def IsArithemeticOrGeometric(L):
  if(Arithemetic(L)):
    print(Arithemetic(L))
  elif(Geometric(L)):
    print(Geometric(L))

print(IsArithemeticOrGeometric(L))

这里有一些错误,我会尽力一一解决。

要求清单

L=[int(x) for x in input("please enter a list:").split()]

当获取非数字类型的数据时,将抛出ValueError 这也会将任何float舍入为int

问题一可以通过用while循环和try-catch block其包围来解决

while True:
    try:
        L=[int(x) for x in input("please enter a list:").split()]
        break
    except ValueError:
        pass

通过将int(x)更改为float(x)可以轻松解决int的问题

使用float ,请注意浮点数的性质

检查算术和几何

在您的解决方案中, i永远不会递增,因此这只会检查前两个值。 借用@ dex-ter的评论,您可以将其更改为

def is_arithmetic(l):
    return all((i - j) == (j - k) for i, j, k in zip(l[:-2], l[1:-1], l[2:]))

有关其工作原理的解释,请检查列表拼接zip的背景

对于is_geometric您可以轻松调整此解决方案。

这也是一个很好的例子unittests会已将此错误清除

assert is_geometric((1,2))
assert is_geometric((1,2, 4))
assert is_geometric((1,2, 4, 8))
assert not is_geometric((1,2, 4, 9))
try:
    is_geometric((1, 2, 'a'))
    raise AssertionError('should throw TypeError')
except TypeError:
    pass

结果

您的结果仅显示True或False是因为这就是您告诉程序执行的操作。 您的IsArithemeticOrGeometric()没有return语句,因此它始终返回None ,它不会被打印。 ,因此所有输出均来自print(Arithemetic(L))print(Geometric(L))

这里可能的解决方案是这样的:

def is_arithmetic_or_geometric(l):
    if is_arithmetic(l):
        return 'arithmetic'
    if is_geometric(l):
        return 'geometric'

print(is_arithmetic_or_geometric(L))

暂无
暂无

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

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