零基礎學習Python 作業 第6章

————CH06 homework————

0 Python 的 floor 除法現在使用 “//” 實現,那 3.0 // 2.0 您目測會顯示什麼內容呢?

Answer:1.0 floor(向下取整)

1 a < b < c 事實上是等於?

Answer: (a < b) and (b < c)

2 不使用 IDLE,你可以輕鬆說出 5 ** -2 的值嗎?

Answer: 1/25 = 0.04

3 如何簡單判斷一個數是奇數還是偶數?

Answer:

if (num % 2) == 0:
    print(num, '是偶數')
else:
    print(num, '是奇數')

4 請用最快速度說出答案:not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9

Answer: 4
優先級順序:not >> and >> or
在考慮短路邏輯 4 and 5 = 5, 3 or 4 = 3
故: 0 or 0 or 4 or 6 or 9 = 4

5 還記得我們上節課那個求閏年的作業嗎?
如果還沒有學到“求餘”操作,還記得用什麼方法可以“委曲求全”代替“%”的功能呢?

Answer: 因爲int()是向下取整,故使用int(year/4)


Practice


0 請寫一個程序打印出 0~100 所有的奇數。

code:

print('----------Generate odd number in the range of 0~100----------')
i = 0
while i <= 100:
    if (i % 2) != 0:
        print(i, end = ' ')
    i += 1

1 我們說過現在的 Python 可以計算很大很大的數據,
但是……真正的大數據計算可是要靠剛剛的硬件滴,不妨寫一個小代碼,讓你的計算機爲之崩潰?

print(4**40) python IDLE關了……..

2 愛因斯坦曾出過這樣一道有趣的數學題:有一個長階梯,若每步上2階,最後剩1階;
若每步上3階,最後剩2階;若每步上5階,最後剩4階;若每步上6階,最後剩5階;
只有每步上7階,最後剛好一階也不剩。(小甲魚溫馨提示:步子太大真的容易扯着蛋~~~)

題目:請編程求解該階梯至少有多少階?

n % 2 = 1
n % 3 = 2
n % 5 = 4
n % 6 = 5
n % 7 = 0

code:

print('----------Seeking the total order of steps----------')
num = 7   # initialization
i = 1     # initialization
while (num % 7) == 0:
    if (num % 2 == 1) and (num % 3 == 2) and (num % 5 == 4) and (num % 6 == 5):
        print('The total steps is ', num)
        break
    else:
        i += 1
        num = 7 * i

print('Thanks')

result:

----------Seeking the total order of steps----------
The total steps is  119
Thanks

優化後的版本:

print('----------Seeking the total order of steps----------')
num = 7   # initialization
i = 1     # initialization
flag = 0  # initialization

# 假設循環計算100次
while i <= 100:
    if (num % 2 == 1) and (num % 3 == 2) and (num % 5 == 4) and (num % 6 == 5):
        flag = 1
        break
    else:
        num = 7 * (i + 1)
    i += 1

if flag == 1:
    print('The total steps is ', num)
else:
    print('100 calculations not found')

result:

----------Seeking the total order of steps----------
The total steps is  119
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章