Published 9月 05, 2018 by with 0 comment

習題25 - 更多更多的練習


用Notepad++打下列的程式碼,
另存為ex25.py. 我附上中文注釋方便好讀.
# split就是以(" ")空格為標記, 遇到標記的符號(空格)就空一格.
如果我用('a')為標記, 整句話只有遇到a 才會變成空格
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(" ")
    return words

# sorted 就是重新排序
# 但這裡是根據參數words來排, 也就是上面函數break_words做完的結果來排序
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

# pop 取出第一個字, 取完後就沒有這個字了
# 但這裡是根據參數words來排, 也就是第一個函數break_words做完的結果來取出
def print_first_word(words):
    """Print the first word after popping it off. """
    word = words.pop(0)
    print(word)

# pop 取出倒數第一個字, 取完後就沒有這個字了.
# 但這裡是根據參數words來排, 也就是第一個函數break_words做完的結果來取出.
def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print(word)

#這個組合了兩個函數, 先把參數(sentence)代入函數break_words做掉(用空格分開), 得到的結果為words,
#然後把words做為參數, 代入函數sort_words做掉(排序).
def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

# 這函數print_first_and_last是把參數(sentence), 用break_words處理(空格分開),
# 然後再用函數print_first_word印出第一個字,
# 然後再用函數print_last_word印出倒數第一個字.
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

# 這函數print_first_and_last_sorted是把參數(sentence), 用sort_sentence處理(空格分開後, 再排序),
# 然後再用函數print_first_word印出第一個字,
# 然後再用函數print_last_word印出倒數第一個字.
def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


然後用Windows的cmd, 執行python打開它.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>>

完成


最初發表 / 最後更新: 2018.09.05 / 2018.09.05

0 comments:

張貼留言