Open In Colab

1.4. (Exercises) Simple Data Structures#

1.4.1. Warm-up: Lists#

  1. Write out the following code without using a list comprehension:
    plus_thirteen = [number + 13 for number in range(1,11)]

  2. Use list comprehension or loops to create a list of first twenty cubes (i.e., x^3 from 0-19)

# Question 1
plus_thirteen = []
for ______ in range(1,11):
  plus_thirteen._______(________)
print(plus_thirteen)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[1], line 4
      2 plus_thirteen = []
      3 for ______ in range(1,11):
----> 4   plus_thirteen._______(________)
      5 print(plus_thirteen)

AttributeError: 'list' object has no attribute '_______'
#@title ##### Your answer should look like this
plus_thirteen = []
for number in range(1,11):
  plus_thirteen.append(number+13)
print(plus_thirteen)
# Question 2
[_____________________________________ range(20)]
#@title ##### Your answer should look like this
[number**3 for number in range(20)]

1.4.2. Main Exercise: Creating and Manipulating Simple Data Structures#

Learning Goals

This assignment will verify that you have the following skills:

  • Create lists and dictionaries

  • Iterate through lists, tuples, and dictionaries

  • Index sequences (e.g. lists and tuples)

  • Define functions

  • Use optional keyword arguments in functions

  • Define classes

  • Add a custom method to a class

NASA_planets_edu.jpg

1.4.2.1. Part I: Lists and Loops#

Q1. Create a list with the names of every planet in the solar system (in order)
Q2. Have Python tell you how many planets there are by examining your list
Q3. Use slicing to display the first four planets (the rocky planets)
Q4. Iterate through your planets and print the planet name only if it has an s at the end

Q1. Create a list with the names of every planet in the solar system (in order)

# Create your list here
planetlist = ['mercury','_',__________________________]

Q2. Have Python tell you how many planets there are by examining your list

# Write your code here
# Hint: Use len() function
# Answer: you should get a single number of 8
print(___(______________))

Q3. Use slicing to display the first four planets (the rocky planets)

# Write your code here
____________________[:_]

Q4. Iterate through your planets and print the planet name only if it has an s at the end

# Write your code here
# Hint: Access the final letter of every planet (planet[-1]), print planet name if the letter equals to "s", continue with the loop otherwise.
# Answers:
# venus
# mars
# uranus

for ________________ in ____________:
  if ___________[__]=='s':
    print(__________)
  else:
    ____________

1.4.2.2. Part II: Dictionary#

Q5) Now create a dictionary that maps each planet name to its mass

You can use values from this NASA fact sheet. You can use whatever units you want, but please be consistent.

# Write your code here
#planetdict = {'mercury':______,'venus':_____,'earth':_____,
#              'mars':__xx___,'jupiter':____,'saturn':____,'uranus':_____,'nepturn':___}

Q6) Use your dictionary to look up Earth’s mass

# Write your code here
print(________[___])

Q7) Loop through the data to create and display a list of planets whose mass is greater than \(100 \times 10^{24}\) kg

# Write your code here
# In the parentheses, you will access the names (keys) of each entry in the dictionary.
# You should see this: ['jupiter', 'saturn', 'nepturn']
q7list = []
for key in list(_______.keys()):
  # Now you wil access the values associated with each key-value pair
  if _____________[key]>100:
    q7list.append(___) # the name of each planet
  else:
    _________
print(q7list)

Q8) Now add Pluto to your dictionary

# Write your code here
# You should see this: ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'nepturn', 'pluto']
_____________['pluto'] = ______
print(planetdict.keys())

1.4.2.3. Part III: Functions#

Q9) Write a function to convert from the unit you chose for planetary masses to \(M_{Earth}\), the mass of the Earth

For example, the mass of Jupiter is:

\(M_{Jupiter} \approx 1898\times10^{24}kg \approx 318 M_{Earth}\)

#write function here
# Write your function here
# The function should take in the any planet mass you want (e.g., planetdict['mars']) and divide by the mass of Earth
# (planetdict['earth'])
def convert_mass_Mearth(______=____):
  return _________/planetdict['earth']

#test it works for jupiter (planetdict['jupiter']), the function should output 317.92294807370183
convert_mass_Mearth(____________)

Q10) Now write a single function that can convert from the unit you chose for planetary masses to both \(M_{Earth}\) or \(M_{Jupiter}\) depending on the keyword argument you specify

# Write your function here
def convert_m_Mearthjupiter(______=____,ourplanet='jupiter'):
  return ___________/planetdict[ourplanet]

# Check if your function work: convert Mjupiter to Mearth and Mjupiter,
# You should see 317.923 (Mearth) and 1.0 (Mjupiter)
print(convert_m_Mearthjupiter(planetdict['jupiter'],_____),convert_m_Mearthjupiter(planetdict['jupiter'],______))
# Store the Mjupiter for Q11
Mjupiter = convert_m_Mearthjupiter(planetdict['jupiter'],'jupiter')

Q11) Write a function takes one argument (mass in \(M_{Jupiter}\)) and returns two arguments (mass in \(M_{Earth}\) and mass in the unit you chose [whichever planet you want])

# Write your function here
def mass_conversion_two_arguments(mass,planet=____):
  a = mass/planetdict[_____] # Earth
  b = mass/planetdict[______] # The planet you want to use as a reference
  return a,b
# Check that it works to convert Jupiter's mass to $M_{Earth}$ and to
# the unit you chose (e.g., Mars' planet)
print(mass_conversion_two_arguments(_____,'mars'))
# Bonus: Use the function from Q10 to convert Neptune's mass to $M_{Jupiter}$
# and then the function from Q11 to convert it back to the unit you chose
# Do you get the original value back?

1.4.2.4. Part IV: Classes#

Q12) Write a class planet with two attributes: name and mass

# Write your class here
class planet:
  def __init__(____,inname=____,inmass=____):
    self.name = inname
    self.mass = inmass
# Create a new instance of that class to represent the Earth (mass=5.97)
earth = planet(_______,_____)
# Create a new instance of that class to represent Jupiter (mass=1898)
jupiter = planet(_______,____)
# How to check that you did the right thing?
print(earth._____,earth.____)

Q13) Add a custom method is_light to the class planet that returns True if the planet is strictly lighter than Jupiter, False strictly heavier than Jupiter, and ‘same mass!’ if the planet weighs the same as jupiter

# Change your class here
class planet:
  def __init__(____,inname=____,inmass=____):
    self.name = inname
    self.mass = inmass
  def is_light(____):
    if ___________<planetdict['jupiter']:
      print('True')
    elif ____________>planetdict['jupiter']:
      print('False')
    else:
      print('same mass!')

# Ask Python whether the Earth is lighter than Jupiter, you should see True for this one!
planet(_____,planetdict[_____]).is_light()
# Ask Python whether Jupiter is lighter than itself, you should see same mass! for this one!
planet(_____,planetdict[_____]).is_light()