01/10/2018, 10:00

Nhờ các bác thông não Python

Em có 1 đoạn code như dưới đây: (được trích từ Learn Python the Hard Way - Ex 25)

    def break_words(stuff):
        words = stuff.split(' ')
        return words

    def sort_words(words):
        return sorted(words)

    def print_first_word(words):
        word = words.pop(0)
        print word

    def print_last_word(words):
        word = words.pop(-1)
        print word

    def sort_sentence(sentence):
        words = break_words(sentence)
        return sort_words(words)

    def print_first_and_last(sentence):
        words = break_words(sentence)
        print_first_word(words)
        print_last_word(words)

    def print_first_and_last_sorted(sentence):
        words = sort_sentence(sentence)

Với sentence = “All good things come to those who wait”

Theo như em hiểu thì khi chạy hàm def cuối cùng của đoạn code này, tức là:

    def print_first_and_last_sorted(sentence):
        words = sort_sentence(sentence)

thì các từ trong tập hợp của biến words sẽ được sắp xếp theo thứ tự. Tuy nhiên sau đó em in biến words ra thì thấy các từ trong biến này vẫn chưa được sắp xếp (Như trong hình). Xin các bác chỉ giáo cho. Em xin chân thành cảm ơn ạ!

Khoa NTA viết 12:14 ngày 01/10/2018

Bạn chép thiếu hàm của người ta kìa:

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)

Các hàm trên không hề tác động đến biến toàn cục words nên biến này không có thay đổi gì cả là đúng rồi :v Hàm trên chỉ in ra màn hình thôi mà, đâu có trả về hay sắp xếp gì ở biến toàn cục đâu mà bạn chờ nó sắp xếp?

Bạn nên chụp hết các dòng bạn đã gõ trong interpreter, biết đâu bạn gõ thiếu thì sao?

Gió viết 12:01 ngày 01/10/2018

hàm sorted không làm thay đổi list ban đầu. Muốn sort list ban đầu thì dùng sentence.sort()

Vu Hoang Tung viết 12:07 ngày 01/10/2018

Cám ơn bác. Sau khi đọc kỹ cmt của bác và đoạn code thì não em cũng thông rồi ạ.

Vu Hoang Tung viết 12:03 ngày 01/10/2018

Em cám ơn bác Gió ạ!

Bài liên quan
0