数据结构与算法 Python 语言实现 课后答案
第 1 章 课后练习答案Excercise1.12 练习R-1.1编写一个Python函数 is_multiple(n, m),用来接收两个整数值 n 和 m,如果 n 是 m 的倍数,即存在整数 i 使得 n = mi,那么函数返回 True,否则返回 False:def is_multiple(n, m):return (n % m == 0)is_multiple(4...
第 1 章 课后练习答案
Excercise1.12 练习
R-1.1 编写一个Python函数 is_multiple(n, m),用来接收两个整数值 n 和 m,如果 n 是 m 的倍数,即存在整数 i 使得 n = mi,那么函数返回 True,否则返回 False:
def is_multiple(n, m):
return (n % m == 0)
is_multiple(4, 2)
True
R-1.2 编写一个Python函数 is_even(k),用来接收一个整数 k,如果 k 是偶数返回 True,否则返回 False。但是,函数中不能使用乘法、除法或取余操作.
def is_even(k):
k = abs(k)
while k > 1:
k = k - 2
return (k == 0)
is_even(10)
True
R-1.3 编写一个Python函数 minmax(data),用来在数的序列中找出最小数和最大数,并以一个长度为 2 的元组的形式返回。注意:不能通过内置函数 min 和 max 来实现。
def minmax(data):
minv = data[0]
maxv = data[0]
for item in data:
if minv > item:
minv = item
if maxv < item:
maxv = item
return minv, maxv
data = [1, 5, 6, 2, 9, 7, 8]
minmax(data)
(1, 9)
R-1.4 编写一个Python函数,用来接收正整数 n,返回 1 ~ n 的平方和。
def SumOfSquare(n):
result = 0
for item in range(n+1):
result += item ** 2
return result
SumOfSquare(4)
30
R-1.5 基于Python的解析语法和内置函数 sum,写一个单独的命令来计算练习R-1.4中的和。
def SumOfSquare2(n):
return sum([x**2 for x in range(n+1)])
def SumOfSquare3(n):
return sum(list(map(lambda x:x**2, range(n+1))))
SumOfSquare3(4)
30
R-1.6 编写一个Python函数,用来接收正整数n,并返回 1 ~ n 中所有的奇数的平方和。
def SquareSumOfOdd(n):
result = 0
for item in range(n+1):
if (item % 2 > 0):
result += item ** 2
return result
SquareSumOfOdd(4)
10
R-1.7 基于Python的解析语法和内置函数 sum,写一个单独的命令来计算练习R-1.6中的和。
def SquareSumOfOdd(n):
return sum((x ** 2 for x in range(n+1) if x % 2 > 0))
SquareSumOfOdd(4)
10
R-1.8 Python 允许负整数作为序列的索引值,如一个长度为 n 的字符串 s,当索引值 -n ≤ \leq ≤ k < 0 时,所指的元素为 s[k],那么求一个正整数索引值 j ⩾ \geqslant ⩾ 0,使得 s[j] 指向的也是相同的元素。
j = n + k
n = 8
k = -2
data = [1, 2, 3, 9, 6, 7, 5, 8]
print(data[k])
j = n + k
print(data[j])
5
5
R-1.9 要生成一个值为 50, 60, 70, 80 的排列,求 range构造函数的参数.
for x in range(5, 9):
print(x * 10, end=" ")
50 60 70 80
list(range(50, 90, 10))
[50, 60, 70, 80]
R-1.10 要生成一个值为 8, 6, 4, 2, 0, -2, -4, -6, -8 的排列,求 range 构造函数中的参数。
list(range(8, -10, -2))
[8, 6, 4, 2, 0, -2, -4, -6, -8]
R-1.11 演示怎样使用 Python 列表解析语法来产生列表 [1, 2, 4, 8, 16, 32, 64, 128, 256].
list(map((lambda x: 2 ** x), range(9)))
[1, 2, 4, 8, 16, 32, 64, 128, 256]
[2 ** x for x in range(9)]
[1, 2, 4, 8, 16, 32, 64, 128, 256]
R-1.12 Python 的 random 模块包括一个函数 choice(data),可以从一个非空序列返回一个随机元素。Random模块还包含一个更基本的 randrange 函数,参数化类似于内置的 range 函数,可以在给定范围内返回一个随机数。只使用 randrange 函数,实现自己的 choice 函数。
def myChoice(data):
import random
randint = random.randrange(len(data))
return data[randint]
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(myChoice(data))
8
创新:
C-1.13 编写一个函数的伪代码描述,该函数用来逆置 n 个整数的列表,使这些以相反的顺序输出,并将该方法与可以实现相同功能的 Python 函数进行比较。
def myReverse(data):
return data[::-1]
data = list(range(10))
myReverse(data)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
data.reverse()
data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
C-1.14 编写一个 Python 函数,用来接收一个整数序列,并判断该序列中是否存在一对乘积是奇数的互不相同的数。
def hasOddMut1(data):
temp = []
for item in data:
if item % 2 != 0 and item not in temp:
temp.append(item)
if len(temp) >= 2:
return True
else:
return False
def hasOddMut2(data):
temp = set()
for item in data:
if item % 2 != 0:
temp.add(item)
return (len(temp) >= 2)
data = [1, 2, 4, 6, 8, 3]
hasOddMut2(data)
True
C-1.15 编写一个 Python 函数,用来接收一个数字序列,并判断是否所有数字都互不相同。
def isDiff1(data):
temp = set()
for item in data:
if item not in temp:
temp.add(item)
else:
return False
return True
def isDiff2(data):
return (len(data) == len(set(data)))
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
isDiff2(data)
True
C-1.16 在1.5.1节 scale 函数的实现中,循环体内执行的命令 data[j] *= factor。我们已经说过这个数字类型是不可变的,操作符 *= 在这种背景下使用是创建一个新的实例(而不是现有实例的变化)。那么 scale 函数是如何实现改变调用者发送的实际参数呢?
C-1.17 1.5.1节 scale 函数的实现如下。它能正常工作吗?请给出原因。
def scale(data, factor):
for val in data:
val = val * factor
data = list(range(9))
print(data)
factor = 3
scale(data, factor)
print(data)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
C-1.18 演示如何使用 Python 列表解析语法来产生列表 [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]。
[x * (x + 1) for x in range(10)]
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
C-1.19 演示如何使用 Python 列表解析语法在不输入所有 26 个英文字母的情况下产生列表 [‘a’, ‘b’, ‘c’,…, ‘z’]。
list(map((lambda x : chr(ord('a') + x)), range(26)))
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’,‘i’, ‘j’, ‘k’, ‘l’,
‘m’, ‘n’, ‘o’,‘p’, ‘q’, ‘r’, ‘s’, ‘t’,‘u’,‘v’, ‘w’,‘x’,‘y’,‘z’]
[chr(ord('a') + x) for x in range(26)]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’,
‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]
C-1.20 Python 的 random 模块包括一个函数 shuffle(data),它可以接受一个元素的列表和一个随机的重新排列元素,以使每个可能的序列发生概率相等。 random 模块还包括一个更基本的函数 randint(a, b),它可以返回一个 a 到 b (包括两个端点)的随机整数。只使用 randint 函数,实现自己的 shuffle 函数。
C-1.21 编写一个Python程序,反复从标准输入读取一行直到抛出 EOFError 异常,然后以相反的顺序输出这些行(用户可以通过键按 Ctrl + D 结束输入)。
def function():
inputStack = []
while True:
try:
temp = input()
inputStack.append(temp)
except KeyboardInterrupt:
while len(inputStack) != 0:
inputStack.pop()
function()
c
C-1.22 编写一个Python程序,用来接收长度为 n 的两个整型数组 a 和 b 并返回数组 a 和 b 的点积。也就是返回一个长度为 n 的数组 c,即 c[i] = a[i] ⋅ \cdot ⋅ b[i], for i = 0, …, n-1.
def myMut1(a, b):
c = []
for i in range(len(a)):
c.append(a[i] * b[i])
return c
def myMut2(a, b):
import numpy as np
return np.array(a) * np.array(b)
a = [1, 2, 3]
b = [4, 5, 6]
myMut2(a ,b)
array([ 4, 10, 18])
C-1.23 给出一个 Python 代码片段的例子,编写一个索引可能越界的元素列表。如果索引越界,程序应该捕获异常结果并打印以下错误消息:“Don’t try buffer overflow attacks in Python!”
def function23(data, i):
try:
return data[i]
except IndexError:
print("Don't try buffer overflow attacks in Python!")
data = [1, 2, 3 ]
function23(data, 3)
Don’t try buffer overflow attacks in Python!
C-1.24 编写一个 Python 函数,计算所给字符串中元音字母的个数。
def numOfCh(string):
temp = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
count = 0
for item in string:
if item in temp:
count += 1
return count
string = "a e i o u"
numOfCh(string)
5
C-1.25 编写一个 Python函数,接收一个表示一个句子的字符串 s,然后返回该字符串的删除了所有标点符号的副本。例如, 给定字符串 “Let’s try, Mike.”,这个函数将返回 “Lets try Mike”。
string = "Let's try, Mike."
re.sub("[.',]", "", string)
‘Lets try Mike’
C-1.26 编写一个程序,需要从控制台输入 3 个整数 a、b、c,并确定它们是否可以在一个正确的算术公式(在给定的顺序)下成立,如“a + b = c” “a = b - c” 或 “a * b = c”。
def function():
temp = input("Please input three numbers!\n")
nums = list(temp.split(" "))
a = int(nums[0])
b = int(nums[1])
c = int(nums[2])
if (a + b == c) or (a == b - c) or ( a * b == c):
return True
else:
return False
function()
Please input three numbers!
1 2 3
True
C-1.27 在 1.8 节中,我们对于计算所给整数的因子时提供了 3 种不同的生成器的实现方法。 1.8 节末尾处的第三种方法是最有效的,但我们注意到,它没有按递增顺序来产生因子。修改生成器,使得其按递增顺序来产生因子,同时保持其性能优势。
def factors(n):
k = 1
temp = []
while k * k < n:
if n % k == 0:
yield k
temp.append(n // k)
k += 1
if k * k == n:
yield k
for item in temp[::-1]:
yield item
list(factors(100))
[1, 2, 4, 5, 10, 20, 25, 50, 100]
C-1.28 在 n 维空间定义一个向量
v
=
(
v
1
,
v
2
,
.
.
.
,
v
n
)
v=(v_{1}, v_{2},... ,v_{n})
v=(v1,v2,...,vn) 的 p 范数, 如下所示:
∣
∣
v
∣
∣
=
v
1
p
+
v
2
p
+
⋅
⋅
⋅
+
v
n
p
p
||v|| = \sqrt[p]{v_{1}^{p} + v_{2}^{p} + ··· + v_{n}^{p}}
∣∣v∣∣=pv1p+v2p+⋅⋅⋅+vnp
对于 p = 2 的特殊情况,这就成了传统的欧几里得范数,表示向量的长度。例如,一个二维向量坐标为 (4,3) 的欧几里得范数为
4
2
+
3
2
=
16
+
9
=
25
=
5
\sqrt{4^{2} + 3^{2}} = \sqrt{16 + 9} = \sqrt{25} = 5
42+32=16+9=25=5。编写 norm 函数,即 norm(v, p),返回向量 v 的 p 范数的值, norm(v),返回向量 v 的欧几里得范数。你可以假定 v 是一个数字列表。
def norm(v, p=2):
import math
return math.sqrt(sum(pow(x, p) for x in v))
v = [3, 4]
norm(v)
5.0
项目:
P-1.29 编写一个 Python 程序,输出由字母 ‘c’,‘a’,‘t’,‘d’,‘o’,‘g’ 组成的所有可能的字符串(每个字母只使用1次)。
def function29():
temp = ['c', 'a', 't', 'd', 'o', 'g']
from itertools import permutations
print(list(map(''.join, permutations(temp))))
function29()
[‘catdog’, ‘catdgo’, ‘catodg’, ‘catogd’, ‘catgdo’, ‘catgod’, ‘cadtog’, ‘cadtgo’, ‘cadotg’, ‘cadogt’, ‘cadgto’, ‘cadgot’, ‘caotdg’, ‘caotgd’, ‘caodtg’, ‘caodgt’, ‘caogtd’, ‘caogdt’, ‘cagtdo’, ‘cagtod’, ‘cagdto’, ‘cagdot’, ‘cagotd’, ‘cagodt’, ‘ctadog’, ‘ctadgo’, ‘ctaodg’, ‘ctaogd’, ‘ctagdo’, ‘ctagod’, ‘ctdaog’, ‘ctdago’, ‘ctdoag’, ‘ctdoga’, ‘ctdgao’, ‘ctdgoa’, ‘ctoadg’, ‘ctoagd’, ‘ctodag’, ‘ctodga’, ‘ctogad’, ‘ctogda’, ‘ctgado’, ‘ctgaod’, ‘ctgdao’, ‘ctgdoa’, ‘ctgoad’, ‘ctgoda’, ‘cdatog’, ‘cdatgo’, ‘cdaotg’, ‘cdaogt’, ‘cdagto’, ‘cdagot’, ‘cdtaog’, ‘cdtago’, ‘cdtoag’, ‘cdtoga’, ‘cdtgao’, ‘cdtgoa’, ‘cdoatg’, ‘cdoagt’, ‘cdotag’, ‘cdotga’, ‘cdogat’, ‘cdogta’, ‘cdgato’, ‘cdgaot’, ‘cdgtao’, ‘cdgtoa’, ‘cdgoat’, ‘cdgota’, ‘coatdg’, ‘coatgd’, ‘coadtg’, ‘coadgt’, ‘coagtd’, ‘coagdt’, ‘cotadg’, ‘cotagd’, ‘cotdag’, ‘cotdga’, ‘cotgad’, ‘cotgda’, ‘codatg’, ‘codagt’, ‘codtag’, ‘codtga’, ‘codgat’, ‘codgta’, ‘cogatd’, ‘cogadt’, ‘cogtad’, ‘cogtda’, ‘cogdat’, ‘cogdta’, ‘cgatdo’, ‘cgatod’, ‘cgadto’, ‘cgadot’, ‘cgaotd’, ‘cgaodt’, ‘cgtado’, ‘cgtaod’, ‘cgtdao’, ‘cgtdoa’, ‘cgtoad’, ‘cgtoda’, ‘cgdato’, ‘cgdaot’, ‘cgdtao’, ‘cgdtoa’, ‘cgdoat’, ‘cgdota’, ‘cgoatd’, ‘cgoadt’, ‘cgotad’, ‘cgotda’, ‘cgodat’, ‘cgodta’, ‘actdog’, ‘actdgo’, ‘actodg’, ‘actogd’, ‘actgdo’, ‘actgod’, ‘acdtog’, ‘acdtgo’, ‘acdotg’, ‘acdogt’, ‘acdgto’, ‘acdgot’, ‘acotdg’, ‘acotgd’, ‘acodtg’, ‘acodgt’, ‘acogtd’, ‘acogdt’, ‘acgtdo’, ‘acgtod’, ‘acgdto’, ‘acgdot’, ‘acgotd’, ‘acgodt’, ‘atcdog’, ‘atcdgo’, ‘atcodg’, ‘atcogd’, ‘atcgdo’, ‘atcgod’, ‘atdcog’, ‘atdcgo’, ‘atdocg’, ‘atdogc’, ‘atdgco’, ‘atdgoc’, ‘atocdg’, ‘atocgd’, ‘atodcg’, ‘atodgc’, ‘atogcd’, ‘atogdc’, ‘atgcdo’, ‘atgcod’, ‘atgdco’, ‘atgdoc’, ‘atgocd’, ‘atgodc’, ‘adctog’, ‘adctgo’, ‘adcotg’, ‘adcogt’, ‘adcgto’, ‘adcgot’, ‘adtcog’, ‘adtcgo’, ‘adtocg’, ‘adtogc’, ‘adtgco’, ‘adtgoc’, ‘adoctg’, ‘adocgt’, ‘adotcg’, ‘adotgc’, ‘adogct’, ‘adogtc’, ‘adgcto’, ‘adgcot’, ‘adgtco’, ‘adgtoc’, ‘adgoct’, ‘adgotc’, ‘aoctdg’, ‘aoctgd’, ‘aocdtg’, ‘aocdgt’, ‘aocgtd’, ‘aocgdt’, ‘aotcdg’, ‘aotcgd’, ‘aotdcg’, ‘aotdgc’, ‘aotgcd’, ‘aotgdc’, ‘aodctg’, ‘aodcgt’, ‘aodtcg’, ‘aodtgc’, ‘aodgct’, ‘aodgtc’, ‘aogctd’, ‘aogcdt’, ‘aogtcd’, ‘aogtdc’, ‘aogdct’, ‘aogdtc’, ‘agctdo’, ‘agctod’, ‘agcdto’, ‘agcdot’, ‘agcotd’, ‘agcodt’, ‘agtcdo’, ‘agtcod’, ‘agtdco’, ‘agtdoc’, ‘agtocd’, ‘agtodc’, ‘agdcto’, ‘agdcot’, ‘agdtco’, ‘agdtoc’, ‘agdoct’, ‘agdotc’, ‘agoctd’, ‘agocdt’, ‘agotcd’, ‘agotdc’, ‘agodct’, ‘agodtc’, ‘tcadog’, ‘tcadgo’, ‘tcaodg’, ‘tcaogd’, ‘tcagdo’, ‘tcagod’, ‘tcdaog’, ‘tcdago’, ‘tcdoag’, ‘tcdoga’, ‘tcdgao’, ‘tcdgoa’, ‘tcoadg’, ‘tcoagd’, ‘tcodag’, ‘tcodga’, ‘tcogad’, ‘tcogda’, ‘tcgado’, ‘tcgaod’, ‘tcgdao’, ‘tcgdoa’, ‘tcgoad’, ‘tcgoda’, ‘tacdog’, ‘tacdgo’, ‘tacodg’, ‘tacogd’, ‘tacgdo’, ‘tacgod’, ‘tadcog’, ‘tadcgo’, ‘tadocg’, ‘tadogc’, ‘tadgco’, ‘tadgoc’, ‘taocdg’, ‘taocgd’, ‘taodcg’, ‘taodgc’, ‘taogcd’, ‘taogdc’, ‘tagcdo’, ‘tagcod’, ‘tagdco’, ‘tagdoc’, ‘tagocd’, ‘tagodc’, ‘tdcaog’, ‘tdcago’, ‘tdcoag’, ‘tdcoga’, ‘tdcgao’, ‘tdcgoa’, ‘tdacog’, ‘tdacgo’, ‘tdaocg’, ‘tdaogc’, ‘tdagco’, ‘tdagoc’, ‘tdocag’, ‘tdocga’, ‘tdoacg’, ‘tdoagc’, ‘tdogca’, ‘tdogac’, ‘tdgcao’, ‘tdgcoa’, ‘tdgaco’, ‘tdgaoc’, ‘tdgoca’, ‘tdgoac’, ‘tocadg’, ‘tocagd’, ‘tocdag’, ‘tocdga’, ‘tocgad’, ‘tocgda’, ‘toacdg’, ‘toacgd’, ‘toadcg’, ‘toadgc’, ‘toagcd’, ‘toagdc’, ‘todcag’, ‘todcga’, ‘todacg’, ‘todagc’, ‘todgca’, ‘todgac’, ‘togcad’, ‘togcda’, ‘togacd’, ‘togadc’, ‘togdca’, ‘togdac’, ‘tgcado’, ‘tgcaod’, ‘tgcdao’, ‘tgcdoa’, ‘tgcoad’, ‘tgcoda’, ‘tgacdo’, ‘tgacod’, ‘tgadco’, ‘tgadoc’, ‘tgaocd’, ‘tgaodc’, ‘tgdcao’, ‘tgdcoa’, ‘tgdaco’, ‘tgdaoc’, ‘tgdoca’, ‘tgdoac’, ‘tgocad’, ‘tgocda’, ‘tgoacd’, ‘tgoadc’, ‘tgodca’, ‘tgodac’, ‘dcatog’, ‘dcatgo’, ‘dcaotg’, ‘dcaogt’, ‘dcagto’, ‘dcagot’, ‘dctaog’, ‘dctago’, ‘dctoag’, ‘dctoga’, ‘dctgao’, ‘dctgoa’, ‘dcoatg’, ‘dcoagt’, ‘dcotag’, ‘dcotga’, ‘dcogat’, ‘dcogta’, ‘dcgato’, ‘dcgaot’, ‘dcgtao’, ‘dcgtoa’, ‘dcgoat’, ‘dcgota’, ‘dactog’, ‘dactgo’, ‘dacotg’, ‘dacogt’, ‘dacgto’, ‘dacgot’, ‘datcog’, ‘datcgo’, ‘datocg’, ‘datogc’, ‘datgco’, ‘datgoc’, ‘daoctg’, ‘daocgt’, ‘daotcg’, ‘daotgc’, ‘daogct’, ‘daogtc’, ‘dagcto’, ‘dagcot’, ‘dagtco’, ‘dagtoc’, ‘dagoct’, ‘dagotc’, ‘dtcaog’, ‘dtcago’, ‘dtcoag’, ‘dtcoga’, ‘dtcgao’, ‘dtcgoa’, ‘dtacog’, ‘dtacgo’, ‘dtaocg’, ‘dtaogc’, ‘dtagco’, ‘dtagoc’, ‘dtocag’, ‘dtocga’, ‘dtoacg’, ‘dtoagc’, ‘dtogca’, ‘dtogac’, ‘dtgcao’, ‘dtgcoa’, ‘dtgaco’, ‘dtgaoc’, ‘dtgoca’, ‘dtgoac’, ‘docatg’, ‘docagt’, ‘doctag’, ‘doctga’, ‘docgat’, ‘docgta’, ‘doactg’, ‘doacgt’, ‘doatcg’, ‘doatgc’, ‘doagct’, ‘doagtc’, ‘dotcag’, ‘dotcga’, ‘dotacg’, ‘dotagc’, ‘dotgca’, ‘dotgac’, ‘dogcat’, ‘dogcta’, ‘dogact’, ‘dogatc’, ‘dogtca’, ‘dogtac’, ‘dgcato’, ‘dgcaot’, ‘dgctao’, ‘dgctoa’, ‘dgcoat’, ‘dgcota’, ‘dgacto’, ‘dgacot’, ‘dgatco’, ‘dgatoc’, ‘dgaoct’, ‘dgaotc’, ‘dgtcao’, ‘dgtcoa’, ‘dgtaco’, ‘dgtaoc’, ‘dgtoca’, ‘dgtoac’, ‘dgocat’, ‘dgocta’, ‘dgoact’, ‘dgoatc’, ‘dgotca’, ‘dgotac’, ‘ocatdg’, ‘ocatgd’, ‘ocadtg’, ‘ocadgt’, ‘ocagtd’, ‘ocagdt’, ‘octadg’, ‘octagd’, ‘octdag’, ‘octdga’, ‘octgad’, ‘octgda’, ‘ocdatg’, ‘ocdagt’, ‘ocdtag’, ‘ocdtga’, ‘ocdgat’, ‘ocdgta’, ‘ocgatd’, ‘ocgadt’, ‘ocgtad’, ‘ocgtda’, ‘ocgdat’, ‘ocgdta’, ‘oactdg’, ‘oactgd’, ‘oacdtg’, ‘oacdgt’, ‘oacgtd’, ‘oacgdt’, ‘oatcdg’, ‘oatcgd’, ‘oatdcg’, ‘oatdgc’, ‘oatgcd’, ‘oatgdc’, ‘oadctg’, ‘oadcgt’, ‘oadtcg’, ‘oadtgc’, ‘oadgct’, ‘oadgtc’, ‘oagctd’, ‘oagcdt’, ‘oagtcd’, ‘oagtdc’, ‘oagdct’, ‘oagdtc’, ‘otcadg’, ‘otcagd’, ‘otcdag’, ‘otcdga’, ‘otcgad’, ‘otcgda’, ‘otacdg’, ‘otacgd’, ‘otadcg’, ‘otadgc’, ‘otagcd’, ‘otagdc’, ‘otdcag’, ‘otdcga’, ‘otdacg’, ‘otdagc’, ‘otdgca’, ‘otdgac’, ‘otgcad’, ‘otgcda’, ‘otgacd’, ‘otgadc’, ‘otgdca’, ‘otgdac’, ‘odcatg’, ‘odcagt’, ‘odctag’, ‘odctga’, ‘odcgat’, ‘odcgta’, ‘odactg’, ‘odacgt’, ‘odatcg’, ‘odatgc’, ‘odagct’, ‘odagtc’, ‘odtcag’, ‘odtcga’, ‘odtacg’, ‘odtagc’, ‘odtgca’, ‘odtgac’, ‘odgcat’, ‘odgcta’, ‘odgact’, ‘odgatc’, ‘odgtca’, ‘odgtac’, ‘ogcatd’, ‘ogcadt’, ‘ogctad’, ‘ogctda’, ‘ogcdat’, ‘ogcdta’, ‘ogactd’, ‘ogacdt’, ‘ogatcd’, ‘ogatdc’, ‘ogadct’, ‘ogadtc’, ‘ogtcad’, ‘ogtcda’, ‘ogtacd’, ‘ogtadc’, ‘ogtdca’, ‘ogtdac’, ‘ogdcat’, ‘ogdcta’, ‘ogdact’, ‘ogdatc’, ‘ogdtca’, ‘ogdtac’, ‘gcatdo’, ‘gcatod’, ‘gcadto’, ‘gcadot’, ‘gcaotd’, ‘gcaodt’, ‘gctado’, ‘gctaod’, ‘gctdao’, ‘gctdoa’, ‘gctoad’, ‘gctoda’, ‘gcdato’, ‘gcdaot’, ‘gcdtao’, ‘gcdtoa’, ‘gcdoat’, ‘gcdota’, ‘gcoatd’, ‘gcoadt’, ‘gcotad’, ‘gcotda’, ‘gcodat’, ‘gcodta’, ‘gactdo’, ‘gactod’, ‘gacdto’, ‘gacdot’, ‘gacotd’, ‘gacodt’, ‘gatcdo’, ‘gatcod’, ‘gatdco’, ‘gatdoc’, ‘gatocd’, ‘gatodc’, ‘gadcto’, ‘gadcot’, ‘gadtco’, ‘gadtoc’, ‘gadoct’, ‘gadotc’, ‘gaoctd’, ‘gaocdt’, ‘gaotcd’, ‘gaotdc’, ‘gaodct’, ‘gaodtc’, ‘gtcado’, ‘gtcaod’, ‘gtcdao’, ‘gtcdoa’, ‘gtcoad’, ‘gtcoda’, ‘gtacdo’, ‘gtacod’, ‘gtadco’, ‘gtadoc’, ‘gtaocd’, ‘gtaodc’, ‘gtdcao’, ‘gtdcoa’, ‘gtdaco’, ‘gtdaoc’, ‘gtdoca’, ‘gtdoac’, ‘gtocad’, ‘gtocda’, ‘gtoacd’, ‘gtoadc’, ‘gtodca’, ‘gtodac’, ‘gdcato’, ‘gdcaot’, ‘gdctao’, ‘gdctoa’, ‘gdcoat’, ‘gdcota’, ‘gdacto’, ‘gdacot’, ‘gdatco’, ‘gdatoc’, ‘gdaoct’, ‘gdaotc’, ‘gdtcao’, ‘gdtcoa’, ‘gdtaco’, ‘gdtaoc’, ‘gdtoca’, ‘gdtoac’, ‘gdocat’, ‘gdocta’, ‘gdoact’, ‘gdoatc’, ‘gdotca’, ‘gdotac’, ‘gocatd’, ‘gocadt’, ‘goctad’, ‘goctda’, ‘gocdat’, ‘gocdta’, ‘goactd’, ‘goacdt’, ‘goatcd’, ‘goatdc’, ‘goadct’, ‘goadtc’, ‘gotcad’, ‘gotcda’, ‘gotacd’, ‘gotadc’, ‘gotdca’, ‘gotdac’, ‘godcat’, ‘godcta’, ‘godact’, ‘godatc’, ‘godtca’, ‘godtac’]
P-1.30 编写一个 Python 程序,输入一个大于 2 的正整数,求将该数反复被 2 整除直到商小于 2 为止的次数。
def function30():
num = int(input("Please input a number: \n"))
count = 0
rest = num
while rest >= 2:
rest = int(rest / 2)
count += 1
return count
function30()
Please input a number:
16
4
P-1.31 编写一个可以“找零钱”的 Python 程序。程序应该将两个数字作为输入,一个是需要支付的钱数,另一个是你给的钱数。当你需要支付的和所给的钱数不同时,它应该返回所找的纸币和硬币的数量。纸币和硬币的值可以基于之前或现在政府的货币体系。试设计程序,以便返回尽可能少的纸币和硬币。
def function31():
coins = {'0.5':0, '1':0, '5':0, '10':0, '20':0, '50':0, '100':0}
temp = input("Please input Pay and Total money: \n").split(" ")
pay, total = int(temp[0]), int(temp[1])
rest = total - pay
coins[100] = int(rest / 100)
rest = int(rest % 100)
coins[50] = int(rest / 50)
rest = int(rest % 50)
coins[20] = int(rest / 20)
rest = int(rest % 20)
coins[10] = int(rest / 10)
rest = int(rest % 10)
coins[5] = int(rest / 5)
rest = int(rest % 5)
coins[1] = int(rest / 1)
rest = int(rest % 1)
coins[0.5] = int(rest / 0.5)
rest = int(rest % 0.5)
return coins.values()
function31()
Please input Pay and Total money:
20 87
dict_values([0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 2, 0])
P-1.32 编写一个 Python 程序来模拟一个简单的计算器,使用控制台作为输入和输出的专用设备。也就是说,计算器的每一次输入做一个单独的行,它可以输入一个数字(如1034或12.34)或操作符(如 + 或 = )。每一次输入后,应该输出计算器显示的结果并将其输出到 Python 控制台。
def function32():
temp = input("Please input Number1 Operation Number2: \n").split(" ")
num1 = int(temp[0])
num2 = int(temp[2])
oper = str(temp[1])
if oper == '+':
result = num1 + num2
elif oper == '-':
result = num1 - num2
elif oper == '*':
result = num1 * num2
elif oper == '/':
result = num1 / num2
else:
raise EOFError("Error Input!")
return result
function32()
Please input Number1 Operation Number2:
2 / 3
0.6666666666666666
P-1.33 编写一个 Python 程序来模拟一个手持计算器,程序应该可以处理来自 Python 控制台(表示 Push 按钮)的输入,每个操作执行完毕后内容输出到屏幕。计算器至少应该能够处理基本的算术运算和复位/清除操作。
def function33():
P-1.34 一种惩罚学生的常见方法是让他们将一个句子重复写很多次。编写独立的 Python 程序,将以下句子 “I will never spam my friends again.” 写 100 次。程序应该对句子进行计数,另外,应该有 8 次不同的随机输入错误。
def function34():
count = 1
string = "I will never spam my friends again."
while count < 11:
temp = input("Now : {} Please write phrase: \n".format(count))
if temp == string:
count += 1
print("Finished!")
function34()
Now : 1 Please write phrase:
I will never spam my friends again.
Now : 2 Please write phrase:
I will never spam my friends again.
Now : 3 Please write phrase:
I will never spam my friends again.
Now : 4 Please write phrase:
I will never spam my friends again.
Now : 5 Please write phrase:
I will never spam my friends again.
Now : 6 Please write phrase:
I will never spam my friends again.
Now : 7 Please write phrase:
I will never spam my friends again.
Now : 8 Please write phrase:
I will never spam my friends again.
Now : 9 Please write phrase:
I will never spam my friends again.
Now : 10 Please write phrase:
I will never spam my friends again.
Finished!
P-1.35 生日悖论是说,当房间中人数 n 超过 23 时,那么该房间里有两个人生日相同的可能性是一半以上。这其实不是一个悖论,但许多人觉得不可思议。设计一个 Python 程序,可以通过一系列随机生成的生日的实验来测试这个悖论,例如可以 n = 5, 10, 15, 20, …, 100 测试这个悖论。
1.第一种思路:
- n u m num num 个人中生日两两不同的概率为:
365 ⋅ 364 ⋅ . . . ⋅ ( 365 − ( n u m − 1 ) ) 365 ⋅ 365 ⋅ . . . ⋅ 365 = 365 ! 36 5 ( n u m ) ⋅ ( 365 − n u m ) ! \frac{365·364·... ·(365-(num-1))}{365·365·...·365} = \frac{365!}{365^{(num)}·(365-num)!} 365⋅365⋅...⋅365365⋅364⋅...⋅(365−(num−1))=365(num)⋅(365−num)!365!
所以 n u m num num 个人中至少两人生日相同的概率为:
p r o p = 1 − 365 ! 36 5 ( n u m ) ⋅ ( 365 − n u m ) ! prop = 1 - \frac{365!}{365^{(num)}·(365-num)!} prop=1−365(num)⋅(365−num)!365!
2.第二种思路:
- 任意 2 个人中生日不同的概率为:
364 365 \frac{364}{365} 365364
n u m num num 个人中两两之间共有组合以下对:
C n u m 2 = n u m ∗ ( n u m − 1 ) 2 C_{num}^{2} = \frac{num*(num-1)}{2} Cnum2=2num∗(num−1)
所以 n u m num num 个人中任意两两之间组合且不相同的可能性为:
( 364 365 ) ( C n u m 2 ) (\frac{364}{365})^{(C_{num}^{2})} (365364)(Cnum2)
所以 n u m num num 个人中至少有两人生日相同的概率为:
p r o p = 1 − ( 364 365 ) ( C n u m 2 ) = 1 − ( 364 365 ) ( n u m ∗ ( n u m − 1 ) 2 ) prop = 1 - (\frac{364}{365})^{(C_{num}^{2})} = 1 -(\frac{364}{365})^{(\frac{num*(num-1)}{2})} prop=1−(365364)(Cnum2)=1−(365364)(2num∗(num−1))
def function35(num):
import math
from decimal import Decimal
prop = 1 - Decimal((math.factorial(365)))/Decimal((math.pow(365, num) * math.factorial(364 - num)))
return prop
def function352(num):
import math
prop = 1 - math.pow((364/365), (num*(num-1)/2))
return prop
function352(23)
0.5004771540365807
P-1.36 编写一个 Python程序,输入一个由空格分隔的单词列表,并输出列表中的每个单词出现的次数。在这一点上,你不需要担心效率,因为这个问题会在本书后面的部分予以解决。
def function36():
import string
temp = input("Please input a string: \n").strip(string.punctuation).split(" ")
keys = list(set(temp))
result = dict(zip(keys,[0]*len(keys)))
for item in temp:
result[item] += 1
return result
function36()
Please input a string:
"I love I"
{‘I’: 2, ‘love’: 1}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)