簡體   English   中英

有沒有辦法按順序從列表中添加和減去數字?

[英]Is there a way to add and subtract numbers from a list sequentially?

我正在嘗試添加和減去列表中的每個數字,例如 1 - 1/3 + 1/5 - 1/7 + 1/9。 如果你繼續這樣做,然后將答案乘以 4,你就會得到 pi 的近似值。

我有一個名為 ODD 的奇數列表,但我在添加和減去如上所示時遇到問題

我今天剛開始用 python 編碼,所以這可能是一個簡單的錯誤,但我在網上找不到任何關於它的信息

謝謝,亞當

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)

因為你聲明fractsfract內循環,不計算總和,但只有兩個和三個總和的條款,分別。 如果在循環外初始化變量,它們的作用域將允許它們累積值。

對於你在做什么,我會使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM