Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise N62 - There is an unnecessary code, Exercise N80 - IndexError #215

Open
Artur-Arstamyan opened this issue Sep 27, 2024 · 1 comment

Comments

@Artur-Arstamyan
Copy link

Artur-Arstamyan commented Sep 27, 2024

Exercise 62 - Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator?
Code

a = np.random.randint(0, 10, (1, 3))
b = np.random.randint(0, 10, (3, 1))
it = np.nditer([a,b,None])

for x,y,z in it: 
    z = x + y

print(it.operands[2])

Unnecessary part

for x,y,z in it: 
    z = x + y

After it = np.nditer([a,b,None]) it.operands[2] already has that value.

Exercise N80
Current code that gives error

r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
R[r] = Z[z]

Output

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Solution - Use tuples

r = tuple(slice(start,stop) for start,stop in zip(R_start,R_stop))
z = tuple(slice(start,stop) for start,stop in zip(Z_start,Z_stop))
@Artur-Arstamyan Artur-Arstamyan changed the title Exercise N62 - There is unnecessary code Exercise N62 - There is an unnecessary code Sep 28, 2024
@Artur-Arstamyan Artur-Arstamyan changed the title Exercise N62 - There is an unnecessary code Exercise N62 - There is an unnecessary code, Exercise N80 - IndexError Sep 28, 2024
@rougier
Copy link
Owner

rougier commented Oct 21, 2024

Thanks.

  • 62 I don't see a reason why operands[2] would hold the result and it doesn't on my machine.
>>> A = np.arange(3).reshape(3,1)
>>> B = np.arange(3).reshape(1,3)
>>> it = np.nditer([A,B,None])
>>> print(it.operands[2])
[[ 4607825790175356065 -4611042647052049243  4603322190547985584]
 [-4611042647052049244  4617283349392834114 -4613744806828471525]
 [ 4603322190547985580 -4613744806828471528  4606153024599475605]]
>>> for x,y,z in it: z[...] = x + y
>>> print(it.operands[2])
[[0 1 2]
 [1 2 3]
 [2 3 4]] 
  • 80 You're right, can you make a PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants