Week 1, Problem 2: Functioning smoothly!
[25 points; individual or pair]

 

 

Part 0: Create a new file

To hold your answers and work from this portion of the lab, use IDLE to create a new file (or save the current one with the new name). Be sure to name the  file for this part of the lab (and homework) hw1pr2.py.

 

Part 1: Using built-in functions

To begin, simply use the interactive Python window to try out some of the built-in functions:

>>> range(0,100)
[0,1,2,...,99]  range returns a list of integers

>>> sum(range(0,101))
5050  sum sums a list of numbers, and range creates a list of integers. Note that when you use range, as with almost everything in python, the right endpoint is omitted!


>>> sum([40,2])
42   a roundabout way of adding 40+2

>>> help(sum)
(an explanation of sum)   help is a good thing—ask for it by name!

>>> dir(__builtins__)

(a huge list of built-in functions, all possible errors, etc.)   dir is also useful, listing everything from a particular file (or module); the special __builtins__ module is, well, built-in!

How to type__builtins__? There are two underscores both before and after the lowercase letters: the underscore, _, is shift-hyphen on most computer keyboards (between the right parenthesis and the plus sign).

If you look carefully in the big list of stuff returned from dir, you will find the sum function you used above. You will not, however, find some other important functions, for example, sin or cos or sqrt. All of these functions (and many more) are in the math module. By the same token, there are many, many more modules (files) of functions available for you to use….

 

Part 2: importing other code (or "modules")

To access functions that are not built-in by default, you need to load them from their modules. There are a couple of ways to do this:

(1)  You can import the module and then access its functions with the module name:

>>> import math

(no response from Python)

>>> math.sqrt(9)
3.0  Note that sqrt returns a float even if its input is an int.

>>> math.cos(3.14159)
-0.999...  Note that cos et al. take radians as input and 3.14159 != math.pi, that is to say it's only an approximation. Try math.cos(math.pi), as well.


(2)  Tired of typing math. in front of things? You can avoid this with
>>> from math import *
(no response from Python)  The asterisk * here means "everything." This will bring all of the functions and constants from the math module into your current python environment, and you can use them without prefacing them by math.

>>> cos(pi)
-1.0
This would have had to be math.cos(math.pi) before the new "from math import *" import statement.

 

Part 3. Creating your own functions in a file

Python has lots of functions, the building blocks of computation. What distinguishes Python from other computing environments is the ease and power of creating your own functions.

Here, we will create a few in your hw1pr2.py file. In that file, below any comments you may have at the very top, type (or paste!) the following function definition:

 

def dbl(x):

""" dbl returns twice its input

input x: a number (int or float)

"""

return 2*x


Next, load this dbl function into the interpreter by hitting the F5 key.

Then, try it out at the interpreter:


>>> dbl(21)
42

The above code creates a function named dbl that outputs twice what it gets as input. The string inside triple quotes """ is called the docstring (documentation string)—this should describe what the function outputs (here in the first line) and what the function inputs (here in the second line). It becomes part of Python's built-in help system. Finally, in the function's last line its work is done and the result is returned.

We will ask you to include a docstring in all of your functions (even simple ones such as these, in order to feed the habit). This self-documenting feature in Python is especially important for making your functions understandable, both to others and to yourself!

Using help to access docstrings

It's worth noting that Python's help command simply prints a function's docstring. As a result, when imported, your dbl function is already a fully-integrated part of the Python language and help system. Try typing help(dbl) at the interpreter prompt:

>>> help(dbl)

Help on function dbl in module __main__:

 

dbl(x)

dbl returns twice its input

input x: a number (int or float)

 

 

Part 4: Try it out! 6 functions to write…

To begin, you may want to include the line

from math import *

or the line

import math

near the top of your hw1pr2.py file. That way, you'll be able to use any functions from the math module as needed in your solutions.

Include a docstring that describes what your function does and what its inputs are for each function.

Example: Write the function tpl(x), which takes in a numeric input and outputs three times that input.

Answer to example: might be something like this, in hw1pr2.py:

def tpl(x):

""" tpl returns thrice its input

input x: a number (int or float)

"""

return 3*x

 

The functions to write:

1. Write sq(x), which takes in a (floating-point) number named x as input. Then, sq should output the square of its input.

2. interp(low,hi,fraction) takes in three numbers, low, hi, and fraction, and should return a floating-point value that linearly interpolates between low and hi as far as fraction specifies. That is, if fraction is zero, low will be returned. If fraction is one, hi will be returned, and values of fraction between 0 and 1 lead to results between low and hi. See the examples below for additional detail.

Your function should also work if fraction is less than zero or greater than one. In this case, it will be linearly extrapolating, rather than interpolating. But we'll stick with the name interp anyway.

From the above description, it might be tempting to divide this function into several cases and use if, elif, and the like. However, it is possible to write this function without using any conditional (if) constructions at all. Some examples:

>>> interp(1.0, 3.0, 0.25)  # a quarter of the way from 1.0 to 3.0

1.5

 

>>> interp(0, 10, 0.42)  # 42% of the way from 0 to 10

4.2

 

Actually, you might get 4.2000000000000002 or something similar, depending on your implementation. This is OK, it simply reflects the finite precision (in binary) available to the computer.

 

>>> interp(24, 42, 0) # 0% of the way from 24 to 42

24.0

 

>>> interp(102, 117, -4.0)  # -400% of the way from 102 to 117

42.0

 

3. Write a function checkends(s), which takes in a string s and returns True if the first character in s is the same as the last character in s. It returns False otherwise. The checkends function does not have to work on the empty string (the string '').

Examples:

>>> checkends('no match')

False

>>> checkends('hah! a match')

True

>>> help(checkends)

This function sees if the first and last characters of its input are the same.

  Input: a string, s

Of course, your docstring may be different—or, feel free to just paste this one….

 

4. Write a function flipside(s), which takes in a string s and returns a string whose first half is s's second half and whose second half is s's first half. If len(s) (the length of s) is odd, the first half of the input string should have one fewer character than the second half. (Accordingly, the second half of the output string will be one shorter than the first half in these cases.)

Here you may want to use the built-in function len(s), which returns the length of the input string, s.

Examples:

>>> flipside('homework')

workhome

 

>>> flipside('carpets')

petscar

 

These last two functions combine string and arithmetic processing.

 

 

5. Write convertFromSeconds(s), which takes in a nonnegative integer number of seconds s and returns a list in the same format as above. In this case, you should be sure that

0 ≤ seconds < 60

0 ≤ minutes < 60

0 ≤ hours < 24

There are no limits on the number of days.
For instance,

 

>>> convertFromSeconds(610)

[0, 0, 10, 10]

>>> convertFromSeconds(100000)

[1, 3, 46, 40]

 

6. Finally, write readSeconds(s), a function that takes in a number of seconds, s, and returns a string that expresses that span of time in terms of days, hours, minutes, and seconds - with the same constraints as in problem 9, above. Your function should handle plurals and singulars correctly, as well (see examples).

Keep in mind that readSeconds should return a string, it should not use the print command at all! Also, you'll likely want to call convertFromSeconds as you write readSeconds. Here are a few examples:

 

>>> readSeconds(80)

0 days, 0 hours, 1 minute, 20 seconds

 

>>> readSeconds(100000)

1 day, 3 hours, 46 minutes, 40 seconds

 

Submitting your file

You should submit your hw1pr2.py file at Canvas.

 

Next

Continue working on homework 1: hw1pr3

Lab 1

Homework 1