behnam heidary - 5 months ago 10

Python Question

I have a mathematics code in python and need to convert it to java. But I can't understand it:

`#python source`

sum([d**2 for d in (x - y)])

`d`

`x,y`

`for`

`d^2`

`d`

Answer

The actual for loop surrounded by brackets is a list comprehension, which generates a list. This is expressed, in general, as follows:

```
[ expression( <variables> ) for <variables> in <list> ]
```

Which means your variables (here `d`

) will iterate over the values in the given list (here `(x - y)`

). The list returned will contain the value of the expression, evaluated for each value of `d`

.

This way of writing defines the variable after it is used, so it is normal you haven't seen it defined before.

In clear, the code is equivalent to the following:

```
squares = []
for d in (x - y):
squares.append(d**2)
sum(squares)
```

Trivially, sum returns the sum of the list.

Because you say your code is doing maths and you are saying *arrays* rather than *lists*, I will suppose from here on that you mean that `x,y`

are numpy arrays.

In this case, `x - y`

has a meaning: item by item subtraction of the arrays.

Written as a list comprehension, it would look like: `[a - b for a,b in`

`zip`

`(x,y)]`

Hence a python rewrite of that code could be:

```
sum = 0
for a,b in zip(x,y):
sum += (a - b) * (a - b)
```

Or only with numpy functions:

```
numpy.square(x - y).sum()
```

Source (Stackoverflow)

Comments