CS 200 - Introduction¶

August 30, 2023

Load file: f0828.py (http://zoo.cs.yale.edu/classes/cs200/lectures/f0828.py)

Note: python file names cannot start with a number, so no 0830.py

In [1]:
import f0828
end of f0828
name: f0828

The file contains the line:

digits = range(10)

which defines a variable, digits

In [2]:
digits
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [2], in <cell line: 1>()
----> 1 digits

NameError: name 'digits' is not defined

But we get an error, because the import statement will prepend the filename to every variable to protect the name space.

In [3]:
f0828.digits
Out[3]:
range(0, 10)
In [4]:
list(f0828.digits)
Out[4]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If we want to avoid this prefix notation, we can use the from statement

In [5]:
from f0828 import *
In [6]:
digits
Out[6]:
range(0, 10)

We next define a function, num_to_word

In [7]:
num_to_word(8)
Out[7]:
'eight'
In [8]:
num_to_word(12)
Out[8]:
False
In [9]:
num_to_word(-1)
Out[9]:
'nine'

Using negative numbers to index a list gives you elements starting at the right hand side

In [10]:
from psource import *
In [11]:
psource(num_to_word)

def num_to_word(num):
    if num > 9:
        return False
    numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
    return numbers[num]

psource is a function that displays the definition of a given function. Here is the definition of psouce:

In [12]:
psource(psource)

def psource(*functions):
    """Print the source code for the given function(s)."""
    source_code = '\n\n'.join(getsource(fn) for fn in functions)
    try:
        from pygments.formatters import HtmlFormatter
        from pygments.lexers import PythonLexer
        from pygments import highlight

        display(HTML(highlight(source_code, PythonLexer(), HtmlFormatter(full=True))))

    except ImportError:
        print(source_code)
In [13]:
psource(word_to_num)

def word_to_num(word):
    numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
    def find_index(lst,n, word):
        if not lst:
            return False
        if lst[0] == word:
            return n
        return find_index(lst[1:], n+1, word)
    return find_index(numbers,0,word)
In [14]:
xlist
Out[14]:
['zero',
 'one',
 'two',
 'three',
 'four',
 'five',
 'six',
 'seven',
 'eight',
 'nine']
In [15]:
y
Out[15]:
['eight',
 'five',
 'four',
 'nine',
 'one',
 'seven',
 'six',
 'three',
 'two',
 'zero']
In [16]:
z
Out[16]:
<map at 0x7f3a886d0880>
In [17]:
zlist
Out[17]:
[8, 5, 4, 9, 1, 7, 6, 3, 2, 0]
In [18]:
''.join(map(str,zlist))
Out[18]:
'8549176320'
In [19]:
int(''.join(map(str,zlist)))
Out[19]:
8549176320
In [20]:
''.join(map(str,zlist)) + '1'
Out[20]:
'85491763201'
In [21]:
int(''.join(map(str,zlist))) + 1
Out[21]:
8549176321

This should look familiar.