Google Python Tutorial -  Basic Python Exercises #2


*참고:  google-python-exercises.zip 의 경우, python 2.x로 작성되어 있다.

나의 경우 python 3.x로 작업하고 있기때문에 2to3를 이용해 우선 3.x로 변경하는 사전 작업후 코드를 작성하였다.


Google Python Tutirial의 Basic Python Exercises에는 총 3개의 예제가 존재가 있다.

그 중 두번째 예제는 List 섹션의 내용을 학습하고 list1.py의 function들을 완성하는 예제이다.

예제는 우선 직접 코드를 작성하였고,  solution폴더에 있는 답과 비교해보는 방식을 취하였다.

직접 작성하여 답과는 다를 수 있다.


#1 list1.py

# Basic list exercises

# Fill in the code for the functions below. main() is already set up

# to call the functions with a few different inputs,

# printing 'OK' when each function is correct.

# The starter code for each function includes a 'return'

# which is just a placeholder for your code.

# It's ok if you do not complete all the functions, and there

# are some additional functions to try in list2.py.

list1.py에는 총 3개의 문제가 있다.


# 1-1 인덱스, len()

# A. match_ends

# Given a list of strings, return the count of the number of

# strings where the string length is 2 or more and the first

# and last chars of the string are the same.

# Note: python does not have a ++ operator, but += works.

def match_ends(words):

    # +++your code here+++

    cnt = 0

    for word in words:

        if len(word) >= 2:

            if word[0] == word[-1]:

                cnt += 1

    return cnt


# 1-2 sorted(), 인덱스, append(), startswith()

# B. front_x

# Given a list of strings, return a list with the strings

# in sorted order, except group all the strings that begin with 'x' first.

# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields

# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

# Hint: this can be done by making 2 lists and sorting each of them

# before combining them.

def front_x(words):

    # +++your code here+++

    xlist = []

    otherlist = []

    words = sorted(words)

    

    for word in words:

        ''' 시작 문자 x를 찾는 다른방법 

        if word.startswith('x'):

            xlist.append(word)

        '''

        if word[0] == 'x'

            xlist.append(word)

        else:

            otherlist.append(word)

    

    xlist = sorted(xlist);

    return xlist + otherlist


# 1-3 sorted(), custom key sort, 인덱스

# C. sort_last

# Given a list of non-empty tuples, return a list sorted in increasing

# order by the last element in each tuple.

# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields

# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]

# Hint: use a custom key= function to extract the last element form each tuple.

def sort_last(tuples):

    # +++your code here+++

    tuples = sorted(tuples, key=myfnc)

    return tuples


def myfnc(s):

    return s[-1]




#2 list2.py

# Additional basic list exercises

list2.py에는 총 2개의 문제가 있다.


# 2-1 인덱스, len(), append()

# D. Given a list of numbers, return a list where

# all adjacent == elements have been reduced to a single element,

# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or

# modify the passed in list.

def remove_adjacent(nums):

    # +++your code here+++

    outputlist = []

    for num in nums:

        cnt = len(outputlist)

        if cnt == 0 or outputlist[-1] != num:

            outputlist.append(num)

    return outputlist


# 2-2 len(), pop(0), pop(-1), append(), extend()

# E. Given two lists sorted in increasing order, create and return a merged

# list of all the elements in sorted order. You may modify the passed in lists.

# Ideally, the solution should work in "linear" time, making a single

# pass of both lists.

def linear_merge(list1, list2):

    # +++your code here+++

    outputlist = []


    while len(list1) != 0 and len(list2) != 0:

        if list1[0] < list2[0]:

            outputlist.append(list1.pop(0))

        else:

            outputlist.append(list2.pop(0))

    

    outputlist.extend(list1)

    outputlist.extend(list2)

    

    ''' pop(-1), reverse()를 이용한 방법 

    while len(list1) != 0 and len(list2) != 0:

        if list1[-1] < list2[-1]:

            outputlist.append(list2.pop(-1))

        else:

            outputlist.append(list1.pop(-1))

    outputlist.extend(list1)

    outputlist.extend(list2)

    outputlist.reverse()

    '''

    return outputlist

        

# Note: the solution above is kind of cute, but unforunately list.pop(0)

# is not constant time with the standard python list implementation, so

# the above is not strictly linear time.

# An alternate approach uses pop(-1) to remove the endmost elements

# from each list, building a solution list which is backwards.

# Then use reversed() to put the result back in the correct order. That

# solution works in linear time, but is more ugly.

+ 오름차순 정렬된 리스트 두개를 인자로 받아서 머지한 정렬된 리스트를 반환하는 함수

선형시간안에 머지된 리스트를 만들도록 구현..

나온 방법대로 했지만..note내용을 정확히 이해는 못했음....ㅠㅠ

'컴&프로그래밍 > Python' 카테고리의 다른 글

6. 모듈  (0) 2014.12.29
Mac OS X Yosemite에서 PyCharm 설치 후 실행  (0) 2014.12.27
5. 클래스  (0) 2014.12.20
4. 제어  (0) 2014.12.19
Google Python Tutorial - Basic Python Exercises #1 String  (0) 2014.12.05
Python 2.x에서 3.x로 변경  (0) 2014.12.03
튜플 자료형 특이사항  (0) 2014.10.19
자료형과 연산자  (0) 2014.10.18
Hello Python  (0) 2014.10.15