{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## CS 200 - Introduction\n", "
\n", "
\n",
"\n",
"August 31, 2022\n",
"\n",
"Load file: f0831.py (http://zoo.cs.yale.edu/classes/cs200/lectures/f0831.py) \n",
"\n",
"Note: python file names cannot start with a number, so no 0831.py\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"end of f0831\n",
"name: f0831\n"
]
}
],
"source": [
"import f0831"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The file contains the line:\n",
"\n",
"digits = range(10)\n",
"\n",
"which defines a variable, digits"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'digits' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Input \u001b[0;32mIn [2]\u001b[0m, in \u001b[0;36mdef num_to_word(num):\n",
" if num > 9:\n",
" return False\n",
" numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]\n",
" return numbers[num]\n",
"
psource
is a function that displays the definition of a given function. Here is the definition of psouce:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"\n",
"\n",
" def psource(*functions):\n",
" """Print the source code for the given function(s)."""\n",
" source_code = '\\n\\n'.join(getsource(fn) for fn in functions)\n",
" try:\n",
" from pygments.formatters import HtmlFormatter\n",
" from pygments.lexers import PythonLexer\n",
" from pygments import highlight\n",
"\n",
" display(HTML(highlight(source_code, PythonLexer(), HtmlFormatter(full=True))))\n",
"\n",
" except ImportError:\n",
" print(source_code)\n",
"
def word_to_num(word):\n",
" numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]\n",
" def find_index(lst,n, word):\n",
" if not lst:\n",
" return False\n",
" if lst[0] == word:\n",
" return n\n",
" return find_index(lst[1:], n+1, word)\n",
" return find_index(numbers,0,word)\n",
"