简体   繁体   English

有没有办法按顺序从列表中添加和减去数字?

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

I'm trying to add and subtract each number in a list like this 1 - 1/3 + 1/5 - 1/7 + 1/9.我正在尝试添加和减去列表中的每个数字,例如 1 - 1/3 + 1/5 - 1/7 + 1/9。 If you keep on doing this and then multiply the answer by 4 you get an aproximation of pi.如果你继续这样做,然后将答案乘以 4,你就会得到 pi 的近似值。

I have a list of odd numbers called ODD but im having trouble adding and subtracing as shown above我有一个名为 ODD 的奇数列表,但我在添加和减去如上所示时遇到问题

I literally just started coding in python today so this could be a simple mistake but I can't find anything online about it我今天刚开始用 python 编码,所以这可能是一个简单的错误,但我在网上找不到任何关于它的信息

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


Your problem is because this loop你的问题是因为这个循环

for i in ODD:

iterates over elements in a list (for each loop).迭代列表中的元素(对于每个循环)。 This is why ODD[i] would result in an index error or would calculate something else than what you're interested in. You should just use the variable i.这就是为什么 ODD[i] 会导致索引错误或会计算出您感兴趣的其他内容。您应该只使用变量 i。

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

Besides, since you write in Python I'd recommend using list comprehension:此外,由于您是用 Python 编写的,我建议您使用列表理解:

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

There is absolutely no need to use any lists in this program.在这个程序中绝对不需要使用任何列表。

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)

I wrote this out with the intention of having each step be clear.我写这个是为了让每一步都清楚。 There are easier ways to write this with less code.有更简单的方法可以用更少的代码来编写它。 Remember that Python is made to be simple.请记住,Python 是为了简单而设计的。 There is usually one clear way to come up with a solution, but always try experimenting.通常有一种明确的方法可以提出解决方案,但始终尝试尝试。

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.

Hope this helps and welcome to Python!希望这会有所帮助并欢迎使用 Python!

Let's examine the for loop:让我们检查一下 for 循环:

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

since you declare fract & sfract inside the loop, they do not compute the sum, but only two and three terms of the sum, respectively.因为你声明fractsfract内循环,不计算总和,但只有两个和三个总和的条款,分别。 If you initialize the variables outside of the loop, their scope will allow them to accumulate the values.如果在循环外初始化变量,它们的作用域将允许它们累积值。

For what you are doing, I would use numpy.float for those variables to prevent overflow.对于你在做什么,我会使用numpy.float来防止这些变量溢出。

If you need to add and subtract sequentially in a list, you can use the Python slice operation to create 2 lists with odd and even indexes.如果需要在一个列表中按顺序进行加减运算,可以使用 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