Quiz: Deep Count

# Deep Count 

# The built-in len operator outputs the number of top-level elements in a List,
# but not the total number of elements. For this question, your goal is to count
# the total number of elements in a list, including all of the inner lists.

# Define a procedure, deep_count, that takes as input a list, and outputs the
# total number of elements in the list, including all elements in lists that it
# contains.


# For this procedure, you will need a way to test if a value is a list. We have
# provided a procedure, is_list(p) that does this:

def is_list(p):
    return isinstance(p, list)

# It is not necessary to understand how is_list works. It returns True if the
# input is a List, and returns False otherwise.

def deep_count(p):
    x = 0
    for item in p:
        if is_list(item):
            x += deep_count(item)
    return len(p) + x




#print deep_count([1, 2, 3])
#>>> 3

# The empty list still counts as an element of the outer list
print deep_count([1, [], 3]) 
#>>> 3 

#print deep_count([1, [1, 2, [3, 4]]])
#>>> 7

print deep_count([[[[[[[[1, 2, 3]]]]]]]])
#>>> 10

이렇게 하는게 맞나 싶다. 배열 p를 인자로 받아 루프를 돌린다. p내에 또다른 배열이 있는지 확인하고 만약 없다면 p의 길이를 반환한다. 만약 있다면 그 배열을 재귀적으로 사용하여 다시 루프를 돌린다. 더이상 배열이 없을때 까지 반복하여 더이상 배열이 없으면 길이와 x값을 매번 더해서 반환 반환반환 아이거말로쓰는것도 잘해야하는데...

Quiz: Only a Little Lucky

def ordered_search(index, ranks, keyword):
    result = {}
    urls = lookup(index, keyword)
    if urls:
        for url in urls:
            if url in ranks:
                result[url] = ranks[url]
        return sorted(result, key=lambda k : result[k], reverse=True) #value를 기준으로 정렬하고, reverse했다.
    else:
        return None

# 검색앤진 코드생략

def lookup(index, keyword):
    if keyword in index:
        return index[keyword]
    else:
        return None

index, graph = crawl_web('http://udacity.com/cs101x/urank/index.html')
ranks = compute_ranks(graph)

print ordered_search(index, ranks, 'the')
#>>> ['http://udacity.com/cs101x/urank/nickel.html',
#    'http://udacity.com/cs101x/urank/arsenic.html',
#    'http://udacity.com/cs101x/urank/hummus.html',
#    'http://udacity.com/cs101x/urank/index.html']


print ordered_search(index, ranks, 'babaganoush')
#>>> None

rank, graph등등... 이전코드를 모두 잘 이해해야지만 풀수 있었다.

#udacity
def ordered_search(index, ranks, keyword):
    pages = lookup(index,keyword)
    return quicksort_page(pages,ranks)

def quicksort_page(pages,ranks):
    if not pages or len(pages) <= 1:
        return pages
    else:
        pivot = ranks[pages[0]]
        worse = []
        better = []
        for page in pages[1:]:
            if ranks[page] <= pivot:
                worse.append(page)
            else:
                better.append(page)
        return quicksort_page(worse,ranks) + [pages[0]] + quicksort_page(better,ranks)

미친생각지도 못했다..

sorted()

# dictionary 정렬
# 뎍셔너리를 sort하면 기본적으로 key를 기준으로 정렬한다.

fruits = { 'apple': 2, 'banana' : 1, 'melon' : 0, 'pear' : 2, 'plum' : 1}

sorted(fruits) #['apple', 'banana', 'melon', 'pear', 'plum']
sorted(fruits.keys()) #['apple', 'banana', 'melon', 'pear', 'plum']

# 역방향
sorted(fruits, reverse=True) #['plum', 'pear', 'melon', 'banana', 'apple']

# 이것을 value를 기준으로 정렬하려면,
# 메소드 안에 람다..?인자를 넣어준다.
# 파이썬은 이런걸 할수 있나보다.
sorted(fruits, key=lambda k : fruits[k]) # ['melon', 'plum', 'banana', 'pear', 'apple']

# 역방향 정렬
sorted(fruits, key=lambda k : fruits[k], reverse=True) #['pear', 'apple', 'plum', 'banana', 'melon']

results matching ""

    No results matching ""