Homework 1: Python fundamentals#

And using external resources to better undersand code!#

Put your name here


Learning Goals#

Content Goals#

  • Use mathematics in Python

  • Utilize loops to perform repeated operations and to store, access, and manipulate data in one more or lists

  • Utilize variables and lists (and dictionaries) to store and access data

  • Use conditional statements to control code flow.

  • Write functions

  • Create an example code that encapsulte all the above (almost)

Practice Goals#

  • Solve a variety of problems using code

  • Write functions

  • Troubleshoot errors and debug your code as issues arise (you’ll do this all the time in this course!)

Assignment instructions#

Work through the following assignment, making sure to follow all the directions and answer all the questions.

This assignment is due at 11:59 pm on Friday, February 9. It should be uploaded into the “Homework Assignments” submission folder for Homework #1. Submission instructions can be found at the end of the notebook.

Total number of points: 45 (points)

Version check#

Before you begin, make sure your Jupyter kernel is Python 3. There are significant differences between Python 2 and Python 3, and we use Python 3 in this course. The kernel type at the upper-right corner should say “Python 3”, and the following code should show a version of the form: 3.x.y (where “x” and “y” are the sub-version numbers).

If your kernel is Python 2, try selecting Python 3 from the Kernel menu above under the sub-menu “Change kernel”. If that does not work, consult the Teams help channel for assistance.

import sys

Bibliography Block#

Use this block to keep track of resources you used and people you worked with. This doesn’t need any sort of fancy formatting, but is useful for me to understand how you are using external resources, as well as for you for later to find particularly helpful links and the like. Some example entries are below.

  • I worked with Maryam Mirzakhani and Grigori Perelman while completing this assignment.\(^\dagger\)

  • I used the wikipedia page on cohomology to get started with the definitions.

  • I used this stack overflow post to fix some issues with my git repository.

  • I wrote a first draft of my abstract using ChatGPT using the prompt “Write an exceptionally good abstract for a talk by Liz Munch”.

\(\dagger\) Note that you are more than welcome to work with other members of the class while completing the assignment. However, the work and coding done must be your own. In particular, direct copy-paste will not be tolerated. When in doubt, my litmus test for plagarism is, “Explain this code to me and your thought process in getting there”.

Part 1: Fibonacci numbers (14 points)#

Why is it that the number of petals in a flower is often one of the following numbers: 3, 5, 8, 13, 21, 34 or 55? For example, the lily has three petals, buttercups have five, the chicory has 21, the daisy has often 34 or 55 petals, etc. https://thefibonaccisequence.weebly.com/flowers.html

Are these numbers the product of chance? No! They all belong to the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …, where each number is obtained from the sum of the two preceding. The \(n\)th Fibonacci number \(f_n\) can be derived by \(f_n = f_{n-1} + f_{n-2}\). For a long time, it had been noticed that these numbers were important in nature, but only relatively recently did we understand that this is related to efficiency during the growth process of plants.

✅  Question 1.1 (5 Points)#

In this exercise, you are given a numerical sequence that has the form \(1, 1, 2, 3, 5, \ldots\). Your goal is to write a loop that computes 50 terms of the Fibonacci sequence. Store this sequence as a list and then print the entire list all at once..

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074]

Note: If you Google Fibonacci number python code you will likely find something about recursion. You are not allowed to use recursion!. You should be able to write this code using only loops and lists! No functions needed.

# Put your code here

✅  Question 1.2 (5 Points)#

Once you have your list of Fibonacci numbers, use it to calculate the ratios \(R_n = f_{n}/f_{n+1}\) and store it into a new list. At the end print the entire new list all at once.

# Put your code here

✅  Question 1.3 (4 Points)#

What type of loops did you use to write the above programs, looping by value or looping by index?

  • If you used looping by value, can you re-write your code using looping by index? Either do it or explain why not.

  • Instead, if you used looping by index, can you re-write your code using looping by value? Either do it or explain why not.

You must explain your answers.

# Put any code you might need here

Put your explanation here.

Part 2: Carbon dating (12 points)#

Archaeologists use the exponential, radioactive decay of carbon-14 to estimate the death dates of organic material. The stable form of carbon is carbon-12, and the radioactive isotope carbon-14 decays over time into nitrogen-14 and other particles. Carbon is naturally in all living organisms, and the carbon-14 that forms in the upper atmosphere enters into living things as long as they are taking in material (food, air, etc.) that contains carbon.

We can estimated how old a fossil is by comparing the content of carbon-14 in the fossil to an equivalent living sample, through the equation below:

\[ N(t) = N_0 \left(\frac{1}{2}\right)^{t/ \tau} \]

where \(N(t)\) is the amount of carbon-14 as a function of time, \(N_0\) is the base carbon-14 amount at \(t=0\), and \(\tau\) is the “half-life”, which is the time after which half of the original amount of a radioactive substance remains. The half-life is a known physical property of the isotope and cannot be changed by the environment. The half-life of carbon-14 is 5,730 years.

Your goal is to find the time in years for a given target fraction, that is \(\tfrac{N}{N_0}\).

✅  Question 2.1 (4 points)#

Write a function called amount_carbon_14 that takes as inputs the time \(t\) and \(N_0\), and returns \(N(t)\).

IMPORTANT: Make sure that your function is not using any global variable, instead, they should all be passed or initialized in the function.

# Put your code here

✅  Question 2.2 (4 Points)#

Using a while loop to simulate the decay of carbon-14 over time and a time step of 50 years, estimate the time for a target fraction of 21% and print when in years after its death the fossil was found.

# Put your code here

✅  Question 2.3 (4 Points)#

  1. Using what you have done previously, create a function called find_time_fossil that takes as inputs the time step and the target fraction of a fossil, and return the estimation of the associated time.

  2. Using this function, verify that you obtain the same result as before.

IMPORTANT: Make sure that your function is not using any global variable, instead, they should all be passed or initialized in the function.

# Put your code here

Part 3: Finding common divisors (4 points)#

For this question you should write code using the tools you learned so far. The code will find all the integers in the interval from 1 to 12000 that are divisible by both 3 and 14. Store all the numbers that satisfy this criterion into a list and print the entire list.

Hint: The “modulo” operator is denoted by a percent sign % in Python. It returns the remainder when two integers are divided. For example, 5%2 (read: “5 mod 2”) returns a value of 1, because 5 divided by 2 is 2 with the remainder 1. The result of a modulo x%d is always between 0 and d-1. Use the modulo operator to help determine if one integer is divisible by another.

Second Hint: Remember the logical operators and, or and not are available in Python.

# put your code here

Part 4. Dictionaries and everything else (15 points)#

Occasionally during this class you will be expected to learn a new Python concept “on-the-fly”. This is when it becomes important for you to be able to digest Python documentation and do some intelligent Googling. For this part of the assignment, you’re going to see if you can pick up a bit about how another Python data container works, the dictionary.

Dictionaries are like lists in the sense that we have some object (e.g. integer, string, etc.) occupying a position in the dictionary. However, dictionaries differ in that we refer to each element by a key rather than an integer index. For example, in the dictionary example_dict in the cell below, the key string "red" corresponds to the value integer -2, the key string "green" corresponds to the value string "beach_ball". We can include values of different types in the same dictionary, just as we did with lists above.

IMPORTANT: Keys may be of any type, but an element can only be accessed by its specific key. Even though "red" is the first key, example_dict[0] is not a valid way to access it. Also note that dictionaries are written using curly braces {}; lists use square brackets []. The key-value pairs are separated by a colon :.

# Here is how to define a dictionary in Python with strings as keys
example_dict = {"red": -2, "orange": "Cata", "green": "beach_ball", "blue": 25}

# This outputs the value that corresponds to the key "red"

# The following line will error, because integer 1 is not a valid key for this dictionary

In addition to the above example, here is a table that highlights some of the other properties of dictionaries in Python (you may need to scroll side-to-side):

Container Type \(\hspace{0.5in}\)

Mutable or Immutable \(\hspace{0.5in}\)

Initialization Without Values \(\hspace{0.9in}\)

Initializtion With Values \(\hspace{2.5in}\)

Adding Values to Container \(\hspace{3.5in}\)

Removing Values from Container \(\hspace{2.0in}\)

Modifying Values \(\hspace{2.0in}\)

Access Method \(\hspace{1.0in}\)

Notable Operations and Additional Information \(\hspace{2.5in}\)




>>> student={'name': 'John Doe', 'age': 22, 'college': 'MSU'}

>>> student['major']='Computer Science'
>>> student
{'name': 'John Doe', 'age': 22, 'college': 'MSU', 'major': 'Computer Science'}

del dictName[keyName] #This method removes all entries associated with the given key

>>> student['age'] = 23
>>> student
{'name': 'John Doe', 'age': 23, 'college': 'MSU', 'major': 'Computer Science'}

Access by key word. Note that this key must be a string.

The ‘in’ keyword can be very helpful with dictionaries. Ex:

  • 'k' in dict #Returns true if key 'k' is in dictionary dict
  • 'k' not in dict #Returns true if key 'k' is not in dicitonary dict
  • for key in dict #This will iterate over all keys in dictionary dict

See webpage here for additional helpful methods and operations

✅  Question 4.1 (3 Points)#

Define a dictionary called cmse_801. There will be 4 elements in your dictionary. The keys should be the strings "Instructor", "TA", "Section", and "Class Days". The values assigned to each key should be your respective instructor, TA, section number (e.g. 1, 2, 3, or 5), and a list that contains the days of the week that the course meets. Once you’ve created it, print your dictionary.

# Put your code here

✅  Question 4.2 (4 Points)#

As you can see dictionaries can be a great way to store data. Assume you live in a time where streaming services did not exist and you actually had hard copies of movies (DVD, VideoCassettes, etc..), music albums (Music cassette, CD, Vinyl, etc…), and books (ever heard of a library?). Now imagine you work for Blockbuster, or a record store, or a library and you have to make a catalog of their collection.

Write a dictionary whose keys are (choose one):

  1. Records Store Music: by storing artist’ name(s), albums, release year, genre(s), type of technology (Vinyl, CD, music casette), aisle number, shelf number

  2. Blockbuster Movies: by storing movie title, release year, director, cast, technology (DVD, Bluray, VC, IMAX, etc.), IMDB rating, genre(s), aisle number, shelf number

  3. Library Books: by storing book author, title, publisher, year, genre(s), type of cover (hardcover, paperback), aisle number, shelf number

Now, store 5 to 10 of your favorite (directors, artists, authors) and for each store 3 or more titles (movies, albums, books). If you don’t have favorites you can pick them from the internet.

Note that each dictionary has the keys aisle number and shelf number. These indicate where the item is stored so that if a customer asks, you (as the clerk) can easily find the item for them. You can choose these however you want, e.g. Aisle 1, Shelf 2

# Put your code here

✅  Question 4.3 (4 Points)#

Write a function that retrieves the aisle and shelf number of a requested item from a catalog.

Your function should take, beside the catalog you created, the following inputs based on the type of catalog:

  1. Record Store Music: The input to your function should be the artist and album name.

  2. Blockbuster Movies: The input to your function should be the movie title and director.

  3. Library Books: The input to your function should be the author and book title.

In addition, your function should return “Item not found” if the customer asks for something not in your catalog. For example. You might have the artist (director, book author), but not their album (movie, book title).

# Put your code here

def find_aisle_and_shelf(..., ..., catalog):

✅  Question 4.4 (4 Points)#

Test that your code works correctly by trying to retrieve

  1. an item that is in your catalog,

  2. an item that is not in your catalog.

# Put your code here

Wait! Before you submit your notebook, read the following important recommendations#

When your TA opens your notebook to grade the assignment, it will be really useful if your notebook is saved in a fully executed state so that they can see the output of all your code. Additionally, it may be necessary from time to time for the TA to actually run your notebook, but when they run the notebook, it is important that you are certain that all the code will actually run for them!

You should get into the following habit: before you save and submit your final notebook for your assignments, go to the “Kernel” tab at the top of the notebook and select “Restart and Run all”. This will restart your notebook and try to run the code cell-by-cell from the top to the bottom. Once it finished, review you notebook and make sure there weren’t any errors that popped up. Sometimes, when working with notebooks, we accidentally change code in one cell that break our code in another cell. If your TA stumbles across code cells that don’t work, they will likely have to give you a zero for those portions of the notebook that don’t work. Testing your notebook one last time is a good way to make sure this doesn’t happen.

Once you’ve tested your whole notebook again, make sure you save it one last time before you upload it to D2L.

Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Homework Assignments” section, find the submission folder link for Homework #1, and upload it there.

Copyright © 2024, Department of Computational Mathematics, Science and Engineering at Michigan State University, All rights reserved.