有没有一种方法可以按顺序将列表中的数字相加和相减



我正在尝试对列表中的每个数字进行加减运算,如1-1/3+1/5-1/7+1/9。如果你继续这样做,然后把答案乘以4,你就得到了π的近似值。

我有一个名为odd的奇数列表,但我在添加和减法时遇到了问题,如上面所示

我今天刚开始用python编码,所以这可能是一个简单的错误,但我在网上找不到任何关于它的信息

谢谢,Adam

import time
start_time = time.time()

EVEN = []
ODD = []
y = int(1.e2)
x = range(y)
#-----------------------------------------------------------------------------------------
for i in x:
if i%2 == 0:  
print(i)
EVEN.append(i)
else:
print(i)
ODD.append(i)
oc = len(ODD)
ec = len(EVEN)
print("")
print(str(oc) + " " + "Odds Found!")
print(str(ec) + " " + "Evens Found!")
print("--- %s seconds to compute ---" % "{:.2f}".format(((time.time() - start_time))))
time.sleep(3)    #START OF PROBLEM
for i in ODD:
fract = 1/ODD[i]-1/ODD[i+1]
sfract = fract + 1/ODD[i+2]
print(fract)
print(sfract)

您的问题是因为这个循环

for i in ODD:

对列表中的元素进行迭代(对于每个循环(。这就是为什么ODD[i]会导致索引错误,或者会计算出你感兴趣的以外的东西。你应该只使用变量i.

flag = True
for i in ODD:
if flag:
fract += 1 / i
else:
fract -= 1/ i
flag = not flag

此外,由于您使用Python编写,我建议您使用列表理解:

EVEN = [i for i in x if i % 2 == 0]
ODD = [i for i in x if i % 2 == 1]

在这个程序中绝对不需要使用任何列表。

arbitrary_number = 1000
sign = 1
total = 0
for n in range(1, arbitrary_number, 2):
total += sign * 1.0 / n
sign = -sign
print(4*total)

我写这篇文章的目的是让每一步都清晰明了。有更简单的方法可以用更少的代码来写这篇文章。请记住,Python是简单的。通常有一种清晰的方法来提出解决方案,但一定要尝试进行实验。

number = 0 #initialize a number. This number will be your approximation so set it to zero.
count = 0 #set a count to check for even or odd [from the formula] (-1)^n
for num in range(1,100,2): #skip even values.
"""
The way range works in this case is that you start with 1, end at 100 or an arbitrary 
number of your choice and you add two every time you increment. 
For each number in this range, do stuff.
"""
if count%2 == 0: #if the count is even add the value
number += 1/num #example add 1, 1/5, 1/9... from number
count += 1 #in order to increment count
else: #when count is odd subtract
number -= 1/num  #example subtract 1/3, 1/7, 1/11... from number
count += 1 #increment count by one
number = number*4 #multiply by 4 to get your approximation.

希望这能有所帮助,欢迎使用Python!

让我们检查for循环:

for i in ODD:
fract = 1/ODD[i]-1/ODD[i+1]
sfract = fract + 1/ODD[i+2]
print(fract)
print(sfract)

由于您声明fract&在循环内的sfract,它们不计算和,而分别只计算和的两项和三项。如果在循环之外初始化变量,它们的作用域将允许它们累积值。

对于您正在执行的操作,我将对这些变量使用numpy.float来防止溢出。

如果需要在列表中按顺序加减,可以使用Python切片操作创建2个具有奇数和偶数索引的列表。

# Example list
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# [1, 3, 5, 7, 9]
add_list = lst[0::2]
# [2, 4, 6, 8]
subtract_list = lst[1::2]
# Now you can add all the even positions and subtract all the odd
answer = sum(add_list) - sum(subtract_list) # Same as 1-2+3-4+5-6+7-8+9

最新更新