《 程式設計導論——以Python為舟》學習筆記(一)
阿新 • • 發佈:2018-11-09
春遊坐車問題
【問題描述】有學生70人組織春遊,要租用大巴,每輛大巴可承載30人,至少要多少輛大巴可裝載所有學生?,請問每輛車要裝載多少學生才能讓每輛車的人數較為平均的分佈,請輸出每輛車的所載人數。
【解題思路】先求得最少需要多少輛大巴,得到大巴數目後需要儘量將學生平均分到所有大巴上,所以可以用整除運算來求得每輛車平均裝載人數。
student = 70; seat = 30
num = student // seat
r = student % seat
if r != 0: #如果在學生坐滿大巴後還有一些學生
num = num + 1
ave = student // num
if r == 0: #如果學生恰好能將大巴都坐滿
print(num,"buses. Each has ",ave," students.")
else:
lastbus = student-(num-1)*ave
print(num,"buses. One bus has ",lastbus," students.")
print("Each of other buses has ",ave," students.")
求二維線性方程組
【問題描述】已知二維線性方程組如下,其中, a0 、a1 、b0 、b1 、c0和c1為已知,求未知量x和y的值。
#方程組係數
a0, b0 , c0 = 3, 1 ,4
a1, b1 , c1 = 0, -2, -1
#等式1兩邊同時擴大a1倍
a2, b2 , c2 = a0 * a1, b0 * a1, c0 * a1
#等式2兩邊同時擴大a0倍
a3, b3 , c3 = a1 * a0, b1 * a0, c1 * a0
#等式1減等式2
a , b, c = a2 -a3, b2 - b3, c2- c3
if ((b == 0) and (c == 0)):
print("Infinite Solution!")
elif (b == 0):
print("No Solution!")
elif ( a0 == 0):
y = c0 / b0
x = (c1 - b1 * y) / a1
print("x =%.2f , y = %.2f" % (x, y))
elif (a1 == 0):
y = c1 / b1
x = (c0 - b0 *y) / a0
print("x =%.2f , y = %.2f" % (x, y))
else:
y = c / b
x = (c0 - b0 * y) / a0
print("x = %.2f, y = %.2f" % (x, y))