loading...

Daily Challenge #233 - Get Planet Name by ID

thepracticaldev profile image dev.to staff ・1 min read

The function below is not returning the correct values. Can you figure out why?

def get_planet_name(id):
    # This doesn't work; Fix it!
    name=""
    switch id:
        case 1: name = "Mercury"
        case 2: name = "Venus"
        case 3: name = "Earth"
        case 4: name = "Mars"
        case 5: name = "Jupiter"
        case 6: name = "Saturn"
        case 7: name = "Uranus"  
        case 8: name = "Neptune"
    return name

get_planet_name(3) # Should return "Earth"

Good luck!


This challenge comes from jhoffner on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

pic
Editor guide
 

switch statements don't exist in Python like they do in some other languages. We can use a dictionary instead:

def get_planet_name(id):
    switcher = {
        1: "Mercury",
        2: "Venus",
        3: "Earth",
        4: "Mars",
        5: "Jupiter",
        6: "Saturn",
        7: "Uranus",
        8: "Neptune"
    }
    return switcher.get(id, "Invalid Planet Index")
 

I'm gonna do the traditional way:

def get_planet_name_by_id(id):
    if id == 1:
        return "Mercury"
    elif id == 2:
        return "Venus"
    elif id == 3:
        return "Earth"
    elif id == 4:
        return "Mars"
    elif id == 5:
        return "Jupiter"
    elif id == 6:
        return "Saturn"
    elif id == 7:
        return "Uranus"
    elif id == 8:
        return "Neptune"
    return "Planet Index doesn't exist"
 

this is the correct answer (: Python intentionally shunned the switch statement because it's easy to make mistakes, especially with languages which allow fall-through (:

 

Haskell

getPlanetName :: Int -> Maybe String
getPlanetName i =
  case i of
    1 -> Just "Mercury"
    2 -> Just "Venus"
    3 -> Just "Earth"
    4 -> Just "Mars"
    5 -> Just "Jupiter"
    6 -> Just "Saturn"
    7 -> Just "Uranus"
    8 -> Just "Neptune"
    otherwise -> Nothing
 

There is no switch statement in Python (which this appears to be).

I think the best replacement would be to use a dictionary and ideally use a try/except to do something if the index is out of range:

planets = {1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars', 5: 'Jupiter', 6: 'Saturn', 7: 'Uranus', 8: 'Neptune'}

try:
    print(planets[x])
except KeyError:
    print("Planet Index does not exist")
 

Because it's Python.

My solution :

<?php

function get_planet_name($id)
{
  $name = '';
  switch ($id) {
    case 1:
      $name = "Mercury";
      break;
    case 2:
      $name = "Venus";
      break;
    case 3:
      $name = "Earth";
      break;
    case 4:
      $name = "Mars";
      break;
    case 5:
      $name = "Jupiter";
      break;
    case 6:
      $name = "Saturn";
      break;
    case 7:
      $name = "Uranus";
      break;
    case 8:
      $name = "Neptune";
      break;
  }
  return $name;
}

echo get_planet_name(3);

Or another one :

package main

import (
    "fmt"
)

func main() {
    result := get_planet_name(3)
    fmt.Println(result)
}

func get_planet_name(id int) string {
    name := ""
    switch id {
    case 1:
        name = "Mercury"
    case 2:
        name = "Venus"
    case 3:
        name = "Earth"
    case 4:
        name = "Mars"
    case 5:
        name = "Jupiter"
    case 6:
        name = "Saturn"
    case 7:
        name = "Uranus"
    case 8:
        name = "Neptune"
    }
    return name
}
 

I have two answers, first one assumes this is python, second assumes its pseudo-code

Python Answer

Python has no concept of switch statements like alot of other languages do. Could implement something similar with a dict.

planets = {
    1: "Mercury",
    2: "Venus",
    3: "Earth",
    4: "Mars",
    5: "Jupiter",
    6: "Saturn",
    7: "Uranus",
    8: "Neptune"
}

def get_planet_name(id):
    return planets.get(id, "")

print("Planet Name: ", get_planet_name(3))

Should give the desired result

Pseudo-Code Answer

Most languages that have switch statements, expect an explicit break inside of each case statement. Otherwise, when the first true case is found, ALL following case statements will execute ( I know PHP does this if you don't have a break in your case statement. )

Also, instead of initializing the variable at the beginning and returning it at the end, you could just have each case return the string.

This switch also has no default case, which could be used to just return the empty string, in the case of an invalid id being given.

 

Here is what I came up with:

I also tested it, the output is 100% correct

 
def get_planet_name(id):
    planets = [ 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto' ]
    return planets[id - 1]
 

No return or break statements, but yes, Python Dicts were the solution to this.