python核心编程2参考答案(第六章)声明:部分不是原创

1、string 模块中是否有一种字符串方法或者函数可以帮我鉴定一下一个字符串

是否是另一个大字符串的一部分?

'a' in 'jake'

True

或者是使用string.find()函数

2、 String Identifiers. Modify the idcheck.py script in 
Example 6–1 such that it will determine the validity of identi-
fiers of length 1 as well as be able to detect if an identifier is a 
keyword. For the latter part of the exercise, you may use the 
keyword module (specifically the keyword.kwlist list) to 
aid in your cause.

参考的程序:

# _*_ coding= utf-8 _*_


import string
import keyword
import sys
import traceback


try:
    #Get all keyword for python
    #keyword.kwlist
    #['and', 'as', 'assert', 'break', ...]
    keyWords = keyword.kwlist


    #Get all character for identifier
    #string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    #string.digits  ==> '0123456789'
    charForId = string.letters + "_"
    numForId = string.digits


    idInput = raw_input("Input your words,please!")


    if idInput in keyWords:
        print "%s is keyword fot Python!" % idInput
    else:
        lenNum = len(idInput)
        if(1 == lenNum):
            if(idInput in charForId and idInput != "_"):
                print "%s is legal identifier for Python!" % idInput
            else:
                #It's just "_"
                print "%s isn't legal identifier for Python!" % idInput


        else:
            if(idInput[0:1] in charForId):
                legalstring = charForId + numForId
                for item in idInput[1:]:
                    if (item not in legalstring):
                        print "%s isn't legal identifier for Python!" % idInput
                        sys.exit()
                print "%s is legal identifier for Python!2" % idInput
            else:
                print "%s isn't legal identifier for Python!3" % idInput


except SystemExit:
    pass
except:
    traceback.print_exc()


3、Sorting.
(a) Enter a list of numbers and sort the values in largest-to-
smallest order.
(b) Do the same thing, but for strings and in reverse alpha-
betical (largest-to-smallest lexicographic) order.

参考代码”:

#-*- coding:utf-8 -*-

#(a)
list1 = []
while True:
    num = int(raw_input("Please input numbers, end with 0: "))
    if num == 0:
        break;
    else:
        list1.append(num)
list1.sort()
print list1

#(b)
list2 = []
while True:
    num = raw_input("Please input numbers, end with 0: ")
    if str == '0':
        break;
    else:
        list2.append(num)
list2.sort()
print list2

6、

# _*_ coding= utf-8 _*_
# 6-6.	创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的
#		空格.(如果使用 string.*strip()函数那本练习就没有意义了)

def mystrip(s):
	mylist = []
	if isinstance(s,str):			
		for i in range(len(s)):
			if s[i] != ' ':
				mylist.append(i)
	else:
		print "您输入内容不是字符串"
	print s[mylist[0]:(mylist[-1]+1)]
ss = input("your input?")
mystrip(ss)

总结:python中else的用法


1.if-else
2.elif(else-if)
3.(while...else) or (for...else) 最后一句只要语句不是使用 break 跳出,else 体都会执行。
4.try...except...else...finally  异常语法

8、

#6–8. 	列表.给出一个整数值,返回代表该值的英文,比如输入 89 返回"eight-nine"。附加题:
#		能够返回符合英文语法规则的形式,比如输入“89”返回“eighty-nine”。本练习中的值限定在家 0
#		到 1,000.

dict_number = {
    '0' : 'zero', '1' : 'one', '2' : 'tow', '3' : 'three', '4' : 'four',
    '5' : 'five', '6' : 'six', '7' : 'seven', '8' : 'eight', '9' : 'nine'
}

def num_to_en(num_str):
    ret_str = ""
    i = 0
    if int(num_str) < 10:  #这一步实现,当小于10的数字也可以转换
        return dict_number[num_str]
    else:                  #大于等于10时,开始转换。根据题目意思,10为one-zero。             
        for i in range(len(num_str)-1):
            ret_str += dict_number[num_str[i]]
            ret_str += '-'
        else:
            ret_str += dict_number[num_str[i+1]]
        return ret_str
    
the_num = raw_input("Please input the number: ")
print num_to_en(the_num) 

9、写一个姊妹函数, 接受分钟数, 返回小时数和分钟数. 总时间不变,并且要求小时数尽可能大.

# _*_ coding= utf-8 _*_
minute = raw_input('Please input your minute:\n')
intmin = int(minute)
m = divmod(intmin,60)[1]
if (divmod(intmin,60)[0] % 24) >= 12: #假如小时在12到24之间就显示12-24之间小时数
    h = divmod(intmin,60)[0] % 24
    print h,':',m
else:               #在12小时之前的,就显示12以下。
    h = divmod(intmin,60)[0] % 24
    print h,':',m

10、字符串.写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转. 比如,输入"Mr.Ed",应该返回"mR.eD"作为输出.

# -*- coding: utf-8 -*-
import string
def reverse_case(a_string):
    ret_string = ""
    for ch in a_string:
        if ch in string.ascii_uppercase:
            ret_string += str.lower(ch)
        elif ch in string.ascii_lowercase:
            ret_string += str.upper(ch)
        else:
            ret_string += ch

    return ret_string

the_string = raw_input("Plese input a string: ")
    
print(reverse_case(the_string))

11、转换
#      (a)创建一个从整数到IP 地址的转换程序,如下格式: WWW.XXX.YYY.ZZZ.
#      (b)更新你的程序,使之可以逆转换.

def num_to_ip(a_num):
    src = int(a_num)
    str_ip = ""
    mylist = [3,2,1]
    for i in mylist:
        tmp = src//(256**i)
        str_ip += str(tmp)
        str_ip += '.'
        src -= tmp*(256**i)
    str_ip += str(src)
    return str_ip
print num_to_ip('2') #假如输入数字是2,结果应该是0.0.0.2

# _*_ coding= utf-8 _*_
#   ip转整数

def ip_to_num(ip):
    list = ip.split('.')
    list.reverse()
    ret_num = 0
    for i in range(len(list)):
        ret_num += int(list[i]) * pow(256,i)

    return ret_num

ip = raw_input('Please input your ip:\n')
print  ip_to_num(ip)

12、字符串
#     (a)创建一个名字为findchr()的函数,函数声明如下:
#        def findchr(string, char)
#        findchr()要在字符串string 中查找字符char,找到就返回该值的索引,
#        否则返回-1.不能用string.*find()或者string.*index()函数和方法
#     (b)创建另一个叫rfindchr()的函数,查找字符char 最后一次出现的位置.
#        它跟findchr()工作类似,不过它是从字符串的最后开始向前查找的.
#     (c)创建第三个函数,名字叫subchr(),声明如下:
#        def subchr(string, origchar, newchar)
#        subchr()跟findchr()类似,不同的是,
#        如果找到匹配的字符就用新的字符替换原先字符.返回修改后的字符串.

# a\
def findchar(string,char):
    n = 0
    for i in string:
        if i == char:
            print 'Find the Char.'
            break
        else:
            n += 1
    if n == len(string):
        print "Can't find the Char!"
    else:
        return n

string = raw_input("which string ?\n")
char = raw_input("which char ?\n")
print findchar(string,char)
# a 的另外方法,是别人写的,很简洁。
def findchr(string, char):
    index = 'no found'
    for i in range(len(string)):
        if char == string[i]:
            index = i
            break

    return index

# test findchr
print(findchr('abcdeabcde', 'a'))
print(findchr('abcde', 'f'))

# b\
def findchr(string, char):
    index = 'no found'
    rstring = string[::-1]
    for i in range(len(rstring)):
        if char == string[i]:
            index = i
            break
  #  real_index = len(rstring) - 1 -i
    return (len(rstring) - 1 -i)

# test findchr
print(findchr('abcdeabcde', 'b'))
print(findchr('abcda', 'a'))

# b的别人的方法
#(b)
def rfindchr(string, char):
    index = -1
    for i in range(len(string)):
        if char == string[len(string)-1-i]:
            index = len(string)-1-i
            break

    return index

# test rfindchr
print(rfindchr('abcdeabcde', 'a'))
print(rfindchr('abcde', 'f'))

# c\
def subchr(string, origchar,newchar):
    index = 'no found'
    list = []
    for i in range(len(string)):
        if origchar == string[i]:
            list.append(i)
            string = string[0:i] + newchar +string[i+1:]
    if len(list) == 0:
        return index
    else:
        return string
# test subchr
print(subchr('abcdeabcde', 'a','k'))
print(subchr('abcde', 'e','l'))
# c 别人的方法

13、字符串.string 模块包含三个函数,atoi(),atol(),和atof(),
#     它们分别负责把字符串转换成整数,长整型,和浮点型数字.
#     从Python1.5 起,Python 的内建函数int(),long(),float()也
#     可以做相同的事了, complex()函数可以把字符串转换成复数.
#     (然而1,5 之前,这些转换函数只能工作于数字之上)string 模
#     块中并没有实现一个atoc()函数,那么你来实现一个,atoc(),
#     接受单个字符串做参数输入,一个表示复数的字符串,例如,
#     '-1.23e+4-5.67j',返回相应的复数对象.你不能用eval()函数,
#     但可以使用complex()函数,而且你只能在如下的限制之下使用
#     complex():complex(real,imag)的real 和imag 都必须是浮点值.
#  别人做的,我只是参考

def atoc(complexstring):
    i = 1
    while i < len(complexstring):
        if complexstring[i] == 'e':
            i += 1
        elif complexstring[i] in ['+', '-']:
            real = complexstring[:i]
            image = complexstring[i:]
            break
        i += 1
    
    print real, image[:-1]
    return complex(float(real), float(image[:-1]))


print(atoc("-1.23e+4-5.67j"))

6-14、随机数.设计一个"石头,剪子,布"游戏,有时又叫"Rochambeau",
#      你小时候可能玩过,下面是规则.你和你的对手,在同一时间做出特
#      定的手势,必须是下面一种手势:石头,剪子,布.胜利者从下面的规
#      则中产生,这个规则本身是个悖论.
#      (a) the paper covers the rock,布包石头.
#      (b)石头砸剪子,
#      (c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算
#        机找一个随机选项,然后由你的程序来决定一个胜利者或者平手.
#        注意:最好的算法是尽量少的使用if 语句.

import random

lpaperrock = ["paper", "rock", "shears"]
dpaperrock = {"1":'paper', "2":'rock', "3":'shears'}
drule = {'12':'WIN', '23':'WIN', '31':'WIN', '11':'Draw', '22':'Draw', '33':'Draw',
         '21':'Fail', '32':'Fail', '13':'Fail'}

def rochambeau(a_string):
    robot = random.randrange(1, 4)
    print
    print(drule[str(a)+str(robot)])

    print("robot is " + str(lpaperrock[robot-1]))
    
a = input('what is your input?\n1.paper\n2.rock\n3.shears\n')
rochambeau(a)

15、

# 6–15.转换
#      (a)给出两个可识别格式的日期,比如 MM/DD/YY 或者 DD/MM/YY 格式,计算出两个日期间的天数.
#      (b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月.
#      (c)还是上面的例子,计算出到此人下次过生日还有多少天.

# (a)
# 非润年的每月的天数
monthdays = (31,28,31,30,31,30,31,31,30,31,30,31)

# 判断润年
def is_leap(year):
    return (( year%4==0 and year%100!=0) or (year%400==0))

# 一年中的天数
def days_of_year(year):
    days = 365
    if is_leap(year):
        days += 1

    return days

# 两年之间的天数    
def days_between_years(small_year, big_year):
    days = 0
    for year in range(small_year, big_year):
        days += days_of_year(year)

    return days

# 某年某月某日是当前年的第几天    
def which_day_for_year(date):
    days = int(date[2]);

    for i in range(0, int(date[1])-1):
        days += monthdays[i]

    if is_leap(int(date[0])):
        days += 1

    return days

# 日期格式 YY/MM/DD    
def days_between_dates(small_date, big_date):
    date1 = small_date.split('/')
    date2 = big_date.split('/')

    if date1 < date2:
        small = date1
        big = date2
    else:
        big = date1
        small = date2
        
    days = days_between_years(int(small[0]), int(big[0]))
    days -= which_day_for_year(small)
    days += which_day_for_year(big)
    
    return days

# print(days_between_dates("2014/05/24", "1990/12/31"))
    

# (b)
# -*- coding: utf-8 -*-
import datetime
# 判断润年,闰月
def is_leap(year):
    return (( year%4==0 and year%100!=0) or (year%400==0))

def num_of_leafmouth(birthday):
    now = datetime.datetime.now().strftime("%Y/%m/%d")
    date1 = birthday.split('/')
    date2 = now.split('/')
    days1 = 0 
    for i in range(int(date1[0])+1,int(date2[0])):
        print i
        print days1
        if is_leap(i):
            days1 += 1
    if int(date1[1]) <= 2:
        days1 += 1
    if int(date2[1]) >= 2:
        days1 += 1
    return days1
print num_of_leafmouth('2010/02/01')

# # (c)
# def days_to_birth(birthday):
#     now = datetime.datetime.now().strftime("%Y/%m/%d")
#     now_year = int(now.split('/')[0])
#     now_month = int(now.split('/')[1])
#     now_day = int(now.split('/')[2])

#     birth_year = int(birthday.split('/')[0])
#     birth_month = int(birthday.split('/')[1])
#     birth_day =  int(birthday.split('/')[2])

#     if now_month > birth_month:
#         next_birth = str(now_year+1)+'/'+str(birth_month)+'/'+str(birth_day)
#     elif now_month < birth_day.split('/')[1]:
#         next_birth = str(now_year)+'/'+str(birth_month)+'/'+str(birth_day)
#     elif now_day > birth_day:
#         next_birth = str(now_year+1)+'/'+str(birth_month)+'/'+str(birth_day)
#     else:
#         next_birth = str(now_year)+'/'+str(birth_month)+'/'+str(birth_day)

#     print now, next_birth
        
#     return days_between_dates(now, next_birth)
        
# print days_to_birth("2013/04/24")

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

# 6–16.矩阵.处理矩阵M 和N 的加和乘操作.


#矩阵暂时没学。等学之后再处理

# 6–17.方法.实现一个叫myPop()的函数,
# 功能类似于列表的pop()方法,用一个列表作为输入,移除列表的最新一个元素,并返回它.

def MyPop(list):
    if poplist.count == 0:  
        return None 
    print list[-1]
    list = list[:-1]
    #print list #这一句是调试语句
    
a = input('your list')
MyPop(a)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值