python核心语法题_Python核心编程 第六章课后习题

6–1.

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

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

Answer:

# 1

str_1 = 'perfect is shit'

if 'shit' in str_1:

print 'INININ!!!'

else:

print 'Not ININININ!!!'

# 2

str_1.find('shit')

str_1.count('shit')

str_1.index('shit')

6-2.

#! /usr/bin/env python

# coding: utf-8

'''

6–2.

字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且

可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.

'''

import string

import keyword

alphas = string.letters + '_'

nums = string.digits

key_list = keyword.kwlist

print 'Welcome to the Identifier Checker v1.0'

print 'Testees must be ai least 2 chars long.'

myInput = raw_input('Identifier to test?')

if len(myInput) >= 1:

if myInput[0] not in alphas:

print '''invalid : first symbol must be alphabetic'''

elif myInput in key_list:

print '''invalid: the input id is a Python's keyword'''

else:

alphnums = alphas + nums

for otherChar in myInput[1:]:

if otherChar not in alphnums:

print '''invalid: remaining symbols must be alphanumeric'''

break

else:

print "okay as an identifier"

6-3.

#! /usr/bin/env python

# coding: utf-8

'''

6–3.

排序

(a) 输入一串数字,从大到小排列之.

(b) 跟 a 一样,不过要用字典序从大到小排列之.

'''

#(a)

def get_num():

global num_list

num_list = []

num = ''

while num != '!':

num = raw_input('输入一些数字,以"!"结束').strip()

if num != '!':

try:

num = float(num)

except:

print '输入有误,请重新输入'

get_num()

else:

num_list.append(num)

else:

break

return num_list

def sort_descending():

get_num()

print sorted(num_list, reverse = True)

print '----------------(a)----------------'

sort_descending()

#(b)

print '-----------------(b)---------------'

key_sort = []

while True:

k = raw_input('输入一些数字吧,以字典序排列大小,以"#"结束输入:')

if k != '#':

key_sort.append(k)

else:

break

print sorted(key_sort, reverse = True)

6-6.

#!/usr/bin/env python

# coding: utf-8

'''

6–6.

字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的

空格(如果使用 string.*strip()函数那本练习就没有意义了)

'''

def blank():

get_str = raw_input('please in put your string: ')

r = len(get_str) - 1

l = 0

while get_str[l] == ' ':

l = l + 1

while get_str[r] == ' ':

r = r - 1

result = get_str[l:r+1]

return result

if __name__ == '__main__':

print blank()

6-8.

#! /usr/bin/env python

# coding: utf-8

'''

6–8.

列表.给出一个整数值,返回代表该值的英文,比如输入 89 返回"eight-nine"。附加题:

能够返回符合英文语法规则的形式,比如输入“89”返回“eighty-nine”。本练习中的值限定在家 0

到 1,000.

'''

# 这道题用字典肯定好做!!!!

def get():

global get_num

get_num = raw_input('please input your number:')

try:

get_num = int(get_num)

except:

print 'Error Input,please input a number!'

get()

else:

print 'Input success!'

#(1)

eng_list = []

eng = "zero,one,two,three,four,five,six,seven,eight,nine,ten"

eng_list = eng.split(',')

result = []

get()

get_list = list(str(get_num))

for i in get_list:

result.append(eng_list[int(i)])

print '-'.join(result)

#(2)

print '------------------附加题-------------------'

'分三组,(1)0-9的数字做一个列表,(2)10-19的数字做一个列表,(3)20、30、40……做一个列表'

str_1 = "zero,one,two,three,four,five,six,seven,eight,nine"

str_2 = "ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty"

str_3 = "thirty,forty,fifty,sixty,seventy,eighty,ninety"

eng_1 = []

eng_2 = []

eng_3 = []

eng_1 = str_1.split(',')

eng_2 = str_2.split(',')

eng_3 = str_3.split(',')

#调用get()

get()

#把输入的数字按“千,百,十,个”位,分割

kilo = get_num / 1000

hund = get_num % 1000 / 100

deca = get_num % 1000 % 100 / 10

unit = get_num % 1000 % 100 %10

'--------------------------------------------------------------------'

#写完才发现,其实用格式化输出更好,连接字符串的方式不太好。

#print '%d thousand- %d hundred' % (eng_1[int(kilo)], eng_1[int(hund)]

'--------------------------------------------------------------------'

if kilo != 0:

if hund != 0 :

if int(deca) >= 2 and unit !=0:

print eng_1[int(kilo)],'thousand','-',eng_1[int(hund)],'hundred','-',eng_3[int(deca)-3],'-',eng_1[int(unit)]

elif int(deca) >= 2 and unit == 0:

print eng_1[int(kilo)],'thousand','-',eng_1[int(hund)],'hundred','-',eng_3[int(deca)-3]

elif 1<=int(deca)<2:

print eng_1[int(kilo)],'thousand','-',eng_1[int(hund)],'hundred','-',eng_2[int(unit)]

elif int(deca)==0 and unit != 0:

print eng_1[int(kilo)],'thousand','-',eng_1[int(hund)],'hundred','-',eng_1[int(unit)]

elif int(deca)==0 and unit == 0:

print eng_1[int(kilo)],'thousand','-',eng_1[int(hund)],'hundred'

elif hund == 0 :

if int(deca) >= 2 and unit !=0:

print eng_1[int(kilo)],'thousand','-',eng_3[int(deca)-3],'-',eng_1[int(unit)]

elif int(deca) >= 2 and unit == 0:

print eng_1[int(kilo)],'thousand','-',eng_3[int(deca)-3]

elif 1<=int(deca)<2:

print eng_1[int(kilo)],'thousand','-',eng_2[int(unit)]

elif int(deca)==0 and unit != 0:

print eng_1[int(kilo)],'thousand','-',eng_1[int(unit)]

elif int(deca)==0 and unit == 0:

print eng_1[int(kilo)],'thousand',

elif kilo == 0:

if hund != 0 :

if int(deca) >= 2 and unit !=0:

print eng_1[int(hund)],'hundred','-',eng_3[int(deca)-3],'-',eng_1[int(unit)]

elif int(deca) >= 2 and unit == 0:

print eng_1[int(hund)],'hundred','-',eng_3[int(deca)-3]

elif 1<=int(deca)<2:

print eng_1[int(hund)],'hundred','-',eng_2[int(unit)]

elif int(deca)==0 and unit != 0:

print eng_1[int(hund)],'hundred','-',eng_1[int(unit)]

elif int(deca)==0 and unit == 0:

print eng_1[int(hund)],'hundred'

elif hund == 0 :

if int(deca) >= 2 and unit !=0:

print eng_3[int(deca)-3],'-',eng_1[int(unit)]

elif int(deca) >= 2 and unit == 0:

print eng_3[int(deca)-3]

elif 1<=int(deca)<2:

print eng_2[int(unit)]

elif int(deca)==0:

print eng_1[int(unit)]

6-9.

#! /usr/bin/env python

# coding: utf-8

'''

6–9.

转换.为练习 5-13 写一个姊妹函数, 接受分钟数, 返回小时数和分钟数. 总时间不

变,并且要求小时数尽可能大.

'''

#5-13.py

'''

def transfomate():

global hour,minute

row_time = raw_input('输入你要转换的时间(格式H:M--> xx:yy):')

time_list = row_time.split(':')

hour = time_list[0]

minute = time_list[1]

total = int(hour) * 60 + int(minute)

return '转换为分钟---->' + str(total)

print transfomate()

'''

def m_trans_h():

get_time = int(raw_input('输入你要转换的时间(分钟数-->一个正整数):'))

hour = get_time / 60

minute = get_time % 60

print hour,'H',':',minute,'M'

m_trans_h()

6-10.

#!/usr/bin/env python

# coding:utf-8

'''

6–10.字符串.写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转.

比如,输入"Mr.Ed",应该返回"mR.eD"作为输出.

'''

str_1 = raw_input('Enter your string:')

str_list = list(str_1)

result_list = []

for i in str_list:

if i.isupper():

result_list.append(i.lower())

elif i.islower():

result_list.append(i.upper())

else:

result_list.append(i)

result = ''.join(result_list)

print 'Before: %s' % str_1

print 'After: %s' % result

6-11.

#!/usr/bin/env python

# coding: utf-8

'''

6–11.转换

(a)创建一个从整数到 IP 地址的转换程序,如下格式: WWW.XXX.YYY.ZZZ.

(b)更新你的程序,使之可以逆转换.

'''

#(a)

print '--------------(a)--------------'

def format_ip():

num = raw_input('Enter ip number(12 integer)')

w = num[0:3]

x = num[3:6]

y = num[6:9]

z = num[9:12]

tmp = [w,x,y,z]

ip = '.'.join(tmp)

return ip

if __name__ == '__main__':

print format_ip()

#(b)

print '--------------(b)--------------'

def re_format_ip():

ip = raw_input('Enter ip:')

tmp = ip.split('.')

num = ''.join(tmp)

return num

if __name__ == '__main__':

print re_format_ip()

6-12.

#!/usr/bin/env python

# coding:utf-8

'''

6–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()类似,不同的是,如果找到匹配的字符就用新的字符替换原先字符.返回

修改后的字符串.

'''

import types

#(a)

def findchr(string, char):

print 'The string is "%s" and the char is "%s"' % (string, char)

result = []

for i, j in enumerate(string):

if char == j:

result.append(i)

if len(result) != 0:

print 'the index of char:'

return result

else:

return -1

#(b)

def rfindchr(string, char):

print 'The string is "%s" and the char is "%s"' % (string, char)

l = len(string)

for i, j in enumerate(string[::-1]):

if char == j:

result = l-i

break

if type(result) is types.IntType :

print 'the last index of char:'

return result

else:

return -1

#(c)

def subchr(string, origchar, newchar):

print 'The string is "%s" ,the origchar is "%s" and the char is "%s"' % (string, origchar,newchar)

result = []

str_list = list(string)

for i, j in enumerate(str_list):

if origchar == j:

str_list[i] = newchar

result = ''.join(str_list)

return result

print '----(a)-----'

print findchr('dota is the best','i')

print '----(b)-----'

print rfindchr('dota is the best!','t')

print '----(c)-----'

print subchr('I love dota','I','We')

6-13.

#! /usr/bin/env python

# coding: utf-8

'''

6–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(string):

flag_index = string.rfind('-')

if flag_index <= 0:

flag_index = string.rfind('+')

if flag_index > 0:

real = float(string[0:flag_index])

imag = float(string[flag_index:-1])

return complex(real,imag)

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

6.-14.

写来写去想了好久,决定还是用字典最简单啦

#!/usr/bin/python

#coding:utf-8

#author:toddler

#date:Jan 14 2015

'''

6–14.随机数.设计一个"石头,剪子,布"游戏,有时又叫"Rochambeau",你小时候可能玩过,下面

是规则.你和你的对手,在同一时间做出特定的手势,必须是下面一种手势:石头,剪子,布.胜利者从

下面的规则中产生,这个规则本身是个悖论.

(a) the paper covers the rock,

布包石头.

(b)石头砸剪子,

(c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算机找一个随机选项,然后由你

的程序来决定一个胜利者或者平手.注意:最好的算法是尽量少的使用 if 语句.

'''

from random import choice

def Rochambeau(idea):

dict_choice = {'stone':'1','shear':'2','paper':'3'}

dict_result = {'11':'draw','22':'draw','33':'draw','12':'win','13':'lose','21':'lose','23':'win','31':'win','32':'lose'}

cpu_choice = choice(['stome','shear','paper'])

print "cpu choice : %s" % cpu_choice

return "the result is : %s" % dict_result[dict_choice[idea] + dict_choice[cpu_choice]]

if __name__ == "__main__":

while True:

idea = raw_input("Please input your idea: stone or shear or paper (e to exit)\n")

print "-----------------------------------------"

print "your choice : %s" % idea

if idea.lower().strip() == 'e':

break

elif (idea != 'stone') and (idea != 'shear') and (idea != 'paper'):

print "Please check your input"

continue

print Rochambeau(idea)

6-15.

#!/usr/bin/env python

# coding:utf-8

# date: Jan 15 2015

# author: toddlerya

"""

6–15.转换

(a)给出两个可识别格式的日期,比如 MM/DD/YY 或者 DD/MM/YY 格式,计算出两个日期间的天

数.

(b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月.

(c)还是上面的例子,计算出到此人下次过生日还有多少天

"""

from datetime import date

def calcdate(string1, string2):

temp_list1 = string1.split("/")

temp_list2 = string2.split("/")

days_count = ""

first_date = date(int(temp_list1[2]), int(temp_list1[1]), int(temp_list1[0]))

second_date = date(int(temp_list2[2]), int(temp_list2[1]), int(temp_list2[0]))

if first_date < second_date:

days_count = abs(second_date - first_date)

return days_count.days

# 以一个人的生日为参数,计算从此人出生到现在的天数,包括所有的闰月

def calcbirth(string):

today = date.today()

time_to_birth = ""

temp_list = string.split("/")

birth = date(int(temp_list[2]), int(temp_list[1]), int(temp_list[0]))

if birth < today:

time_to_birth = abs(today - birth)

else:

print("Please input the right birth")

return time_to_birth.days # 返回计算后的天数,用".days"取得天数,舍去小数点

def nextbirth(string):

today = date.today()

time_to_birth = ""

temp_list = string.split("/")

month_day = date(today.year, int(temp_list[1]), int(temp_list[0]))

birth = date(int(today.year+1), int(temp_list[1]), int(temp_list[0]))

if today < month_day:

next_time_to_birth = abs(month_day - today)

elif today < birth:

next_time_to_birth = abs(birth - today)

else:

print("Please input the right birth")

return next_time_to_birth.days # 返回计算后的天数,用".days"取得天数,舍去小数点

if __name__ == "__main__":

while True:

choice = raw_input("I can do something:\na: Count the number of days between two date\n"

"b: Count the number of days since you born\n"

"c: Count the number of days before your next birth\n"

"q to quit\n")

if choice == 'q':

break

elif choice == 'a':

str_1 = raw_input("Please enter your first date: like DD/MM/YY \n")

str_2 = raw_input("Please enter your second date\n")

try:

print("The number of days between two date is", calcdate(str_1, str_2))

except:

print("Please check your enter format DD/MM/YY")

elif choice == 'b':

str_date = raw_input("Please enter your date: like DD/MM/YY \n")

try:

print "You had born", calcbirth(str_date), "days"

except:

print("Please check your enter format DD/MM/YY")

elif choice == 'c':

str_date = raw_input("Please enter your birth date: like DD/MM/YY \n")

try:

print "There are", nextbirth(str_date), "days of your next birthdays"

except:

print("Please check your enter format DD/MM/YY")

6-16.

真是笨,想了那么久,勤能补拙,多写多练(づ ̄3 ̄)づ

#!/usr/bin/env python

# coding:utf-8

# author: toddlerya

# date: Jan 15 2015

"""

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

"""

def matrix_add(mat_1, mat_2):

# 矩阵加法应满足两个矩阵的行数列数相同

if len_m1 != len_m2:

print "Error, two matrix must have the same dimension!"

return

elif len_n1 != len_n2:

print "Error, two matrix must have the same dimension!"

return

else:

res_matrix = []

for m in range(len_m1):

res_matrix.append([])

for n in range(len_n1):

res_matrix[m].append(mat_1[m][n] + mat_2[m][n])

return res_matrix

def matrix_multiply(mat_1, mat_2):

# 矩阵乘法不满足交换律;矩阵乘法满足结合律

if len_n1 != len_m2:

print "Error, the dimension of matrix is wrong!"

else:

res_matrix = []

for m in range(len_m1):

res_matrix.append([])

for r in range(len_n1):

res_matrix[m].append(0)

for n in range(len_n2):

res_matrix[m][r] += mat_1[m][n] * mat_2[n][r]

return res_matrix

def enter():

global matrix_1, matrix_2, len_m1, len_n1, len_m2, len_n2

matrix_1 = input("Please input the matrix M\n")

matrix_2 = input("Please input another matrix N\n")

len_m1 = len(matrix_1)

len_n1 = len(matrix_1[0])

len_m2 = len(matrix_2)

len_n2 = len(matrix_2[0])

if __name__ == "__main__":

while True:

choice = raw_input("Matrix addition(A) or Matrix multiplication(B) (q to quit)\n").lower()

if choice == "a":

enter()

print matrix_add(matrix_1, matrix_2)

elif choice == "b":

enter()

print matrix_multiply(matrix_1, matrix_2)

elif choice == 'q':

break

elif choice != "a" or "b" or "q":

print "Please check your enter!"

6-17.

#!/usr/bin/env python

# coding:utf-8

"""

6–17.方法.实现一个叫 myPop()的函数,功能类似于列表的 pop()方法,用一个列表作为输入,

移除列表的最新一个元素,并返回它.

"""

def myPop(alist):

new_list = alist[:-1]

return new_list

if __name__ == "__main__":

get_list = input("Please input your list: \n")

print "The initializing list is %s" % get_list

print "The new list is", myPop(get_list)

6-18.

zip() 内建函数

在 6.13.2 节里面关于 zip()函数的例子中,zip(fn,ln)返回的是什么?

200326_9Azu_2003106.png

返回的是元组。

6-19.

#!/usr/bin/env python

# coding:utf-8

# author:toddlerya

# date:Jan 17 2015

"""

6–19.多列输出.有任意项的序列或者其他容器,把它们等距离分列显示.由调用者提供数据和

输出格式.例如,如果你传入 100 个项并定义 3 列输出,按照需要的模式显示这些数据.这种情况下,应

该是两列显示 33 个项,最后一列显示 34 个.你可以让用户来选择水平排序或者垂直排序.

"""

def reverse_matrix(a_list):

"""反转矩阵"""

row = len(a_list)

col = len(a_list[0])

col_temp = []

res_rev_matrix = []

for c in range(col):

for r in range(row):

col_temp.append(a_list[r][c])

res_rev_matrix.append(col_temp)

col_temp = [] # 必须清空该列表,否则影响后面的数据

" 不足的空格补'*' "

sub = len(res_rev_matrix[0]) - (len(a_list[row - 1]) - len(a_list[row - 2]))

if sub != len(res_rev_matrix[0]):

res_rev_matrix.append(["*"] * sub + a_list[row - 1][col:len(a_list[row - 1])])

return res_rev_matrix

def multi_print(b_list, line, style=True):

length = len(b_list)

res_matrix = []

interval = length / line

remainder = length % line

if 0 == remainder:

x = 0

y = 0

while y < line:

res_matrix.append(b_list[x:x + interval])

x += interval

y += 1

else:

x = 0

y = 0

while y < line-1:

res_matrix.append(b_list[x:x + interval])

x += interval

y += 1

res_matrix.append(b_list[x:x + interval+remainder])

if not style:

return reverse_matrix(res_matrix)

return res_matrix

if __name__ == "__main__":

result = []

container = []

for i in range(1, 101):

container.append(i)

print "水平排序:\n"

result = multi_print(container, 5)

for i in result:

print i

print "\n\n"

print "垂直排序:\n"

result = multi_print(container, 8, False)

for i in result:

print i

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值