Python_24_Udacity_Evans_Intro to CS_6_How to have infinite power

总目录


课程页面:https://www.udacity.com/course/intro-to-computer-science--cs101
授课教师:Dave Evans https://www.cs.virginia.edu/~evans/
如下内容包含课程笔记和自己的扩展折腾

factorial (recursion)

# -*- coding: utf-8 -*-

# Define a procedure, factorial, that takes a natural number as its input, and
# returns the number of ways to arrange the input number of items.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)


print factorial(0)
#>>> 1

print factorial(5)
#>>> 120

print factorial(10)
#>>> 3628800

Palindromes

# -*- coding: utf-8 -*-

# Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.

# Base Case: '' => True
# Recursive Case: if first and last characters don't match => False
# if they do match, is the middle a palindrome?

# 下面的是我的算法:
def is_palindrome(s):
    if s == "":
        return True
    else:
        return s[0] == s[-1] and is_palindrome(s[1:-1])

'''
这里是Udacity的算法,和我的思路稍许不一样:
def is_palindrome(s):
    if s == "":
        return True
    else:
        if s[0] == s[-1]:
            return is_palindrome(s[1:-1])
        else:
            return False
'''


print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True
print is_palindrome('aba')
# True

Evans有提及,相比于interactive way,对python来说,the recursive way is fairly expensive... 有时候还是最好用数学上的一些算法优化一下。

Fibonacci numbers (recursive)

# -*- coding: utf-8 -*-

# Define a procedure, fibonacci, that takes a natural number as its input, and
# returns the value of that fibonacci number.

# Two Base Cases:
#    fibonacci(0) => 0
#    fibonacci(1) => 1

# Recursive Case:
#    n > 1 : fibonacci(n) => fibonacci(n-1) + fibonacci(n-2)

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print fibonacci(0)
#>>> 0
print fibonacci(1)
#>>> 1
print fibonacci(15)
#>>> 610

Fibonacci numbers (interactive)

# -*- coding: utf-8 -*-

#Define a faster fibonacci procedure that will enable us to computer
#fibonacci(36).

# 下面是我的算法,写的很臃肿
def fibonacci(n):
    fibo1 = 0
    fibo2 = 1
    count = 1
    if n == 1:
        return 1
    if n == 0:
        return 0
    while count < n:
        r = fibo1 + fibo2
        fibo1 = fibo2
        fibo2 = r
        count +=1
    return r

'''
# Udacity的算法相较之下好多了
def fibonacci(n):
    current = 0
    after = 1
    for i in range(n):
        current, after = after, current+after
    return current
'''

print fibonacci(36)
#>>> 14930352

Implementing Urank

# -*- coding: utf-8 -*-

# Modify the crawl_web procedure so that instead of just returning the
# index, it returns an index and a graph. The graph should be a
# Dictionary where the key:value entries are:

#  url: [list of pages url links to]


def crawl_web(seed): # returns index, graph of outlinks
    tocrawl = [seed]
    crawled = []
    graph = {}  # :[list of pages it links to]
    index = {}
    while tocrawl:
        page = tocrawl.pop()
        if page not in crawled:
            content = get_page(page)
            add_page_to_index(index, page, content)
            outlinks = get_all_links(content)
            graph[page] = outlinks
            #Insert Code Here

            union(tocrawl, outlinks)
            crawled.append(page)
    return index, graph


cache = {
   'http://udacity.com/cs101x/urank/index.html': """

Dave's Cooking Algorithms

Here are my favorite recipes:

For more expert opinions, check out the Nickel Chef and Zinc Chef. """, 'http://udacity.com/cs101x/urank/zinc.html': """

The Zinc Chef

I learned everything I know from the Nickel Chef.

For great hummus, try this recipe. """, 'http://udacity.com/cs101x/urank/nickel.html': """

The Nickel Chef

This is the best Hummus recipe! """, 'http://udacity.com/cs101x/urank/kathleen.html': """

Kathleen's Hummus Recipe

  1. Open a can of garbanzo beans.
  2. Crush them in a blender.
  3. Add 3 tablespoons of tahini sauce.
  4. Squeeze in one lemon.
  5. Add salt, pepper, and buttercream frosting to taste.
""", 'http://udacity.com/cs101x/urank/arsenic.html': """

The Arsenic Chef's World Famous Hummus Recipe

  1. Kidnap the Nickel Chef.
  2. Force her to make hummus for you.
""", 'http://udacity.com/cs101x/urank/hummus.html': """

Hummus Recipe

  1. Go to the store and buy a container of hummus.
  2. Open it.
""", } def get_page(url): if url in cache: return cache[url] else: return None def get_next_target(page): start_link = page.find('>> ['http://udacity.com/cs101x/urank/hummus.html', #'http://udacity.com/cs101x/urank/arsenic.html', #'http://udacity.com/cs101x/urank/kathleen.html', #'http://udacity.com/cs101x/urank/nickel.html', #'http://udacity.com/cs101x/urank/zinc.html']

Computer Ranks

# -*- coding: utf-8 -*-

#Finishing the page ranking algorithm.

def compute_ranks(graph):
    d = 0.8 # damping factor
    numloops = 10

    ranks = {}
    npages = len(graph) # 6
    for page in graph:
        ranks[page] = 1.0 / npages # 0.16667

    for i in range(0, numloops):
        newranks = {}
        for page in graph:
            newrank = (1 - d) / npages
            for item in graph:
                if page in graph[item]:
                    newrank += d*(ranks[item]/len(graph[item]))
            newranks[page] = newrank
        ranks = newranks
    return ranks



cache = {
   'http://udacity.com/cs101x/urank/index.html': """

Dave's Cooking Algorithms

Here are my favorite recipies:

For more expert opinions, check out the Nickel Chef and Zinc Chef. """, 'http://udacity.com/cs101x/urank/zinc.html': """

The Zinc Chef

I learned everything I know from the Nickel Chef.

For great hummus, try this recipe. """, 'http://udacity.com/cs101x/urank/nickel.html': """

The Nickel Chef

This is the best Hummus recipe! """, 'http://udacity.com/cs101x/urank/kathleen.html': """

Kathleen's Hummus Recipe

  1. Open a can of garbonzo beans.
  2. Crush them in a blender.
  3. Add 3 tablesppons of tahini sauce.
  4. Squeeze in one lemon.
  5. Add salt, pepper, and buttercream frosting to taste.
""", 'http://udacity.com/cs101x/urank/arsenic.html': """

The Arsenic Chef's World Famous Hummus Recipe

  1. Kidnap the Nickel Chef.
  2. Force her to make hummus for you.
""", 'http://udacity.com/cs101x/urank/hummus.html': """

Hummus Recipe

  1. Go to the store and buy a container of hummus.
  2. Open it.
""", } def crawl_web(seed): # returns index, graph of inlinks tocrawl = [seed] crawled = [] graph = {} # , [list of pages it links to] index = {} while tocrawl: page = tocrawl.pop() if page not in crawled: content = get_page(page) add_page_to_index(index, page, content) outlinks = get_all_links(content) graph[page] = outlinks union(tocrawl, outlinks) crawled.append(page) return index, graph def get_page(url): if url in cache: return cache[url] else: return None def get_next_target(page): start_link = page.find('>> {'http://udacity.com/cs101x/urank/kathleen.html': 0.11661866666666663, #'http://udacity.com/cs101x/urank/zinc.html': 0.038666666666666655, #'http://udacity.com/cs101x/urank/hummus.html': 0.038666666666666655, #'http://udacity.com/cs101x/urank/arsenic.html': 0.054133333333333325, #'http://udacity.com/cs101x/urank/index.html': 0.033333333333333326, #'http://udacity.com/cs101x/urank/nickel.html': 0.09743999999999997}

你可能感兴趣的:(Python_24_Udacity_Evans_Intro to CS_6_How to have infinite power)