Lesson 5 : How to Repeat

웹크롤러로 시드페이지의 모든 링크를 긁어오는 방법을 배운다. 이것을 가능하게 하기위해 프로시저(함수와 같은의미로 쓰임)procedure와 control 을 배운다.

이전에 배운코드를 활용해 모든 링크를 추출하는 방법을 생각해 보았다.

page = ...contents of some web page ...
start_link = page.find('<a href=')
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote+1)
url = page[start_quote+1: end_quote]
print url

#그리고 반복
page = page[end_quote:]
...

만약 페이지에 100개의 링크가 있다면 위와 같은 코드를 100번 반복해야 한다. 이번 문제점을 해결하기 위한 방안으로 프로시저가 있다. 위 코드에서 page변수를 제외한 모든 코드는 계속 반복된다.

approximately : 대략
assignment : 할당

프로시저(procedure)

다른 언어의 함수와 같다.

# 1개의 파라미터를 받는 프로시저
def rest_of_string(s): # s = 'audacity'
    return s[1:]

print rest_of_string('audacity') # => 'udacity'

# 2개의 파라미터를 받는 프로시저
def sum(a,b):
    a = a+b
    return a

a = 1
b = 2
print sum(a,b) # => 3
print a # => 1 a는 변하지 않았다.

Quiz : Find Second

# input two strings : search string, target string
# example
# a = "My name is minwoo. It's my name."
# print find_second(name, "name") => 28

def find_second(search, target):
    first = search.find(target)
    second = search.find(target, first+1)
    return second

danton = "De l'audace, encore de l'audace, toujours de l'audace"
print find_second(danton, 'audace') #>>> 25

Quiz : Is Friend

# Assume I am friends with
# everyone whose name starts with either 'D' or 'N', but no one
# else. You do not need to check for
# lower case 'd' or 'n'

def is_friend(a):
    if name[0] == "D" || name[0] == "N":
        return True
    else:
        return False

print is_friend('Diane') #>>> True

OR expression

or 연산자는 좌변이 truthy한 값일경우 좌변을 저장하고, falsy한 값일경우 우변을 저장한다. 만약 좌변이 truthy한 값이라면 우변에 어떤값이 들어와도 (에러를 발생하는 요소, 정의되지 않은 변수라던가) 무시한다.

a = True
b = False

result = a or "a was Truthy value."
print result # => True

result = b or "b was Falsy value."
print result # => "b was Falsy value."

AND expression

and 연산자는 or연산자와 반대로 작동한다. 좌변이 truthy한 값일경우 우변을 저장하고, falsy한 값일경우 좌변을 반환한다.

a = True
b = False

result = a and "a was Truthy value."
print result # => "a was Truthy value."

result = b and "b was Falsy value."
print result # => False

Quiz : Factorial

팩토리얼이 경우의 수 였어?!?

# 내가만든것
def factorial(num):
    size = 1
    total = 1
    while size <= num:
        total = total * size
        size = size + 1
    return total

#유다시티
#변수가 하나 없이 진행된다.

def factorails(n):
    result = 1
    while n >= 1:
        result = result * n
        n = n -1
    return result

print factorial(4)
#>>> 24
print factorial(5)
#>>> 120
print factorial(6)
#>>> 720

Break Time!

# while <TestExpression>:
#    <code>
#    if <BreakTest>:
#        break
#    <More Code>

def use_break(n):
    i = 1
    while True:
        if i > n:
            break
        print i
        i = i+1
    return i

Multiple Assignment

<name>,<name>,<name>,... = <expression>,<expression>,<expression>,...

a,b = 1,2
# a=1, b=2
a,b,c = 1,2 # => ValueError: need more than 2 values to unpack
a,b,c = 1,2,3,4 # => ValueError: too many values to unpack

a,b = b,a # => 값이 swap된다.

js같은경우 [a,b] = [1,2]이런식으로 가능하다.

url 추출가능여부

#                input can more than one --> <params>,<parmas>,...
#def <name>(<parameters>) :
#    <block>

def get_next_target(page):
    start_link = page.find('<a href=') #=> find메서드는 타겟을 찾을수 없으면 -1을 반환한다.
    if start_link == -1:
        return None, 0

    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote+1)
    url = page[start_quote+1: end_quote]
    return url, end_quote

url,endpos = get_next_target(page) # => multiple assignment

모든 url 추출

def get_next_target(page):
    start_link = page.find('<a href=') #=> find메서드는 타겟을 찾을수 없으면 -1을 반환한다.
    if start_link == -1:
        return None, 0

    start_quote = page.find('"', start_link)
    end_quote = page.find('"', start_quote+1)
    url = page[start_quote+1: end_quote]
    return url, end_quote

def print_all_links(page):
    while page: # get_next_target에서 url을 찾을수 없으면 page가 0이 되고 루프가 멈춘다.
        url,endpos = get_next_target(page) # => multiple assignment
        if url: #url을 반환하면 출력하고 page를 갱신한다.
            print url
            page = page[endpos:]
        else: #url이 없으면(None) 여기서 break를 건다.
            break

실제 web을 긁고싶은데 아쉽군..

Quiz: Finish

n = any positive integer
while n != 1:
    if n % 2 == 0: #n is even
        n = n/2
    else:
        n = 3 * n + 1

# 콜라츠 추측
# 어떤값을 넣어도 1이된다는 공식
# 아닌경우가 없는것 같은데 왜 결과를 알수없다는거지 ㅋㅋ

<String>.rfind(<String>) : find()의 반대. 가장 마지막 위치를 찾는다.

Quiz: Range of a Set

# def set_range(a,b,c):
#     arr = [a,b,c]
#     arr.sort()
#     return arr[-1]-arr[0]

def bigger(a,b):
    if a>b:
        return a
    else:
        return b

def biggest(a,b,c):
    return bigger(a,bigger(b,c))


def small(a,b,c):
    if bigger(a,b)==a:
        if b>c:
            return c
        else:
            return b
    else:
        if a>c:
            return c
        else:
            return a

def set_range(a,b,c):
    return biggest(a,b,c) - small(a,b,c)

print set_range(10, 4, 7)
#>>> 6  # since 10 - 4 = 6

print set_range(1.1, 7.4, 18.7)
#>>> 17.6 # since 18.7 - 1.1 = 17.6

Lesson 2:Problem Set(Optianal 2)

Superhero Nuisance

def fix_machine(debris, product):
    i = 0
    while i < len(product):
        if debris.find(product[i]) != -1:
            i += 1
        else:
            return "Give me something that's not useless next time."
    return product

### TEST CASES ###
print "Test case 1: ", fix_machine('UdaciousUdacitee', 'Udacity') == "Give me something that's not useless next time."
print "Test case 2: ", fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity'
print "Test case 3: ", fix_machine('AEIOU and sometimes y... c', 'Udacity') == 'Udacity'
print "Test case 4: ", fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt'

Days Old

10 Row Abacus

풀었으니 만족..

Leap Year Baby

어렵다
알고리즘 개못해 멍청이 같은 천민우..

Jungle Animal

def jungle_animal(animal, my_speed):
    result=""

    if animal == 'cheetah':
        if my_speed > 115:
            result="Run!"
        else:
            result="Stay calm and wait!"
    elif animal == 'zebra':
        result="Try to ride a zebra!"
    else:
        result="Introduce yourself!"

    print result


jungle_animal('cheetah', 30)
#>>> "Stay calm and wait!"

jungle_animal('gorilla', 21)
#>>> "Introduce yourself!"

results matching ""

    No results matching ""