零基础学习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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章