Information Engineering Exercise II 月曜日3~4限目 3rd-4th Period, Mon. 担当:北川 晃(技術教育コース) A. Kitagawa (Technology Education)
プログラムの作成(Editing program)
プログラムの作成の約束事1(Convention for editing program 1) ‘#’記号から始まる行はコメント行と見なされる. (A statement starting with a symbol ‘#’ is regarded as a comment. ) 日本語文字を使う場合(コメント行であっても)は,プログラムの最初に ‘# coding: utf-8’ という行を入れる.これがない場合は,実行の際にエラーが表示される. (When you use Japanese codes, insert the following statement at the head of the program: ‘# coding: utf-8’ If this statement is not contained, some error message is displayed. )
プログラムの作成の約束事2(Convention for editing program 2) 各行の最初に,必要がなければ空白を入れてはいけない. 行頭の空白は文法的なブロックであると見なされる. (In the beginning of each statement, blank symbols cannot be inserted with no intention (They are regarded as a grammatical block). ) 一行が長くなる場合は,バックスラッシュ’\’を入れて改行することができる. (A long statement in a line can be broken with a backslash (In Japan, backslash is assigned with a Japanese symbol ‘\’). )
練習:四則演算(Exercise: four basic arithmetic operations) 半径rの円の円周ℓと面積Sを計算するプログラムを作れ. 円周率をπ=3.1415926とする. (Make a program for calculating the circumstance ℓ and area S of a circle of radius r. Let the circular constant be pi=3.1415926. ) r=3.0 pi=3.1415926 l=2*pi*r s=pi*r**2 print 'l=',l print 's=',s
練習:四則演算(Exercise: four basic arithmetic operations) 「3時21分50秒から8時17分46秒までは何時間 何分 何秒か」 というように,一般に時分秒の組で表された二つの時刻の 間の時間を計算したい. H1時M1分S1秒 から H2時M2分S2秒 までの時間 H3時間M3分S3秒を計算して表示させるプログラムを作れ. (What hours, what minutes, and what seconds is it, from 3:21:50 to 8:17:46? Calculate it by programming. )
考え方(Algorithm) 時刻をすべて秒単位に換算してする. (Convert a time in the second scale. ) t=3600×(hour)+60×(minute)+(second) 秒単位の大きな数tから時分秒への換算は, (Conversion to style (hour):(minute):(second) is: tを3600で割る……………… その商が「時間」 (The quotient of t and 3600 is ‘hour’) 余りを60で割る……………… その商が「分」 (The quotient of the remainder and 60 is ‘minute’. ) 余りが「秒」 (The remainder is ‘second’. )
答え(Answer) h1=3 m1=21 s1=50 h2=8 m2=17 s2=46 t1=3600*h1+60*m1+s1 t=t2-t1 h3=t/3600 remainder=t-h3*3600 m3=remainder/60 s3=remainder-m3*60 Start time print 'Elapsed time is',h3,':',m3,':',s3 Finish time Conversion of time in the second scale Time difference Calculation of ‘hour’ Calculation of ‘minute’ Calculation of ‘second’
数学で用いる関数(Functions in mathematics) (If ‘math’ module is imported, we can use mathematical functions. ) pi: circular constant e: Napier's constant sqrt(x): square root of x. sin(x), cos(x), tan(x): sinusoidal functions of x. fabs(x): Absolute value of x. exp(x): Exponential function of x. log(x,b): logarithmic function with base b. import math a = math.sqrt(2) b = math.fabs(-5) c = math.cos(pi) d = math.log(a,e)
while文(while statement) 条件式が成り立っている間,処理を繰り返す構文. (Processes are repeated during a condition holds. ) Comparative operators: True or False x == y: True when x is equal to y. x != y: True when x is not equal to y. x < y: True when x is less than y. x > y: True when x is greater than y. x <= y: True when x is not greater than y. x >= y: True when x is not less than y. while condition : process 1 process 2 … Indent Colon Maybe, ‘before judgement loop’ only?
This block is repeated while 1≤𝑖≤10. while文の例(Example of while statement) 1~nの和を求めよ. (Calculate summation of 1 to an integer n. ) Initial step of iteration s=0 n=10 i=1 while i<=n: s=s+i i=i+1 print 's=',s This block is repeated while 1≤𝑖≤10.
ユークリッドの互除法(Euclidean algorithm) ユークリッドの互除法を用いて,2つの正整数a,b(a>b)の最大公約数を求めよ. (Calculate G. C. M. of positive values a and b (a>b) using Euclidean algorithm. ) When the quotient of 𝑎 and 𝑏 and its remainder are 𝑞 and 𝑟, respectively, the G. C. M. (Greatest Common Measure) of 𝑎 and 𝑏 is equal to that of 𝑏 and 𝑟. 例:1058と943の最大公約数 (G. C. M. of 1058 and 943) 1058/943 =1 remainder 115 (G. C. M of 943 and 115) 943/115 =8 remainder 23 (G. C. M. of 115 and 23) 115/23 =5 remainder 0 Repeat this procedure until reminder becomes 0. Final divisor is G. C. M.
ユークリッドの互除法のアルゴリズム(Algorithm) 2つの整数aとbを読み込む. (Read two integers a and b. ) a→m,b→nを代入. (Substitute a and b to m and n, respectively. ) ℓ=(m÷nのあまり)を計算. (Calculate remainder of m/n as ℓ. ) (n,ℓ)を新たな(m,n)として代入. (Substitute (n,ℓ) as a new (m,n). ) 手順3と4を,あまりℓが0になるまで繰り返す. (Repeat 3rd and 4th steps until remainder ℓ becomes 0. ) このときのnを最大公約数として書き出す. (Write the final n as G. C. M. )
答え(Answer) a=1058 b=943 m=a n=b ℓ=m%n while ℓ!=0: m=n n=ℓ print 'G. C. M. of',a,'and',b,'is',n Calculation of remainder This block is repeated until the remainder becomes 0.
for~in 文(for~in statement) 特定の回数,処理を繰り返す構文. (Iteration of processes for a given number of times. ) range()関数は等差数列を要素とするリストを生成する. ‘range()’ is a function that gives list with components of an arithmetic sequence. range(3): 0~2 range(1,8): 1~7 range(1, 8, 2): 1, 3, 5, 7 range([first term, ]final term[, step]) For example, i for variable in range(3): process 1 process 2 … Indent Colon
for~in 文の例(Example of for~in statement) (Calculate summation of 1 to an integer n. ) n=10 s=0 for i in range(1,n+1): s=s+i print s 1~10
(an approximation value of square root of a) 平方根の計算(A square root of integers) a=1, 2, …, 50に対して,以下の手順で平方根 𝑎 を計算せよ. (Calculate a square root of integer a(=1, 2, …, 50) in the following way. ) : math.sqrt(a) aの平方根の近似値: (an approximation value of square root of a) 補正値(correction):
平方根の計算:アルゴリズム 整数1≤𝑎≤50について,以下の手順を繰り返す. (Repeat following steps for integers 1≤𝑎≤50. ) 初期値として, 𝑥 0 = roota=1を代入する. (As an initial value, substitute 𝑥 0 =roota=1. ) 補正値𝑐= 1 2 𝑎 𝑥 0 − 𝑥 0 の計算を行う. (Calculate a correction 𝑐= 1 2 𝑎 𝑥 0 − 𝑥 0 . ) roota=roota+cにより補正を行う.(Correct the value: roota =roota+c. ) 補正した値の相対値 𝑐 𝑥 0 を設定した値𝜀と比較して小さくなるまで補正を繰り返す. (Repeat correction until 𝑐 𝑥 0 <𝜀. ) for~in 文 while 文 𝜀= 10 −6
During 𝑐 𝑥 0 >𝜀, this block is repeated. 答え(Answer) Import of math module import math eps=0.000001 for a in range (1,51): roota=1.0 c=1.0 while math.fabs(c)/roota>eps: c=(a/roota-roota)/2 roota=roota+c print 'sqrt(',a,')=',roota 1~50 During 𝑐 𝑥 0 >𝜀, this block is repeated.
ファイル操作1(File operation 1) パイソン上で使うデータを外部ファイルから読み込んだり, 外部ファイルへ書き出したりできる. (Python program can read data from an external file or write data to an external file. ) ‘f’をパイソン上でのファイルを表す. (‘f’ denotes file to read in a Python program. ) ‘filename’にはファイルのパスも書ける. (The path of the external file can be written at the filename. ) データの読み込み(Reading data): f = open(“filename”,”r”) s = f.read() f.close() readline Python reads data: read(): to the end of file and return it as a string. readline(): to the end of line and return it as a string. readlines(): and return it as a list the element of which correspond to each line, respectively. First data Second data Third data read list readlines
ファイル操作2(File operation 2) データの書き込み読み込み(Writing data): ‘w’の場合は既存の内容をすべて 破棄して新たに書き込む. (For ‘w’, all data in the target file is deleted, and the string is newly written.) ‘a’の場合は,既存のファイルに追記する. (For ‘a’, the string is appended at the end of the target file. f = open(“filename”,”w”) s = f.write(“str”) f.close() with~as文(with~as statement) ファイルは自動的に閉じられる. with open(“filename”, “r”) as f: s = f.read() with open(“filename”, “w”) as f: f.write(“str”) コロン(:)の後,インデントの行はブロック構造をなす (A block structure: Colon and indents) ファイルは自動的に閉じられる.(The target file is automatically closed. ) 読み込みで,ファイルが存在しない場合でもエラーが出ない. インデント (indent)
データの型の変換(Conversion of data type) ファイルから読み込む値,ファイルへ書き出す値は文字列として扱われる. (Data read from and written to an external file is treated as strings. ) 読み込んだ値を数値として扱いたい場合,また数値をファイルに書き出す場合は, 次の型変換の組み込み関数を用いる. (If we use the data that is read in as an value, or If we need to write values to an file, we need to convert the data type with following built-in functions. ) float(): 整数,文字列(Integer, string)⇒浮動小数点数(Floating-point number) int(): 浮動小数点数,文字列(Floating-point number, string)⇒整数(Integer) str(): 数値(Value)⇒文字列(String)
文字列の結合,改行コード(Connection of strings, linefeed code) 文字列は’+’記号を用いて結合することができる. (Strings can be connected with ‘+’ symbol. ) >>> a = ‘Python’ >>> b = ‘ in Raspberry Pi’ >>> a + b ‘Python in Raspberry Pi’ 文字列に’\n’を挿入することで,改行することができる. (Inserting ‘\n’, we have linefeed in a string. ) >>> a = ‘Python \n in Raspberry Pi’ >>> print a Python in Raspberry Pi
ファイル操作の練習(Exercise of file operations 1) テキストエディタでドキュメント内に”reading_file.txt”を作成し, パイソン上で変数’s’に全体を読み込んでみよ. ‘s1’,’s2’,s3’に順に一行目,二行目,三行目を 数値として読み込むためにはどうすればよいか. (Create a file named as “reading_file.txt” in your document folder with notepad, and read entire of the file to a variable ‘s’. Then, read the first, second, and third lines to variables ‘s1’, ‘s2’, and ‘s3’ as values, respectively. ) reading_file.txt 1 2.0 -3.0
ファイル操作の練習(Exercise of file operations 2) f1 = open(“c:/Users/####/Documents/reading_file.txt”,”r”) s = f1.read() f1.close() print s f2 = open(“c:/Users/####/Documents/reading_file.txt”,”r”) s1 = int(f2.readline()) s2 = float(f2.readline()) s3 = float(f2.readline()) f2.close() print s1,s2,s3 三回繰り返す. (Repeat three times. ) with open (“c:/…/reading_file.txt”,”r”) as f1: s = f1.read() print s with open (“c:/…/reading_file.txt”,”r”) as f2: s1 = int(f2.readline()) s2 = float(f2.readline()) s3 = float(f2.readline()) print s1,s2,s3 Alternatively,
ファイル操作の練習(Exercise of file operations) それぞれ変数が数値s1=1,s2=2.0,s3=-3.0とする.s1の値を ドキュメント内の新規ファイル”writing_file.txt”に書き込んでみよ. また,同じファイルにs2,s3の値を追記せよ. (Let s1, s2, and s3 be values 1, 2.0, and -3.0, respectively. Write the string s1 to a new file in your document folder. Then append strings s2 and s3 to the same file. )
ファイル操作の練習(Exercise of file operations) s1 = str(1) s2 = str(2.0) s3 = str(-3.0) f = open(“c:/…/writing_file.txt”,”w”) f.write(s1+’\n’) f.close() f = open(“c:/…/writing_file.txt”,”a”) f.write(s2+’\n’) f.write(s3+’\n’) Alternatively, s1 = str(1) s2 = str(2.0) s3 = str(-3.0) with open (“c:/…/writing_file.txt”,”w”) as f: f.write(s1+’\n’) with open (“c:/…/writing_file.txt”,”a”) as f: f.write(s2+’\n’) f.write(s3+’\n’) 改行記号 (linefeed code)