Python核心编程第二版第六章序列:字符串,列表和元组(课后习题)----我的答案

6-1.字符串。string模块中是否有一种字符串方法或者函数可以帮我鉴定下一个字符串是否是另一个大字符串的一部分?

判断一个字符串是否包含另一个字符串: find()、index()、rfind()、rindex()

import string
s = 'sdadaadaa'
print s.find('dad')
print s.index('sda')

6-2.字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kwlist)来帮你.

import string
import keyword

alphas = string.letters + '_'
nums = string.digits
kw = keyword.kwlist

print 'Welcome to the Identifier Checker v1.1'
print 'Now we can check keyword.'
print 'Teatees must be at least 1 chars long.'
myInput = raw_input('Identifier to test?')

if len(myInput) > 0:
    if myInput[0] not in alphas:
        print '''invalid: first symbol must be alphabetic'''
    elif myInput in kw:
        print 'that is a keyword in Python'
    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"

6-3.排序

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

aList = [1, 2, 7, 8 ,4, 3]
aList.sort()
print aList

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

aList = {'name': 'cytus', 'age': 18, 'like': 'dog'}
print sorted(aList.keys())
print sorted(aList.items(), key= lambda item:item[1])

6-4.算术。更新上一章里面你的得分测试练习方法方案,把测试得分放到一个列表中去。你的代码可以算出一个平均数。

def testScore():
    if score >= '90' and score <= '100':
        print("Your testscore is A.")
    elif score >= '80' and score <= '89':
        print("Your testscore is B.")
    elif score >= '70' and score <= '79':
        print("Your testscore is C.")
    elif score >='60' and score <= '69':
        print("Your testscore is D.")
    elif score < '60':
        print("Your failed in this test and got a F.")
    else:
        print("Try input some numbers.")

yourScore = []

while True:
    score = raw_input("Input your real grade or enter q to quit: ")

    if score == 'q':
        break
    else:
        yourScore.append(int(score))
    print 'The avar is %f.' % float(sum(yourScore)/len(yourScore))

    testScore()

6-5.字符串

(a).更新你在练习2-7中的方案, 使之可以每次向前向后都显示一个字符串的一个字符。

import string
Strings = raw_input('Input some strings:> ')
for i in Strings:
    print i
print '\n'
for i in Strings[::-1]:
    print i

(b).通过扫描来判断两个字符串是否匹配。

String1 = raw_input('Input first str: ')
String2 = raw_input('Input second str: ')
if len(String1) != len(String2):
    print 'They are not the same.'
else:
    for i in xrange(len(String1)):
        if String1[i] == String2[i]:
            print 'They are the same.'
        else:
            print 'They are not same.'

在这里把扫描理解成遍历字符串。

扫描二维码关注公众号,回复: 917230 查看本文章

附加题:在你的方案里加入大小写区分。

(c).

String = ['level']
s = []
t = []
for i in String:
    s = s.append(i)

for n in String[::-1]:
    t = t.append(n)

if s == t:
    print 'The str is a huiwen.'
else:
    print 'The str is not a huiwen.'
(d).
s = []
String = ['l', 'o', 'v', 'e']
for i in String[::-1]:
    s.append(i)

String += s
print String

6-6.字符串。创建一个string.strip()的替代函数:接受一个字符串,去掉它前后的空格。

#coding:utf-8
str1 = raw_input("Enter a string -->")
if str1[0] == ' ':
    if str1[-1] == ' ':
        str1 = str1[1:-1]
    else:
        str1 = str1[1:]
elif str1[-1] == ' ':
    str1 == str1[:-1]

print str1

删除所有空格没有思路

6-7.调试。看一下在例6.5中给出的代码

(a).

#coding=utf-8
#从用户那接受一个数字传给num_str
num_str = raw_input('Enter a number: ')
#将num_str强制转换为int类型给num_num
num_num = int(num_str)
#将1-num_num+1之间的数传给fac_list
fac_list = range(1, num_num+1)
print "BEFORE:", 'fac_list'
#设置一个i=0的变量
i = 0
#while循环
while i < len(fac_list):
    #如果num_num能整除fac_list里的数,则删除fac_list的那个数
    if num_num % fac_list[i] == 0:
        del fac_list[i]
    #if语句结束i进位
    i = i + 1
#输出循环结束后的fac_list
print "AFTER:", 'fac_list'

我在pycharm上运行的时候程序输入偶数并没有死掉,结果

Enter a number: 6
Before: [1, 2, 3, 4, 5, 6]
After: [2, 4, 5]

2并没有被删掉,试了一下其他偶数,删除结果每次都会漏掉2,输入奇数没有任何问题

#coding:utf-8
#得到一个用户输入
num_str = raw_input('Enter a number: ')

#将用户输入的数字字符转化成int类型
num_num = int(num_str)

#创建一个1~用户输入数字的列表
fac_list = range(1, num_num + 1)
print "Before:",fac_list

# 定义一个整型变量并赋值为0
i = 0
deleted = []

# while循环判断条件
while i < len(fac_list):
    # 用户输入数字对里表中index 为i的数字求余.
    if num_num % fac_list[i] == 0:
        deleted.append(fac_list[i])#修改此处.

    # 变量自增.
    i = i + 1
for ch in deleted:
    fac_list.remove(ch)

print "After:", fac_list

参考

6-8.列表。给出一个整型值,返回代表该值的英文。

#coding=utf-8
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','fifth','sixty','seventy','eighty','ninety']
hundreds = ['hundreds']

myInput = raw_input("Enter an integer -->")
myInput_num = int(myInput)

if myInput_num <=19:
    print units[myInput_num]
elif myInput_num <100:
    tens_unit = int(myInput[0])-2
    unit_unit = int(myInput[1])
    if unit_unit == 0:
        print tens[tens_unit]
    else:
        print tens[tens_unit] + '-' + units[unit_unit]
elif myInput_num < 1000:
    if myInput_num <= 119:
        hundred_unit = int(myInput[0])
        unit_unit = int(myInput[1:])
        print units[hundred_unit] + ' hundreds and ' + units[unit_unit]
    else:
        hundred_unit = int(myInput[0])
        tens_unit = int(myInput[1])-2
        unit_unit = int(myInput[2])
        if unit_unit == 0:
            print units[hundred_unit] + ' hundreds and ' + tens[tens_unit]
        else:
            print units[hundred_unit] + ' hundreds and ' + tens[tens_unit] + '-' + units[unit_unit]

编写时有很多字符错误,复制别人相同代码段又能正常运行。。。。

6-9.转换。为练习5-13写一个姊妹函数,接受分钟数返回小时数和分钟数。总时间不变,并且要求小时数尽可能大。

def tranSh(m):
    hour = mins / 60
    min = mins - hour * 60
    if mins < 60:
        print "The time is %dmins." % mins
    elif mins >= 60:
        print "The time is %d hours and %d mins" % (hour, min)

mins = int(raw_input('Input some mins: '))
tranSh(mins)

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

#coding=utf-8
def caseSwap(str1):
    return str1.swapcase()

myInput = raw_input("Enter a string to swap -->")
print caseSwap(myInput)
#使用了swapcase()内建函数. 也可以使用isupper() 和islower() 来逐个字符转换.

6-11.转换。

(a).创建一个从整型到IP地址的转换程序。

pass

6-12.(a).

#coding:utf-8
def findchr(string,char):
    #enumerate()用于遍历一个数据对象,返回下标和对象,一般用于for循环
    for i,j in enumerate(string):

        if j == char:
            return i
    else:
        return -1


print findchr([1, 2, 3], 3)

(b).

#coding:utf-8
def rfindchr(string,char):
    #enumerate()用于遍历一个数据对象,返回下标和对象,一般用于for循环,start标明下标起始位置
    for i,j in enumerate(string, start=-1):

        if j == char:
            return i
    else:
        return -1


print rfindchr([1, 2, 3], 3)

(c).

def subchr(myString,origChar,newChar): 

    if origChar not in myString: 

        print "-1" 

    else: 

        print myString.replace(origChar,newChar)

6-13.pass

6-14.

#coding:utf-8
from random import randint
while True:

    dict1 = {1: '石头', 2: '剪刀', 3: '布'}
    dict2 = {1: '石头', 2: '剪刀', 3: '布'}

    judge = {('石头','剪刀'): 'Win',('石头','布'): 'Lose',('石头','石头'): 'draw',('剪刀','布'): 'Win',('剪刀','石头'):'Lose',('剪刀',
    '剪刀'):'draw',('布','石头'):'Win',('布','剪刀'):'Lose',('布','布'):'draw',}

    pc_input = dict2[randint(1,3)]
    you_input = dict1[int(raw_input("输入'1'代表石头 '2'代表剪刀 '3'代表布 任何一个: "))]

    print "电脑的选择是:%s , 你的选择是:%s , 结果是:%s " % (pc_input, you_input, judge[pc_input, you_input])

6-15.pass

6-16.矩阵。转

# -*- coding: UTF-8 -*-
 
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
 
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
 
result = [[0,0,0],
         [0,0,0],
         [0,0,0]]
 
# 迭代输出行
for i in range(len(X)):
   # 迭代输出列
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]#乘法就把+改*就行了
 
for r in result:
   print(r)

在python3中numpy库使用array[]直接定义数组,直接用+-*/对array数组进行操作

6-17.

aList = ['123', '2345', 'dasda']


def myPop(m):
    if len(aList) == 0:

        print "You can't pop from an empty list ..."

    else:

        dEle = aList[-1]

        print "Removed [", dEle, "]"

        aList.remove(dEle)

myPop(aList)
print aList

直接使用用户输入的列表必须得有一个存储的函数实现,且存储函数调用必须先于mypop()

6-18.

通过for循环依次将fn[0],ln[0];fn[1],ln[1];fn[2],ln[2]使用zip()数组组合成数组返回,并用title()方法将首字母大写

6-19.pass

猜你喜欢

转载自blog.csdn.net/qq_41805514/article/details/80145239
今日推荐