Homework 17

Problem 1

Problem 2

Write a function called sum that will return the sum of an arbitrary number of arguments given as function parameters. Test the function by calling it with sum(1,2,3,4) and sum(1,2,3,4,5).

Problem 3

Create a dictionary called uconv that pairs conversion strings with conversion factors so that you can multiply a number by the conversion factor corresponding to the string, for example:

a_m = 5.5
a_ft = a_m*uconv['m_to_ft']

Include a few common conversions for distance, mass, and eneregy and test them out.

Problem 4

Write a dictionary called Mel pairing elements C, H, O, and N with their molecular weights (12.01, 1.008, 16.00, 14.01). Then write a function called M(sp) that takes a string name of a molecule made up of the given elements and returns the molecular weight of the species. So, M('CH2O') should return 30.026. You’ll have to figure out how to process the species name. You can treat strings like arrays, so, if sp='CH2O' then len(sp) is 4 and sp[1] is H. In my solution, I Googled “Python test if a single character is a number” and it gave the isdigit() function. Like, if c = "5" then c.isdigit() is True. You can assume there are less than 10 atoms of a given element in a molecule. Your function should make use of your Mel dictionary. You can do this problem with the tools we’ve learned so far, and as outlined here.

If you want a more general function, one that can handle species with element names with two letters, like Na, or Cl, and that can handle bigger atom numbers, like C12H24ClOH, then here’s a fancy piece of Python code that makes use of a so-called regular expression. This expression has four parts, separated by | which means “or”. The four parts split between a letter and a digit, between a digit and a letter, between two uppercase letters, or between a lowercase letter and an uppercase letter. The prompt I gave Codex (AI) to provide this was “Python, split a string between letters and numbers, or two consecutive uppercase letters, or between a lowercase letter and an uppercase letter.”


import re

species = 'C12H24ClOH'

parts = re.split( r"(?<=[A-Za-z])(?=\d)|(?<=\d)(?=[A-Za-z])|(?<=[A-Z])(?=[A-Z])|(?<=[a-z])(?=[A-Z])", species )

print(parts)

will output ['C', '12', 'H', '24', 'Cl', 'O', 'H']