嗨嗨,感謝閱讀【python入門教室】的讀者, 為了讓大家能夠溫故知新, 小馬的【python入門教室】幾乎每篇後都有課後練習供讀者學習 這邊默默記錄一下每題的參考解答, 供讀者練習過後可以對答案 也...
嗨嗨,感谢阅读【python入门教室】的读者,
为了让大家能够温故知新,
小马的【python入门教室】几乎每篇后都有课后练习供读者学习
这边默默记录一下每题的参考解答,
供读者练习过后可以对答案
也给小马自己做为备忘
建议读者若想阅读【python入门教室】学习,
题目先自己思考过,
真的想不出来再来对答案
【python入门教室】(1) 带你一步步进入python的世界
习题- 8kyu- Count the Monkeys!
def monkey_count(n):
return range(1, n+1) #或写list(range(1, n+1))
习题- 8kyu- Can we divide it?
def is_divide_by(number, a, b):
return number % a == 0 and number % b == 0
【python入门教室】(2) 几个好用的内建函数介绍- max(), min(), len(),sorted(),sum(),abs(), pow()
习题- 7kyu- Odd or Even?
def odd_or_even(arr):
return 'odd' if sum(arr) % 2 else 'even'
习题- 7kyu- No Loops 1 - Small enough?
def small_enough(a, limit):
return max(a) <= limit
习题- 7kyu- Are the numbers in order?
def in_asc_order(arr):
return sorted(arr) == arr
【python入门教室】(3) 列表和字串也想做加法和乘法?
习题: 密码不外漏
def hidePassword(psd):
return '*' * len(psd)
【python入门教室】(4) 超完整的python字串函数用法统整
习题: 判断合法的变数名称
def isLegal(s):
return s.replace('_','').isalnum() and not s[0].isdigit()
【python入门教室】(5) 内建型态介绍: 元组tuple(),字典dict(), 集合set()
习题- 多啦a梦的口袋
def countItem(pocket):
return len(set(pocket))
习题- 7kyu- Number of Decimal Digits
def digits(n):
return len(str(n))
习题- 7kyu- Isograms
def is_isogram(string):
string = string.lower()
return len(set(string)) == len(string)
【python入门教室】(6) python 的切片语法介绍
习题- 明日歌星
def judge(scores):
return sorted(scores)[1:-1]
【python入门教室】(7) python 的列表生成式语法介绍
习题- 7kyu- Sum of a sequence
def sequence_sum(begin_number, end_number, step):
return sum(range(begin_number, end_number+1, step))
习题- 韩信的千军万马
def soldiers(m, n):
return [i for i in range(m+1, n) if i%3==2 and i%5==3 and i%7==2]
【python入门教室】(8) 如果你愿意一层一层一层 的剥开繁琐逻辑 (化简冗长的if-else教学)
习题- 今天星期几
t = int(input())
S = ["日","一","二","三","四","五","六]
print("今天星期"+S[t])
习题- 判断闰年
def isLeapYear(n):
return n%4==0 and n%100!=0 or n%400==0
【python入门教室】(9) python3.6版后的新特性: f-string,方便在字串内放变数
习题- 6kyu- Create Phone Number
def create_phone_number(n):
return f"({n[0]}{n[1]}{n[2]}) {n[3]}{n[4]}{n[5]}-{n[6]}{n[7]}{n[8]}{n[9]}"
【python入门教室】(10) 认识python的生成器与迭代器
(暂无习题)
【python入门教室】(11) 介绍内建高阶函数- map, filter, reduce
习题- 读懂程式码
答: 使用者可以输入数字(以空白隔开),并将输入的数字做总。如果使用者输入非数字字元,会无法做加法而出错
【python入门教室】(12) 魔镜啊魔镜,谁是列表中最美丽的元素? (任意规则的排序方法)
习题: 依指定规则重排字串
s = input() #测试範例输入 Sorting1234
L=sorted(s, key= lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), s.index(x)))
print("".join(L)) #预期结果: ortingS1324
解说:
元组中将字串中的每个字元依序映射出四个值(排序的优先权):
「是否为数字」、「若是数字是否为偶数」、「是否为大写字母」、「在原字串的位置」。
【python入门教室】(13) 内建函数any(), all(), zip()介绍
习题: 矩阵向左旋转
def rotateLeft(arr):
A = [a[::-1] for a in arr] #水平翻转
return list(map(list,(zip(*A)))) #行列互换,再利用map函数将zip内的元组转列表
解说: 先水平翻转,再行列互换
123 (水平翻转) 321 (行列互换) 369
456 => 654 => 258
789 987 147
【python入门教室】(14) 随心所欲的自定义函数参数介绍
修正的程式:
(函数只用一次的状况)
mulFuncs = (lambda x: x*i for i in range(1, 6))
for func in mulFuncs:
print(func(2))
(函数需要存下来用多次的状况)
mulFuncs = [lambda x, m=i: x*m for i in range(1,6)]
for func in mulFuncs:
print(func(2))
【python入门教室】(15) 黑魔法,recursion,recursion depon (递迴函数的介绍)
习题- 计算正整数平方和
def f(n):
return 1 if n==1 else f(n-1) + pow(n, 2)
def f(n):
return sum(pow(i, 2) for i in range(n+1))
【python入门教室】(16) python内建模组总览,介绍time, math, statistics模组
(暂无习题)
【python入门教室】(17) 模拟掷骰子,介绍random模组
习题- 骰子大比拼
参考程式码:
import random
def dice(n):
return random.randint(1,n)
def ex():
X = dice(6) + dice(6)
Y = dice(12)
return X>Y
def simulate(experiment, times):
success=0
for i in range(times):
if experiment():
success+=1
return success/times
print(simulate(ex,10000))
其实本题机率在数学上的值正好就是50%,
不论你选哪组骰子,你和玛丽都是各自一半机率获胜,
这个游戏是公平的
【python入门教室】(18) python内建模组collections模组介绍,选择容器的艺术
习题- 统计每个单字出现的次数
def trans(article):
return ''.join([c.lower() if c.isalpha() else ' ' for c in article])
article = "How are you? I am fine, thank you. And you you you you you? You are so smart."
article = trans(article) #将字串全部变成小写,并去除标点符号
print(article) #测试印出转换后的字串
count = Counter(article.split())
print(count) #印出每个字出现的次数
【python入门教室】(19) python内建模组itertools模组介绍,趣味的排列组合
习题- forty+ten+ten=sixty
等式「FORTY+TEN+TEN=SIXTY」只有唯一组解:
29786 + 850 + 850 = 31486
範例程式(因是暴力穷举,程式需等待一段时间乃正常现象):
from itertools import permutations
# 将元组转整数,例如(1,2,3)-> 123
def tToN(Tuple):
return int(''.join(map(str,Tuple)))
def check(Tuple):
FORTY = tToN(Tuple[:5])
TEN = tToN(Tuple[3:4]+Tuple[5:7])
SIXTY = tToN(Tuple[-3:]+Tuple[3:5])
return FORTY+TEN+TEN == SIXTY
for p in permutations(range(0,10),10):
if check(p):
FORTY = tToN(p[:5])
TEN = tToN(p[3:4]+p[5:7])
SIXTY = tToN(p[-3:]+p[3:5])
print(f"{FORTY} + {TEN} + {TEN} = {SIXTY}")
习题- 4kyu- The observed PIN
import itertools
possibles={'0':'08', '1':'124','2':'1235','3':'236','4':'1457',\
'5':'24568','6':'3569','7':'478','8':'57890','9':'689'}
def get_pins(observed):
P= itertools.product(*map(lambda x: possibles[x],observed))
return list(map(lambda x: ''.join(x),P))