Python核心編程 第六章課後習題

6–1.
python

字符串.string 模塊中是否有一種字符串方法或者函數能夠幫我鑑定一下一個字符串git

是不是另外一個大字符串的一部分?算法

Answer:app

# 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.
dom

#! /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.ide

#! /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.ui

#! /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.idea

#! /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.spa

#!/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)返回的是什麼?

返回的是元組。

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
相關文章
相關標籤/搜索