简体   繁体   中英

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. If you keep on doing this and then multiply the answer by 4 you get an aproximation of pi.

I have a list of odd numbers called ODD but im having trouble adding and subtracing as shown above

I literally just started coding in python today so this could be a simple mistake but I can't find anything online about it

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.

    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:

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. 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!

Let's examine the for loop:

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. 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.

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.

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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