数据结构与算法 Python语言实现 课后习题解答Chapter 1

1.12 Exercises
Reinforcement
R-1.1 Write a short Python function, is_multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise.

def is_multiple(n,m):
    return not n%m 

R-1.2 Write a short Python function, is_even(k), that takes an integer value and
returns True if k is_even, and False otherwise. However, your function
cannot use the multiplication, modulo, or division operators.

def is_even(k):
    k=abs(k)
    while True:
       if k==0:
          return True
       elif k==1:
          return False
       k=k-2
    
R-1.3 Write a short Python function, minmax(data), that takes a sequence of
one or more numbers, and returns the smallest and largest numbers, in the
form of a tuple of length two. Do not use the built-in functions min or
max in implementing your solution.

def minmax(data):
    min=data[0]
    max=data[0]
    for i in data:
       if i           min=i
       if i>max:
          max=i
    return (min,max)

R-1.4 Write a short Python function that takes a positive integer n and returns
the sum of the squares of all the positive integers smaller than n.

def sumOfSquares(n):
    sum=0
    for i in range(1,n+1):
        sum=sum+i*i
    return sum
    

R-1.5 Give a single command that computes the sum from Exercise R-1.4, relying
on Python’s comprehension syntax and the built-in sum function.

sum([i*i for i in range(1,n+1)])

R-1.6 Write a short Python function that takes a positive integer n and returns
the sum of the squares of all the odd positive integers smaller than n.


In [20]: def sumOfSquaresOfOdd(n):
    ...:     return sum([i*i for i in range(1,n+1) if i%2>0])
    ...:
    ...:

In [21]: sumOfSquaresOfOdd(3)
Out[21]: 10

R-1.7 Give a single command that computes the sum from Exercise R-1.6, relying
on Python’s comprehension syntax and the built-in sum function.

sum([i*i for i in range(1,n+1) if i%2>0])

R-1.8 Python allows negative integers to be used as indices into a sequence,
such as a string. If string s has length n, and expression s[k] is used for index
−n≤k<0, what is the equivalent index j ≥0 such that s[j] references
the same element?

j=n-k

R-1.9 What parameters should be sent to the range constructor, to produce a
range with values 50, 60, 70, 80?


In [26]: list(range(50,90,10))
Out[26]: [50, 60, 70, 80]
R-1.10 What parameters should be sent to the range constructor, to produce a
range with values 8, 6, 4, 2, 0, −2, −4, −6, −8?

In [27]: list(range(8,-10,-2))
Out[27]: [8, 6, 4, 2, 0, -2, -4, -6, -8]

R-1.11 Demonstrate how to use Python’s list comprehension syntax to produce
the list [1, 2, 4, 8, 16, 32, 64, 128, 256].


In [29]: [pow(2,i) for i in range(9)]
Out[29]: [1, 2, 4, 8, 16, 32, 64, 128, 256]
R-1.12 Python’s random module includes a function choice(data) that returns a
random element from a non-empty sequence. The random module includes
a more basic function randrange, with parameterization similar to
the built-in range function, that return a random choice from the given
range. Using only the randrange function, implement your own version
of the choice function.

In [31]: lst
Out[31]: [1, 2, 3]

In [32]: random.choice(lst)
Out[32]: 3

In [33]: random.randrange(10)
Out[33]: 2

In [34]: def myChoice(lst):
    ...:     import random
    ...:     minN=min(lst)
    ...:     maxN=max(lst)
    ...:     while True:
    ...:
    ...:         i=random.randrange(minN,maxN+1)
    ...:         if i in lst:
    ...:            return i
    ...:
    ...:

In [35]: myChoice(lst)
Out[35]: 2

 

Creativity
C-1.13 Write a pseudo-code description of a function that reverses a list of n
integers, so that the numbers are listed in the opposite order than they
were before, and compare this method to an equivalent Python function
for doing the same thing.

In [38]: lst[::-1]
Out[38]: [3, 2, 1]

C-1.14 Write a short Python function that takes a sequence of integer values and
determines if there is a distinct pair of numbers in the sequence whose
product is odd.

In [41]: def productIsOdd(lst):
    ...:     'with two and more different odd numbers'
    ...:     lst=[i for i in lst if i%2>0]
    ...:     if len(set(lst))>=2:
    ...:         return True
    ...:     else:
    ...:         return False
    ...:

In [42]: productIsOdd([1,3,10])
Out[42]: True

In [43]: productIsOdd([1,5,10])
Out[43]: True

In [44]: productIsOdd([1,8,10])
Out[44]: False

C-1.15 Write a Python function that takes a sequence of numbers and determines
if all the numbers are different from each other (that is, they are distinct).


In [45]: def isDiff(lst):
    ...:     return len(lst)==len(set(lst))
    ...:
    ...:

In [46]: isDiff([1,3,35])
Out[46]: True

In [47]: isDiff([1,3,3,5])
Out[47]: False

C-1.16 In our implementation of the scale function (page 25), the body of the loop
executes the command data[j] = factor. We have discussed that numeric
types are immutable, and that use of the = operator in this context causes
the creation of a new instance (not the mutation of an existing instance).
How is it still possible, then, that our implementation of scale changes the
actual parameter sent by the caller?

C-1.17 Had we implemented the scale function (page 25) as follows, does it work
properly?
def scale(data, factor):
for val in data:
val = factor
Explain why or why not.

it can't work.val只是对data列表中数据的引用,是一个变量,而不是列表元素对象本身。需要在对象上改变,需要采用索引的方法,如习题16;

def scale(data,factor):

    for j in range(len(data)):

          data[j]*=factor

 

C-1.18 Demonstrate how to use Python’s list comprehension syntax to produce
the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].

递推公式:A(n)-A(n-1)=2*(n-1);

求和叠加,求得多项式通式:A(n)=n*(n-1)


In [65]: [i*(i-1) for i in range(1,11)]
Out[65]: [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]

C-1.19 Demonstrate how to use Python’s list comprehension syntax to produce
the list [ a , b , c , ..., z ], but without having to type all 26 such
characters literally.

对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:

>>> ord('A')
65
>>> ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'文'

In [71]: [chr(ord('a')+i) for i in range(26)]
Out[71]:
['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’s random module includes a function shuffle(data) that accepts a
list of elements and randomly reorders the elements so that each possible
order occurs with equal probability. The random module includes a
more basic function randint(a, b) that returns a uniformly random integer
from a to b (including both endpoints). Using only the randint function,
implement your own version of the shuffle function.

In [94]: def myShuffle(lst):
    ...:     import random
    ...:     lstlen=len(lst)
    ...:     shuffle=[]
    ...:     lst2=list(range(len(lst)))
    ...:     while lst2:
    ...:         i=random.randint(0,lstlen-1)
    ...:         if i in lst2:
    ...:             shuffle.append(lst[i])
    ...:             lst2.remove(i)
    ...:     lst[:]=shuffle[:]
    ...:

In [95]: myShuffle(lst)

In [96]: lst
Out[96]: [4, 3, 2, 5, 1]
 

C-1.21 Write a Python program that repeatedly reads lines from standard input
until an EOFError is raised, and then outputs those lines in reverse order
(a user can indicate end of input by typing ctrl-D).

>>> def inputTest():
    lst=[]
    try:
        while True:
            lst.append(input('please input:'))
    except EOFError:
        for i in lst[::-1]:
            print(i)

            
>>> 
>>> inputTest()
please input:123
please input:456
please input:789
please input:
789
456
123
>>> 

C-1.22 Write a short Python program that takes two arrays a and b of length n
storing int values, and returns the dot product of a and b. That is, it returns
an array c of length n such that c[i] = a[i] · b[i], for i = 0, . . . ,n−1.


In [108]: a
Out[108]: array([1, 2, 3])

In [109]: b=np.array([4,5,6])

In [110]: b
Out[110]: array([4, 5, 6])

In [111]: a*b
Out[111]: array([ 4, 10, 18])

In [112]: def dot_product(a,b):
     ...:     return a*b
     ...:
     ...:

In [113]: dot_product(a,b)
Out[113]: array([ 4, 10, 18])

当为array的时候,默认d*f就是对应元素的乘积,multiply也是对应元素的乘积,dot(d,f)会转化为矩阵的乘积, dot点乘意味着相加,而multiply只是对应元素相乘,不相加

C-1.23 Give an example of a Python code fragment that attempts to write an element
to a list based on an index that may be out of bounds. If that index
is out of bounds, the program should catch the exception that results, and
print the following error message:
“Don’t try buffer overflow attacks in Python!”

 

In [120]: try:
     ...:     a=[1,2,3]
     ...:     a[5]
     ...: except IndexError:
     ...:     print('Don\'t buffer overflow attacks in Python!')
     ...:
Don't buffer overflow attacks in Python!

 

C-1.24 Write a short Python function that counts the number of vowels in a given
character string.

美国英语中,a,e,i,o,u是元音字母。

In [121]: def numOfVowels(s):
     ...:     vowels=('a','e','i','o','u','A','E','I','O','U')
     ...:     num=0
     ...:     for i in s:
     ...:         if i in vowels:
     ...:             num+=1
     ...:     return num
     ...:
     ...:

In [122]: numOfVowels('god')
Out[122]: 1

In [123]: numOfVowels('please')
Out[123]: 3

 

C-1.25 Write a short Python function that takes a string s, representing a sentence,
and returns a copy of the string with all punctuation removed. For example,
if given the string "Let’s try, Mike.", this function would return
"Lets try Mike".

如果想用英文的标点,则可调用string包的string.punctuation函数可得到


In [145]: def removePunctuation(s):
     ...:     import string
     ...:     punctuation=string.punctuation
     ...:     s2=''
     ...:     for i in s:
     ...:         if i not in punctuation:
     ...:             s2+=i
     ...:     return s2
     ...:
     ...:
     ...:

In [146]: removePunctuation(s)
Out[146]: 'lets try'

In [166]: import string

In [167]: import re

In [168]: s="Let's try,OK?"

In [169]: pun=string.punctuation

In [170]: pun
Out[170]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

In [171]: r'['+pun+r']'
Out[171]: '[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'

In [172]: re.sub(r'['+pun+']','',s)
Out[172]: 'Lets tryOK'

C-1.26 Write a short program that takes as input three integers, a, b, and c, from
the console and determines if they can be used in a correct arithmetic
formula (in the given order), like “a+b = c,” “a = b−c,” or “a ∗ b = c.”


In [179]: def threeIntegers():
     ...:     a=input('please input three integers,\na:')
     ...:     b=input('b:')
     ...:     c=input('c:')
     ...:     a,b,c=int(a),int(b),int(c)
     ...:     print('a+b=c 成立') if a+b==c else print('a+b=c 不成立')
     ...:

In [180]: threeIntegers()
please input three integers,
a:10
b:20
c:30
a+b=c 成立

C-1.27 In Section 1.8, we provided three different implementations of a generator
that computes factors of a given integer. The third of those implementations,
from page 41, was the most efficient, but we noted that it did not
yield the factors in increasing order. Modify the generator so that it reports
factors in increasing order, while maintaining its general performance advantages.

In [204]: def factors(n):
     ...:     k=1
     ...:     lst=[]
     ...:     while k*k      ...:         if n%k==0:
     ...:             yield k
     ...:             lst.append(n//k)
     ...:         k+=1
     ...:     if k*k==n:
     ...:         yield k
     ...:
     ...:     for i in lst[::-1]:
     ...:         yield i
     ...:
     ...:

In [205]: f=factors(100)

In [206]: try:
     ...:     while True:
     ...:         print( next(f))
     ...:
     ...: except Exception:pass
     ...:
     ...:
     ...:
1
2
4
5
10
20
25
50
100

In [207]:
 

C-1.28 The p-norm of a vector v = (v1,v2, . . . ,vn) in n-dimensional space is defined
as

数据结构与算法 Python语言实现 课后习题解答Chapter 1_第1张图片


In [207]: def norm(v,p=2):
     ...:     sum=0
     ...:     for i in v:
     ...:         sum=sum+pow(i,p)
     ...:     return pow(sum,1.0/p)
     ...:
     ...:

In [208]: norm((4,3))
Out[208]: 5.0

In [209]: norm((4,3),3)
Out[209]: 4.497941445275415

Projects
P-1.29 Write a Python program that outputs all possible strings formed by using
the characters c , a , t , d , o , and g exactly once.

In [218]: def allStr():
     ...:     s=['c','a','t','d','o','g']
     ...:     for i in s:
     ...:         print(i)
     ...:         ss=s.copy()
     ...:         ss.remove(i)
     ...:         for j in ss:
     ...:             print(i+j)
     ...:             sss=ss.copy()
     ...:             sss.remove(j)
     ...:             for k in sss:
     ...:                 print(i+j+k)
     ...:                 ssss=sss.copy()
     ...:                 ssss.remove(k)
     ...:                 for m in ssss:
     ...:                     print(i+j+k+m)
     ...:                     sssss=ssss.copy()
     ...:                     sssss.remove(m)
     ...:                     for n in sssss:
     ...:                         print(i+j+k+m+n)
     ...:                         ssssss=sssss.copy()
     ...:                         ssssss.remove(n)
     ...:                         for p in ssssss:
     ...:                             print(i+j+k+m+n+p)
     ...:

P-1.30 Write a Python program that can take a positive integer greater than 2 as
input and write out the number of times one must repeatedly divide this
number by 2 before getting a value less than 2.


In [223]: def numOfDivide(n):
     ...:     num=1
     ...:     while n//2>=2:
     ...:         num+=1
     ...:         n=n//2
     ...:     return num
     ...:
     ...:
     ...:

In [224]:

In [224]: numOfDivide(10)
Out[224]: 3

P-1.31 Write a Python program that can “make change.” Your program should
take two numbers as input, one that is a monetary amount charged and the
other that is a monetary amount given. It should then return the number
of each kind of bill and coin to give back as change for the difference
between the amount given and the amount charged. The values assigned
to the bills and coins can be based on the monetary system of any current
or former government. Try to design your program so that it returns as
few bills and coins as possible.

In [238]: def makeChange(charged,given):
     ...:     coin=[100,50,20,10,5,1,0.5,0.1]
     ...:     changed=given-charged
     ...:     if changed==0:return
     ...:     i=0
     ...:     ok=True
     ...:     while ok:
     ...:         if coin[i]<=changed:
     ...:            print('面值'+str(coin[i])+',张数:'+str(changed//coin[i]))
     ...:
     ...:
     ...:            ok=False
     ...:            makeChange(0,changed%coin[i])
     ...:         i+=1
     ...:

In [239]:

In [239]: makeChange(50,100)
面值50,张数:1

In [240]: makeChange(20,87)
面值50,张数:1
面值10,张数:1
面值5,张数:1
面值1,张数:2

P-1.32 Write a Python program that can simulate a simple calculator, using the
console as the exclusive input and output device. That is, each input to the
calculator, be it a number, like 12.34 or 1034, or an operator, like + or =,
can be done on a separate line. After each such input, you should output
to the Python console what would be displayed on your calculator.

 

 

 

 

你可能感兴趣的:(数据结构与算法)