開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIII部(ステートメント)まとめ演習(プログラムを書き直すのソート)4を解いてみる。
その他参考書籍
4.
コード(TextWrangler)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- L = [1, 2, 4, 8, 16, 32, 64] X = 5 found = i = 0 while not found and i < len(L): if 2 ** X == L[i]: found = 1 else: i = i + 1 if found: print("at index", str(i)) else: print(str(X), "not found") print("a") i = 0 while i < len(L): if 2 ** X == L[i]: print("at index", str(i)) break i += 1 else: print(str(X), "not found") print("b") for x in L: if 2 ** X == x: print("at index", L.index(x)) break else: print(str(X), "not found") print("c") if 2 ** X in L: print("at index", L.index( 2 ** X)) else: print(str(X), "not found") L = [] print("d") for x in range(9): L.append(2 ** x) if 2 ** X in L: print("at index", L.index(2 ** X)) else: print(str(X), "not found")
入出力結果(Terminal)
$ ./sample.py at index 5 a at index 5 b at index 5 c at index 5 d at index 5 $
ちなみにJavaScriptの場合。
コード(TextWrangler)
var result = "a\n"; var L = [1, 2, 4, 8, 16, 32, 64]; var X = 5 var found = i = 0; while(!found && i < L.length){ if(Math.pow(2, X) === L[i]){ found = 1; } else { i++; } } if(found){ result += "at index " + i + "\n"; } else { result += X + " not found\n"; } result += "b\n"; label:{ while(i < L.length){ if(Math.pow(2, X) === L[i]){ result += "at index " + L.indexOf(Math.pow(2, X)) + "\n"; break label; } i++; } result += X + " not found\n"; } result += "c\n"; loop1:{ for(var prop in L){ if(L[prop] === Math.pow(2, X)){ result += "at index " + L.indexOf(Math.pow(2,X)) + "\n"; break loop1; } } result += X + " not found\n"; } result += "d\n"; L = []; for(var i = 0; i <= 8; i++){ L.push(Math.pow(2, i)); } loop2:{ for(var prop in L){ if(L[prop] === Math.pow(2, X)){ result += "at index " + L.indexOf(Math.pow(2,X)) + "\n"; break loop2; } } result += X + " not found\n"; } $('#pre0').text(result);
0 コメント:
コメントを投稿