Google Python Tutorial -  Basic Python Exercises #1


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

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


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

그중 첫번째 예제는 String 섹션의 내용을 학습하고 string1.py의 string function들을 완성하는 예제이다.

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

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


#1 string1.py

# 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 string2.py.

string1.py에는 총 4개의 문제가 있다.


# 1-1 str생성자

# A. donuts

# Given an int count of a number of donuts, return a string

# of the form 'Number of donuts: <count>', where <count> is the number

# passed in. However, if the count is 10 or more, then use the word 'many'

# instead of the actual count.

# So donuts(5) returns 'Number of donuts: 5'

# and donuts(23) returns 'Number of donuts: many'

def donuts(count):

    # +++your code here+++

    prefix = 'Number of donuts: '

    postfix = ''

    

    if count < 10:

        postfix = str(count)

    else:

        postfix = 'many'

        

    return prefix + postfix


# 1-2 string 길이, 슬라이스

# B. both_ends

# Given a string s, return a string made of the first 2

# and the last 2 chars of the original string,

# so 'spring' yields 'spng'. However, if the string length

# is less than 2, return instead the empty string.

def both_ends(s):

    # +++your code here+++

    if len(s) < 2:

        return ''

    else:

        return s[:2] + s[-2:]


# 1-3 인덱스, 슬라이스, replace()

# C. fix_start

# Given a string s, return a string

# where all occurences of its first char have

# been changed to '*', except do not change

# the first char itself.

# e.g. 'babble' yields 'ba**le'

# Assume that the string is length 1 or more.

# Hint: s.replace(stra, strb) returns a version of string s

# where all instances of stra have been replaced by strb.

def fix_start(s):

    # +++your code here+++

    firstchar = s[0]

    remindstr = s[1:]

    totalstr = firstchar + remindstr.replace(firstchar, '*')

    return totalstr


# 1-4 슬라이스

# D. MixUp

# Given strings a and b, return a single string with a and b separated

# by a space '<a> <b>', except swap the first 2 chars of each string.

# e.g.

# 'mix', pod' -> 'pox mid'

# 'dog', 'dinner' -> 'dig donner'

# Assume a and b are length 2 or more.

def mix_up(a, b):

    # +++your code here+++

    firststr = a[:2]+b[2:]

    secndstr = b[:2]+a[2:]

    return secndstr + ' ' + firststr




#2 string2.py

# Additional basic string exercises


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


# 2-1 슬라이스

# D. verbing

# Given a string, if its length is at least 3,

# add 'ing' to its end.

# Unless it already ends in 'ing', in which case

# add 'ly' instead.

# If the string length is less than 3, leave it unchanged.

# Return the resulting string.

def verbing(s):

    # +++your code here+++

    if len(s) >= 3:

        if s[-3:] == 'ing'

            s += 'ly'

        else

            s += 'ing'

    return s


# 2-2 find(), 슬라이스

# E. not_bad

# Given a string, find the first appearance of the

# substring 'not' and 'bad'. If the 'bad' follows

# the 'not', replace the whole 'not'...'bad' substring

# with 'good'.

# Return the resulting string.

# So 'This dinner is not that bad!' yields:

# This dinner is good!

def not_bad(s):

    # +++your code here+++

    totalstr = s

    notidx = s.find('not')

    badidx = s.find('bad')

    

    if notidx != -1 and badidx != -1:

        if notidx < badidx:

            frontstr = s[:notidx]

            backstr = 'good' + s[badidx+3:]

            totalstr = frontstr + backstr

    return totalstr


# 2-3 //(정수나누기), %(나머지 연산자), 슬라이스

# F. front_back

# Consider dividing a string into two halves.

# If the length is even, the front and back halves are the same length.

# If the length is odd, we'll say that the extra char goes in the front half.

# e.g. 'abcde', the front half is 'abc', the back half 'de'.

# Given 2 strings, a and b, return a string of the form

#a-front + b-front + a-back + b-back

def front_back(a, b):

    # +++your code here+++

    ahalf = len(a) // 2     # 정수 나누기에 유의 

    bhalf = len(b) // 2


    if (len(a)%2) != 0:

        ahalf += 1

    if (len(b)%2) != 0:

        bhalf += 1

    

    return a[:ahalf] + b[:bhalf] + a[ahalf:] + b[bhalf:]


* 참고: 구글 해답: python 3.x으로 변환하면서 solution code를 실행하면 runtime error가 발생함

슬라이스 인덱스에 정수가 아닌값이 들어가게 되면서 발생한 error

/ 대신에 //로 변환하여 error를 수정할 수 있음

def front_back(a, b):

    # +++your code here+++

    # LAB(begin solution)

    # Figure out the middle position of each string.

    a_middle = len(a) / 2

    b_middle = len(b) / 2

    if len(a) % 2 == 1:# add 1 if length is odd

        a_middle = a_middle + 1

    if len(b) % 2 == 1:

        b_middle = b_middle + 1 

    return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]


    # LAB(replace solution)

    # return

    # LAB(end solution)

error message

Traceback (most recent call last):

  File "/Users/eunguru/Source/Python/Google_BasicEx/solution/string2.py", line 106, in <module>

    main()

  File "/Users/eunguru/Source/Python/Google_BasicEx/solution/string2.py", line 101, in main

    test(front_back('abcd', 'xy'), 'abxcdy')

  File "/Users/eunguru/Source/Python/Google_BasicEx/solution/string2.py", line 68, in front_back

    return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]

TypeError: slice indices must be integers or None or have an __index__ method


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

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 #2 List  (0) 2014.12.11
Python 2.x에서 3.x로 변경  (0) 2014.12.03
튜플 자료형 특이사항  (0) 2014.10.19
자료형과 연산자  (0) 2014.10.18
Hello Python  (0) 2014.10.15
Mac에서 python 3. x 버전 사용 하기  (3) 2014.10.12