15-112 Fundamentals of Programming September 29 , 2013

advertisement
15-112 Fundamentals of
Programming
September 29th , 2013
Announcements
Midterm next Sunday
What are we doing today?
Reading from URLs
Recursion
What is HTML?
Hyper Text Markup Language
<HTML>
<TITLE> Hello World </TITLE>
<H1> Welcome to My Webpage </H1>
<img src="melatest.jpg“>
</HTML>
How does the www work?
You enter a URL in the address bar of
your web browser
The web browser fetches the index.html
file from that location
Index.html file has HTML code that is
displayed by the web browser
Reading webpages
We can read web pages using Python
We use the library called urllib
Open a url by using urlopen
p = urllib.urlopen("http://www.cnn.com")
line = p.readline()
while line:
print line
line = p.readline()
Let’s Try this
Read UPC barcode from user and display the
item using http://www.upcdatabase.com
import urllib
upc = raw_input("Enter UPC> ")
p = urllib.urlopen("http://www.upcdatabase.com/item/"+upc)
line = p.readline()
while line:
if "Description" in line:
line = line.replace("Description","")
line = line.replace("<td>","")
line = line.replace("</td>","")
line = line.replace("<tr>","")
line = line.replace("</tr>","")
print line
line = p.readline()
Recursion
A method of simplification that involves
dividing a problem into simpler
subproblems of the same type.
A function that calls itself is called a
recursive functions
Factorial Example
def factorial(n):
if n == 0:
Base Case
return 1
return n * factorial(n-1)
Recursive Case
General Form of Recursive
Functions
Function (input)
base case – this will stop chain of calls
recursive case – call Function with simpler input
Definition of Factorial
F(0) = 1
F(n) = n*F(n-1)
Definition of power
F(b,0) = 1
F(b,e) = b * F(b,e-1)
Factorial Power
def power(base, exp):
if (exp == 0):
return 1
else:
return base * power(base, exp-1)
Sum of All elements in a list
F([ ]) = 0
F([x,….]) = x + F([….])
Sum of All elements in a list
def listSum(list):
if (len(list) == 0):
return 0
else:
return list[0] + listSum(list[1:])
Exercise
We want to write a function that counts
how many odd numbers exist in a list
Write the function definition
Write the recursive function
Exercise 2
Following is the Fibonacci series
1, 1, 2, 3, 5, 8, 13, 21, 34
In general
Fn = Fn-1 + Fn-2
Write the function definition
Write a recursive function called Fib(n)
that returns the nth Fibonacci number
Download