Search code examples
pythonpython-3.xnumpyloopsnested-loops

How to write efficient loops in Python and solve error: "ValueError: operands could not be broadcast together with shapes (6,) (4,)"?


I'm trying to avoid loops as much as possible in Python because I have been told that code runs more efficiently when there are fewer loops. For the same reason, I'm also trying to use "zip" instead of nested loops for dealing with more than one iterator.

  1. Is this advice correct?
  2. I have tried using the advice but can't get past this error when trying to run the code below. I have probably done something silly but cant figure it out. Could anyone please point me in the right direction?
ValueError: operands could not be broadcast together with shapes (6,) (4,)
import numpy as np
import itertools

# For each value in d and e, I want to loop through all a and b.

d = np.array([1, 2, 3, 4]) 
e = np.array([1000, 2000, 3000, 4000])

a = np.array([10.0e+2, 20.0e+2, 30.0e+2, 40.0e+2, 50.0e+2, 60.0e+2])
b = np.array([1.0e-1, 2.0e-1, 3.0e-1, 4.0e-1, 5.0e-1, 6.0e-1])

c = np.zeros(6)
for (j, k) in zip(d, e):
    c = ((b * (25.0 - a))/(8*e)) + d

Solution

  • You are multiplying by e and adding b. Did you mean to use k and j accordingly instead?

    for (j, k) in zip(d, e):
        c = ((b * (25.0 - a))/(8*k)) + j