1

I have an array that I would like to perform 2 calculations on.

1) I want to take the largest integer not greater than x for every array value, divide that value by 3, then subtract 2.

2) I then want to sum the array values.

Here is my script:

mass = [1,2,3,4,5]

def Multiply(x):
    return (math.floor(x/3) - 2)

for i in mass: 
    new_mass = Multiply(i)

    print(new_mass)

When I run the script it works as expected. I get:

-2 -2 -1 -1 -1

However, when try to sum the new_mass in a "total" variable I get the following error:

total = sum(new_mass)
print(total)

"TypeError: 'int' object is not iterable"

Can someone please help? Below is the complete code:

mass = [1,2,3,4,5]

def Multiply(x):
    return (math.floor(x/3) - 2)

for i in mass: 
    new_mass = Multiply(i)

    print(new_mass)

total = sum(new_mass)
print(total)

2 Answers 2

4

new_mass is an integer that gets overwritten with each loop through i.

define your total at the start and sum it as you loop through, then print.

something like:

mass = [1,2,3,4,5]
total = 0 

def Multiply(x):
    return (math.floor(x/3) - 2)

for i in mass: 
    new_mass = Multiply(i)
    total = total + new_mass
    print(new_mass)

print(total)

If you want to write the calculation back to the array it would look something like this: (untested)

mass = [1,2,3,4,5]

def Multiply(x):
    return (math.floor(x/3) - 2)

for i in mass: 
    i = Multiply(i)
    print(i)

print(sum(mass))
Sign up to request clarification or add additional context in comments.

Comments

0

Is this what you want?

import numpy as np
mass = np.array([1,2,3,4,5])
newmass = mass / 3 - 2
np.floor(newmass).sum()

This returns -7.0.

https://repl.it/@shinokada/stackoverflow001

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.