2016年7月14日木曜日

開発環境

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 10.(Lists)のExercises 10-9.(No. 2366)を取り組んでみる。

Exercises 10-9.(No. 2366)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time

# out: []
# out.append(word1)
# out: [word1]
# out.append(word2)
# out: [word1, word2]
# ...


def words2list_append(filename):
    out = []
    with open(filename) as f:
        for word in f:
            word = word.strip()
            out.append(word)
    return out

# this takes longer to run.
# out: []
# [word1] # (creates a new list)
# [] + [word1] # (creates a new list)
# out: [word1]
# [word2] # (creates a new list)
# [word1] + [word2] # (creates a new list)
# out: [word1, word2]
# ...


def words2list_add(filename):
    out = []
    with open(filename) as f:
        for word in f:
            word = word.strip()
            out = out + [word]
    return out

if __name__ == '__main__':
    filename = 'words.txt'
    for func in [words2list_append, words2list_add]:
        t = time.time()
        func(filename)
        t = time.time() - t
        print('{0}: {1}秒'.format(func.__name__, t))

入出力結果(Terminal, IPython)

$ ./sample9.py
words2list_append: 0.19927096366882324秒
words2list_add: 243.23818492889404秒
$

0 コメント:

コメントを投稿