Try   HackMD

無線及寬頻網路HW1 1102951

第一題

執行畫面

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

程式碼

python程式碼如下

import math def is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True with open("prime.txt", "w") as f: f.write(f"The following numbers are prime between 1 to 1000 :") for i in range(1, 1001): if is_prime(i): f.write(f" {i},")

TCL程式碼如下

set prime_start 1 set prime_end 1000 proc is_prime {n} { if {$n < 2} { return 0 } for {set i 2} {$i < $n} {incr i 1} { if {$n % $i == 0} { return 0 } } return 1 } set f [open "prime.txt" "w"] puts $f "The following numbers are prime between 1 to 1000 :" for {set j $prime_start} {$j <= $prime_end} {incr j 1} { if {[is_prime $j]} { puts $f " $j," } } close $f

簡要說明

我將TCL與python程式碼都寫了一個is_prime函數來驗證該數是否為質數,如果是,則回傳1(true),反之為0(false),不過不同的是tcl程式碼直接遍歷1 to n來算出是否為質數,而python程式碼則是透過math中的函數sqrt(n)來降低運算次數,最後再寫入prime.txt中

TCL vs Python

變數定義與使用

TCL

使用 set 定義變數,且使用 $ 來引用變數值,如set i 1$i

Python

直接定義變數,如i = 1,且不需要在引用變數時加符號。

循環語法

TCL

使用 for 迴圈,語法為for {初始化} {條件} {增量}

Python

使用 for i in range(),範圍用內建函數range()來生成。

文件操作

TCL

使用openputs來打開文件並寫入數據。

Python

使用with open()write()來進行文件操作。

第二題

第一小題

執行畫面

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

程式碼

$1 == "r" && $3 == "0" && $4 == "2" && $5 == "tcp" {count++} END {print count}

簡要說明

找出第1個欄位為r,第3個欄位為0,第4個欄位為2,第5個欄位為tcp,符合以上條件的記錄數量

答案

601160

第二小題

執行畫面

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

程式碼

$1 == "r" && $3 == "0" && $4 == "2" && $5 == "tcp" {sum += $6} END {print sum}

簡要說明

將符合第一小題的所有記錄,第6個欄位值加總

答案

601160

第三小題

執行畫面

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

程式碼

$1 == "r" && $3 == "0" && $4 == "2" && $5 == "tcp" { if (first == "") { first = $2 } last = $2 } END { diff = last - first print diff }

簡要說明

在所有記錄中,第1個欄位為r,第3個欄位為0,第4個欄位為2,第5個欄位為tcp,符合以上條件的記錄,第一筆與最後一筆記錄,計算出兩者的第2欄位的值相差

答案

2.99981