+ 1
Where is the Parentheses error
points = [ (12, 55), (880, 123), (64, 64), (190, 1024), (77, 33), (42, 11), (0, 90) ] distance = list(range(len(points))) z = 0 for (x,y) in points: distance[z] = math.sqrt((x**2) + (y**2)) z += 1 print(min(distance))
6 Réponses
+ 6
You can avoid the math library, by expressing square as the power to the 1/2.
In Python we don't really need to initialize an array with a fixed size, like in C. We can build the list dynamically. The most pythonic way is writing a list comprehension, which already contains creating the list and adding all the elements:
distance = [(x**2 + y**2)**0.5 for x, y in points]
+ 5
The code you provided calculates the Euclidean distance between each point in a list and the origin (0, 0) and outputs the minimum distance.
I don't see any issues with the parentheses in this code. However, there is a missing import statement for the `math` module, which is used to calculate the square root. You should add the following line at the beginning of your code:
```
import math
```
Here's the updated code with the import statement added:
```
import math
points = [
(12, 55),
(880, 123),
(64, 64),
(190, 1024),
(77, 33),
(42, 11),
(0, 90)
]
distance = list(range(len(points)))
z = 0
for (x, y) in points:
distance[z] = math.sqrt((x**2) + (y**2))
z += 1
print(min(distance))
```
This code should run without any issues and output the minimum distance.
+ 5
tamaslud Since all list items will be overwritten in the loop, the initial value is irrelevant. In fact, there's no need to initialize.
Good point on enumerate.
+ 5
TENGRANN SAN You don't need to initialize the list, nor refer to each individual index, or even check its length. Read about list method "append".
+ 5
the list comprehension mentioned by Tibor Santa is a good idea. instead of the formula that is currently used, we can also use the *math.dist()* mehod that was added in python 3.8:
from math import dist
print(min([dist((0,0), point) for point in points]))
[edited]:
or using a generator expression:
from math import dist
print(min(dist((0, 0), point) for point in points))
+ 4
distance should be initialized with zeros , instead 0,1,2,3 ...
distance = len(points)*[0]
if index is used in loop, better do it with enumerate:
for z, (x,y) in enumerate (points):
distance[z] = math.sqrt((x**2) + (y**2))