下面是我写的代码,它只检查第一个和最后一个模式,而不是中间。 任何帮助深表感谢。
def arith_geo(list_n):
if len(list_n) == 0:
return 0
for n in range(len(list_n) - 1):
if (list_n[n + 1] - list_n[n]) == (list_n[n-1] - list_n[n-2]):
return 'Arithmetic'
elif (list_n[n + 1] / list_n[n]) == (list_n[n -1 ] / list_n[n - 2]):
return 'Geometric'
else:
return -1
print(arith_geo([1, 2, 3, 8, 5, 6]))
答案 0 :(得分:0)
1)对长度为0,1,2(长度为2的序列有效AP或GP?)进行特殊处理
2)制作Arith_Counter
和Geom_Counter
变量。
3)为范围n
1..length-2
创建循环
4)每一步。
check if AP property valid -
if yes, increment Arith_Counter
check if GP property valid
if yes, increment Geom_Counter.
5)最后检查
Arith_Counter = length - 2
or
Geom_Counter = length - 2
(or both)
这是一种简单的方法,无需提前退货(您可以在每一步后添加检查计数器)
答案 1 :(得分:0)
感谢@MBo和@Jeremy Kahan,你的回答是很棒的指令,我和他们设法解决了这个问题。 这就是我所做的:
def arith_geo(list_n):
if len(list_n) == 0:
return 0
diff = list_n[1] - list_n[0]
div = list_n[1] / list_n[0]
for num in range(1, len(list_n)):
if list_n[num] - list_n[num - 1] == diff:
counter = 'Arithmetic'
elif list_n[num] / list_n[num-1] == div:
counter = 'Geometric'
else:
counter = -1
break
return counter
print(arith_geo([2,4,8,16]))
print(arith_geo([1,2,3,4]))
print(arith_geo([1,2,8,3]))
答案 2 :(得分:0)
使用all
内置函数和顺序消除可能的状态,它可以非常简单地实现:
def arith_geo(list_n):
if len(list_n) < 2:
return "Not a progression - the list is too short"
# ---------------------------------------------
states = ['Arithmetic', 'Geometric'] # possible states of list_n
b1, b2 = list_n[:2]
adj_elements = list(zip(list_n[1:], list_n[2:]))
# ---------------------------------------------
# arithmetric part:
# ---------------------------------------------
if not all(y - x == b2 - b1 for x,y in adj_elements):
states.remove('Arithmetic')
# ---------------------------------------------
# geometric part:
# ---------------------------------------------
# according to the definition of geometric progression:
# b1 != 0
# q != 0 <=> b2 != 0
# ---------------------------------------------
if b1 * b2 == 0 or not all(y / x == b2 / b1 for x,y in adj_elements):
states.remove('Geometric')
# ---------------------------------------------
state_message = {0:"Neither arithmetic nor geometric",
2:"Both arithmetic and geometric",
1:(states+[''])[0]}
return state_message[len(states)]
结果:
print(arith_geo([])) # Not a progression - the list is too short
print(arith_geo([0])) # Not a progression - the list is too short
print(arith_geo([1, 2])) # Both arithmetic and geometric
print(arith_geo([7, 7])) # Both arithmetic and geometric
print(arith_geo([7, 7, 7])) # Both arithmetic and geometric
print(arith_geo([0, 0])) # Arithmetic
print(arith_geo([0, 1])) # Arithmetic
print(arith_geo([1, 0])) # Arithmetic
print(arith_geo([0, 2, 4])) # Arithmetic
print(arith_geo([7, 5, 3])) # Arithmetic
print(arith_geo([1, 2, 4])) # Geometric
print(arith_geo([1, -0.5, 0.25])) # Geometric
print(arith_geo([0, 2, 3, 8])) # Neither arithmetic nor geometric
print(arith_geo([1, 2, 3, 8])) # Neither arithmetic nor geometric
请注意,根据几何级数的定义,该函数可区分对[0, 0]
和[7, 7]
,以及[0, 1]
和[1, 2]
。