Home > database >  Finding the maximum x, y and z value in a list of dictionaries
Finding the maximum x, y and z value in a list of dictionaries

Time:09-24

I cannot for the life of me figure out this problem (description listed below) code ive tried so far just returns "none"

import math



def farthest_planet(planets):
    plane = 0
    for planet in planets:
        tempval = math.sqrt(int(planet['x']) ** 2   int(planet['y'] ** 2   int(planet['z']) ** 2))
        plane = tempval
        if tempval > plane:
            return planet
        
         

For each planet, you have the 3-dimensional coordinates of its location. A distance can be calculated using the 3D version of the Pythagorean Theorem. In words it is the square root of the sum of the squares of all 3 coordinates. I For example, if a planet is at x = 1, y = 2 and z = 3, its distance is the square root of 1 4 9. ### Function Name farthest_planet *** Parameters planets: A list of planets. Each planet is a dictionary with keys x, y, and 'ż. The values of these keys are positive floating point values. These values represent the planet's coordinates, with the origin being the center of the star they orbit. ### Return Value The planet from planets that is farthest from the center of the star they orbit. ### Examples farthest_planet([{ 'x': 1, 'y': 2., 'z': 3. }, { 'x': 10., 'y: 20., 'z': 30. }) -> { 'x': 10., 'y': 20., 'z': 30}.

CodePudding user response:

with plane = tempval, you're automatically overwriting the value of plane so they will always equal the same value before you get to the comparison portion of your code.

you want to make the comparison first, then reassign if the value of tempval is greater than plane.

then at the end of all of your comparisons, return plane (so take the return statement out of the for loop altogether).

for...
...
    if tempval > plane:
        plane = tempval
return plane

CodePudding user response:

It doesn't make sense for the code

if tempval > plane:

because you make plane = tempval
Instead, code as following:

if tempval > plane:
    plane = tempval
    rt_planet = planet
return rt_planet

CodePudding user response:

You can use the max function on the list of planets and give it a key function that computes the distance to the star:

planets = [{ 'x': 1, 'y': 2., 'z': 3. }, { 'x': 10., 'y': 20., 'z': 30. }]

max(planets,key=lambda p:sum(c*c for c in map(p.get,('x','y','z'))))

{'x': 10.0, 'y': 20.0, 'z': 30.0}

For distance comparisons, you don't need to apply the square root. The sum of squares will provide the same relative ordering because if a > b, then √a > √b

  • Related