Python核心编程(第二版)课后习题部分答案

2-11:

借鉴了一位博主的稿子,但关键部分做了改动。

# !/usr/bin/env python
# -*- coding:utf-8 -*-

print ('Please input corresponding number to run different function:\n(1)Calculate the sum of five numbers;\n(2)Calculate the average of five numbers;\n(3)Exit')
while True:
    total = 0
    flag = int(input('Select:'))
    if flag==1:
        group = []
        for i in range(5):
            group.append(int(input('Enter the %dth number:'%(i+1))))
        for x in group:
            total += x
        print ('The SUM:%d'%total)
    elif flag==2:
        group = []
        for i in range(5):
            group.append(float(input('Enter the %dth number:'%(i+1))))
        for x in group:
            total += x
        average = total/5
        print ('The average:%d'%average)
    elif flag==3:
        break
    else:
        print ('You have entered the wrong number, please try again.')  

3-1:

Python是一门动态语言,也是一种强类型语言。它会根据你的赋值确定类型,在创建一个变量时开辟内存,而类型一旦确定就不再改变,当然,可以用工厂函数int()、float()来强制改变。

3-3:

因为__xxx__这样的变量命名方式对Python有特殊意义,因为下划线对解释器有特殊意义,且是内建标识符所使用的符号。(一般来讲,_xxx 被看作是“私有的”)

3-4:

同一行可以书写多条语句,不过语句之间要加';'加以间隔。

3-8:

书上有点小错误自己修正了一下,能够在py文件所在目录下创建一个简单的文本文件,如果输入的名字含有后缀的话(例如:.txt),生成的文件就直接双击就可以打开了。

#! /usr/bin/env python

'makeTextFile.py -- create text file in current path'

import os
ls = os.linesep #字符串给出当前平台的行终止符

#get filename
while True:
    fname = input('\nCreate a filename:')#书上没有,我自己加上去的
    if os.path.exists(fname):   
        print("ERROR:'%s' aready exists"%fname)
    else:
        break

#get file content (text) lines
all = []
print("\nEnter lines('.' by itself to quit).\n")

#loop until user terminates input
while True:
    entry = input('请输入一行文本>>>')
    if entry == '.':
        break
    else:
        all.append(entry)

# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s'%(x,ls) for x in all])   #以行的单位写入文件
fobj.close()
print ("Done.")


3-11:

#! /usr/bin/env python

'raedTextFile.py -- raed and display text file'

#get file
fname = input("Please enter the filename you want to open:")

#attempt to open file for reading

try:
    fobj = open (fname,'r')
except (IOError,e):
    print("*** file open error",e)
else:
    #display contents to screen
    for eachline in fobj:
        print (eachline.rstrip())#截掉字符串右边的空格,split函数才是分割的
fobj.close()

4-1:

三个属性:身份、类型、值;id,对象的内存地址;type,决定遵循什么样的规则操作;data,对象表示的数据项。

4-2:

对象不支持更新操作,值不可以改变,称为immutable,不可更改的,Python中只有列表和字典类型是可变类型。

4-3:

字符串、列表、元组是按顺序访问的,而字典是映射访问的;一个是顺序存放,顺序访问,一个是无序存放,通过唯一的键来访问,称哈希键-值对。

4-5:

str()函数得到的字符串可读性好,而repr()函数得到的字符串通常可以用来重新获得该对象;repr()对Python比较友好,而str()对用户比较友好。repr()和反引号(``)等价。

4-9:

Python仅缓存简单整型,因为他认为在程序中这些小整型会经常用到,现阶段Python3.6缓存的整型范围为(-5,256),在这个范围内,两个对象的值相等,他们就是一个对象,即id相同,而字符串也是不可变对象,只要指向相同的字符创,就是一个对象,只是有多个别名而已。

5-1:

标准整型:32位或64位;长整型:Python的长整型类型能表达的数值仅仅与你的机器支持的(虚拟)内存大小有关,Python能够很轻松的表达很大的整型。

5-6:

只是涉及到两个操作数的运算,想扩展实现多个操作数的运算,但是不行!

#coding:utf-8
""" 由于水平限制,只能实现2元运算"""
def calculator(expression):
    operator = ['+','-','*','/']
    sysmol = ''
    for i in operator:
        if i in expression:
            sysmol = i
    if sysmol == '':
        print('操作符错误!')
        return
    num = expression.split(sysmol)
    if '.' in num[0] or '.' in num[1]:
        num1 = float(num[0])
        num2 = float(num[1])
    else:
        num1 = int(num[0])
        num2 = int(num[1])
    if sysmol == operator[0]:
        print (expression,'=',num1+num2)
    elif sysmol == operator[1]:
        print(expression,'=',num1-num2)
    elif sysmol == operator[2]:
        print(expression,'=',num1*num2)
    elif sysmol == operator[3]:
        print(expression,'=',num1/num2)
expression = input("Please input a math expression like'1+2':")
calculator(expression)


5-15:

def gcd(x,y):
        if x%y==0:
                return y
        else:
                while True:
                        res = x%y
                        if res==0:
                                return y
                                break
                        elif res==1:
                                return 1
                                break
                        x=y
                        y=res
def lcm(x,y):
        return x*y/(gcd(x,y))  #It helps me review the Number theroy. Suddenly be enlightened. Take a tumble.  `~`                    
def main():
        while True:
                string = input ('Please input two numbers:')
                num = string.split()
                print ("Their min multiple is ", lcm(int(num[0]),int(num[1])))
                print ("Their max factor is ", gcd(int(num[0]),int(num[1])))
                prompt = input("Would do you like to quit?(yes/no):")
                if prompt == "yes":
                        break

if __name__ == '__main__':
        main()
                

6-2:

书上是Python2的语言,作者用的是Python3,所以做了一点改变,keyword模块中的keylist在Python3中没有,而是换成了kwword,string.letters也变成了string.ascii_letters,同时也有print的差别。

#!usr/bin/env python3

import string
import keyword

alphas = string.ascii_letters + '_'
nums = string.digits
officalkey = keyword.kwlist

print ('Welcome to the Identifier Checker v1.0')
while True:
        myInput= input('Identifier to test? (Press ctrl+C to exit)')
        if myInput in officalkey:
                print ("It's a offical Python identifier.")
        elif len(myInput) > 1:
                if myInput[0] not in alphas:
                        print ('''invalid: first symbol must be
                                alphabetic''')
                else:
                        for otherChar in myInput[1:]:
                                 if otherChar not in alphas + nums:
                                        print ('''invalid: remaining
                                        symbols must be alphanumeric''')
                                        break
                        else:
                                print ("okay as an identifier")
        elif len(myInput)==1 and myInput in alphas:
                print ("It's a single indentifier.")
        elif len(myInput)==1 and myInput in nums:
                print ("Error!Not to be a number.")

6-3:

nums = [0,1,2,3,4,5,6,7,8,9]
string = input("请输入一串数字:").split()
Tuple = []
for ch in string:
        Tuple.append(int(ch))
res1 = sorted(Tuple)[::-1]
print (res1)

Dict = {}
for ch in string:
        Dict[ch] = int(ch)
res2 = sorted(Dict)[::-1]
print (res2)

也是做了这一题之后,我才知道,Python有直接可以排序的函数sorted。

6-5:

分A,B,C,D四个函数,各实现每一小题。

#! /usr/bin/env python3.6
# __author__ =="spwpun" for python 6-5
import re
def testA():
        string = input("Enter a string -->")
        for i in range(len(string)):
                print (string[i])
                flag = input("Would do you like to see the previous character?")
                if flag == 'yes':
                        print (string[i-1])
                flag = input("Would do you like to see the later character?")
                if flag == 'yes':
                        print (string[i+1])

def testB():
        """ This function is to compare two strings. """
        str1 = input("Please input your first string:")
        str2 = input("Please input your second string:")
        if len(str1) != len(str2):
               print("They are not macth. They have different length.")
        else:
                for i in range(len(str1)):
                        if str1[i] != str2[i]:
                                print ("They are not matchs.")
                                break
                        elif i == (len(str1)-1):
                                print("They are matchs.")

def testC():
        """ This function is to judge if a string is a palindrome. """
        strC = input ("Enter a string -->")
        long = len(strC)
        if long%2 == 0:
                for i in range(int(long/2)):
                        if strC[i] != strC[long-1-i]:
                                print ("Not repeat!")
                                break
                else:
                        print ("Repeat!")
        elif long%2 != 0:
                for i in range(int(long/2)):
                        if strC[i] != strC[long-i-1]:
                                print ("Not repeat!")
                                break
                else:
                        print("Repeat.")
def testD():
        """ To get a palindrome. """
        strd = input("Enter a string -->")
        strd_ = strd[::-1]
        strd = strd+strd_
        print("The result is -->",strd)
        
if __name__ == "__main__":
        choice = input("Please select test(A,B,C,D):")
        if choice == 'A':
                testA()
        elif choice == 'B':
                testB()
        elif choice == 'C':
                testC()
        elif choice == 'D':
                testD()       

因为英文原版的C小题里面就是让判断是否是回文,翻译成了重现,导致这道题耽误了好长时间。这说明有能力的话还是尽量去看原版,翻译的男面会有些纰漏。

6-6:

#! /usr/bin/env python3.6
# __author__ == "spwpun" for python 6-6
""" To define a function can replace string.strip()."""
def mystrip(string):
        i=0;k=-1
        while True:
                if string[i] != ' ':
                        string = string[i:]
                        break
                i = i+1
        while True:
                if string[k] != ' ':
                        string = string[:k+1]
                        break
                k =k-1       
        return string

6-8:

将数字转换成对应的英文单词,列表的使用。

#!/usr/bin/env python

units = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve',
             'thirteen','forteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens = ['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
num_str = input("Please enter a number(0,999)-->")
num_int = int(num_str)
if num_int<=19:
        print (units[num_int])
elif num_int<100:
        ten = tens[int(num_str[0])-2]
        unit = units[int(num_str[1])]
        if unit == 'zero':
                print (ten)
        else:
                print (ten+'-'+unit)
elif int(num_str[1:])<19:
        hundred = units[int(num_str[0])]
        rest = units[int(num_str[1:])]
        print(hundred,' hundred ',rest)
else:
        hund = units[int(num_str[0])]
        ten = tens[int(num_str[1])-2]
        uni = units[int(num_str[2])]
        if uni == 'zero':
                print(hund,' hundred ',ten)
        else:
                print(hund,' hundred ',ten+'-'+uni)
6-11:

split和join的简单用法。

#!/usr/bin/env python3.6

def mytransferIP(ipaddress):
        blocks = []
        length = len(ipaddress)
        if length != 12:
                print("Invalid IP address!")
        else:
                for i in range(4):
                        block = ipaddress[:3]
                        ipaddress = ipaddress[3:]
                        blocks.append(block)
        return '.'.join(blocks)
def mytransferIP2(ipaddress):
        if len(ipaddress) != 15:
                print("Invalid IP address!")
        trans = ipaddress.split('.')
        ip = trans[0]+trans[1]+trans[2]+trans[3]
        return ip
        
6-12:

#!/usr/bin/env python3.6
# by spwpun

def findchr(string, char):
        for i in range(len(string)):
                if char == string[i]:
                        return i
        else:
                return -1
def rfindchr(string,char):
        k = -1
        while True:
                if char == string[k]:
                        return k+len(string)
                k -=1
                if k+len(string)<0:
                        return -1
                        break
def subchr(string, origchr, newchar):
        newst = []
        newstr = ''
        for i in range(len(string)):
                newst.append(string[i])
                if origchr == string[i]:
                        newst[i] = newchar
        for i in range(len(newst)):
                newstr += newst[i]
        return newstr

要注意,字符串是不可变对象,不能直接修改它的值,需要借助list的可变性来建造一个newstr,newst是list,存放string,替换后通过循环新建一个newstr,不过这个newstr要事先定义为全局变量,不然返回的时候会报错。

7-1:

dict.update(dict2) 字典dict2的键-值对添加到dict中。

7-2:

数字,字符串,元组是hashable的,可以做字典的键,但元组中的值要是不可变的,如数字、字符串,而字典和list不是,不能作为字典的键。

7-3:

(a)用sorted函数;(b)循环显示;

7-4:

list1 = ['a','b','c']
list2 = [1,2,3]
mydict = dict([ (list1[i],list2[i]) for i in range(len(list1)) ])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值