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
import f0828
end of f0828 name: f0828
The file contains the line:
digits = range(10)
which defines a variable, digits
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.
f0828.digits
range(0, 10)
list(f0828.digits)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If we want to avoid this prefix notation, we can use the from statement
from f0828 import *
digits
range(0, 10)
We next define a function, num_to_word
num_to_word(8)
'eight'
num_to_word(12)
False
num_to_word(-1)
'nine'
Using negative numbers to index a list gives you elements starting at the right hand side
from psource import *
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:
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)
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)
xlist
['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
y
['eight', 'five', 'four', 'nine', 'one', 'seven', 'six', 'three', 'two', 'zero']
z
<map at 0x7f3a886d0880>
zlist
[8, 5, 4, 9, 1, 7, 6, 3, 2, 0]
''.join(map(str,zlist))
'8549176320'
int(''.join(map(str,zlist)))
8549176320
''.join(map(str,zlist)) + '1'
'85491763201'
int(''.join(map(str,zlist))) + 1
8549176321
This should look familiar.