1.七段數碼管繪製
七段數碼管是一種展示數字的有效方式。
請用程序繪製當前系統時間對應的七段數碼管,效果如下:
要求如下:
(1) 使用 time 庫獲得系統當前時間,格式如下:20190411
(2) 繪製對應的七段數碼管
(3) 數碼管風格不限
import turtle as t
import time
def drawGap(): #繪製數碼管間隔
t.penup()
t.fd(5)
def drawLine(draw): #繪製單段數碼管
t.pendown() if draw else t.penup()#<表達式1> if <條件> else <表達式2>
t.fd(40)
drawGap()
t.right(90)
def drawDigit(digit): #根據數字繪製七段數碼管
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,6,8] else drawLine(False)
t.left(90)
drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
t.left(180)
t.penup() #爲繪製後續數字確定位置
t.fd(20) #爲繪製後續數字確定位置
def drawDate(date): #date爲日期,格式爲'%Y-%m=%d+'
t.pencolor("red")
for i in date:
drawDigit(eval(i))
def main():
t.setup(800,350,200,200)
t.penup()
t.fd(-300)
t.pensize(5)
drawDate(time.strftime('%Y%m%d',time.gmtime()))
t.hideturtle()
t.done()
main()
2.科赫雪花小包裹
科赫曲線,也叫雪花曲線。繪製科赫曲線。
import turtle
def koch(size, n): #每一段直線的長度size;階數n
if n == 0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
def main(level):
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200, 100)
turtle.pendown()
turtle.pensize(2)
koch(400,level) #長度600像素;level階
turtle.hideturtle()
try:
level = eval(input("請輸入科赫曲線的階: "))
main(level)
except:
print("輸入錯誤")
3.任意累積
描述
計算任意個輸入數字的乘積。
輸入
示例1:1,2,3,4
輸出
示例1: 24
#累積
def cmul(a,*b): #可變參數*b,參數數量不確定
s = a
for i in b:
s *= i
return s
print(eval("cmul({})".format(input())))
4.斐波那契數列計算
描述
根據編程模板補充代碼,計算斐波那契數列的值,具體功能如下:
- 獲取用戶輸入整數N,其中,N爲正整數
- 計算斐波那契數列的值
如果將斐波那契數列表示爲fbi(N),對於整數N,值如下:
fbi(1)和fbi(2)的值是1,當N>2時,fbi(N) = fbi(N-1) + fbi(N-2)
請採用遞歸方式編寫。
輸入
示例1:4
輸出
示例1:3
#斐波那契數列 fbi(n)=fbi(n-1)+fbi(n-2)
def fbi(n):
if n == 1 or n == 2:
return 1
else:
return fbi(n-1) + fbi(n-2)
n = eval(input())
print(fbi(n))
5.漢諾塔實踐
描述
有三個圓柱A、B、C,初始時A上有N個圓盤,N由用戶輸入給出,最終移動到圓柱C上。
每次移動步驟的表達方式示例如下:[STEP 10] A->C。其中,STEP是步驟序號,寬度爲4個字符,右對齊。
輸入格式
一個整數
示例1:3
輸出格式
每個步驟一行,每行參考格式如下:[STEP 10] A->C
示例1:
[STEP 1] A->C
[STEP 2] A->B
[STEP 3] C->B
[STEP 4] A->C
[STEP 5] B->A
[STEP 6] B->C
[STEP 7] A->C
#漢諾塔
steps = 0
def hanoi(src, des, mid, n): #源柱子、目的柱子、中間的過渡柱子、圓盤的數量
global steps
if n == 1:
steps += 1
print("[STEP{:>4}] {}->{}".format(steps, src, des))
else:
hanoi(src, mid, des, n-1)
steps += 1
print("[STEP{:>4}] {}->{}".format(steps, src, des))
hanoi(mid, des, src, n-1)
N = eval(input())
hanoi("A", "C", "B", N)