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

#!/usr/bin/env python
def check_id(myInput):
        import string
        import keyword
        alphas = string.letters + '_'
        nums = string.digits
        alphanums = alphas + nums
        key = keyword.kwlist
        str_length = len(myInput)
        if str_length == 0:
                print 'WRONG: zero-lengthed string("%s").'%(myInput)
        elif myInput[0] not in alphas:
                print '''invalid: first symbol must be alphabetic'''
        elif myInput in key:
                print '''invalid :Input cannot be a keyword'''
        else:
                for otherChar in myInput[1:]:
                        if otherChar not in alphanums:
                                print '''invalid: remaining symbols must be alphanumertic'''
                                break
                else:
                        print '%s is logal identifier.' % (myInput)
if __name__ == '__main__':
        while True:
                myInput = raw_input('Identifier to test?')
                check_id(myInput)       

6-3.排序

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

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

s = raw_input('please enter a serial of numbers,using SPACE to seperate: \n')
import string
alphas = string.digits + " "
for eachs in s:
        if eachs not in alphas:
                print 'you may have entered non-digit character.'
                break
a = s.strip()
s_input = a.split(" ")
num = []
for i in s_input:
        num.append(int(i))
num.sort()
num.reverse()
print 'Sorted result(Big-->Small): ',
for t in num:
        print t,
print
print 'acording the directory to get result: ',
for i,j in enumerate(num):
        print (i,j),                    

6-6.字符串.创建一个 string.strip()的替代函数:接受一个字符串,去掉它前面和后面的空格(如果使用 stri

ng.*strip()函数那本练习就没有意义了)

#!/usr/bin/env python
s = raw_input('please enter a string : ')
print 'the strip of string is :',
import string
alpha = ' ' + string.letters
st = []
for c in s :
        if c not in alpha:
                print 'Error:you may have entered non-string'
                exit(0)
                break
l = len(s)
i = 0
while i < l:
        if s[i] == ' ':
                i += 1
        else:
                break
s = s[i:]
l = len(s) - 1
while l > 0:
        if s[l] == ' ':
                l -= 1
        else:
                break
s = s[:l+1]
print s

6-7.调试。看一下在例 6.5 中给出的代码(buggy.py),这个程序有一个很大的问题,比如输入 6,12,20,30,等它会死掉,实际上它不能处理任何的偶数,找出原因。

#!/usr/bin/env python
num_str = raw_input('Enter a number: ')
num_num = int(num_str)
fac_list = range(1, num_num+1)
print "BEFORE:", fac_list
set_fac = set(fac_list)
i = 0
while i < len(fac_list):
        if num_num % fac_list[i] == 0:
                del fac_list[i]
        else:
                i = i + 1
print "AFTER:"+str(fac_list)
print "Factors of %d are: "%num_num, str(list(set_fac-set(fac_list)))

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

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
alpha = ['one','two','three','forth','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen',\
                 'fifteen','sixteen','seventeen','eighteen','nineteen','twenty','']
tendigits = ['twenty','thirty','forty','fifty','sixty','eighty','ninety','']
s_num = raw_input("enter a number: ")
s = int(s_num)
if s < 0:
        print 'Error:you may have entered a minus.'
elif s <= 20:
        print alpha[s - 1]
elif s < 100:
        i = s / 10
        j = s - i * 10
        print tendigits[i - 2]+'-'+alpha[j - 1]
elif s <1000:
a = s / 100
b = (s - a * 100) / 10
c = s - a * 100 - b * 10
if b == 0 and c ==0:
print alpha[a - 1]+' hundred'
elif b == 0 and c != 0:
print alpha[a-1]+' hundred'+' and '+alpha[c-1]
elif b != 0 and c == 0:
print alpha[a-1] + tendigits[b-2]
else:
print alpha[a - 1]+' hundred'+' and '+tendigits[b - 2]+'-'+alpha[c - 1]
elif s == 1000:
print 'one thousand'

6-10.字符串。写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写翻转。比如,输入“Mr.Ed”,应该返回“mR.eD”作为输出。

#!/usr/bin/env python
#_*_ coding: utf-8 _*_
def reverseletters():
        str_input = raw_input('Input a string : ')
        #str_input.upper()
        #str_input.lower()
        print str_input.swapcase()
if __name__ =='__main__':
        reverseletters()

6-12. 字符串.

a). 创建一个名字为 findchr() 的函数, 函数声明如下:

def findchr(string, char)

findchr() 要在字符串 string 中查找字符 char, 找到就返回该值的索引,否则返回-1. 不能用string.*find()

或者 string.*index() 函数和方法.

#!/usr/bin/env python
#_*_ coding : utf-8 _*_
def findchr(string,char):
        i = 0
        l = len(string)
        if char not in string:
                print -1
        else:
                while i < l:
                        if string[i] == char:
                                print i,
                        i += 1
if __name__ == '__main__':
        string = raw_input("please input a string :")
        char = raw_input('a char:')
        findchr(string,char)

b). 创建另一个叫 rfindchr() 的函数,查找字符 char 最后一次出现的位置. 它跟findchr() 工作类似,不过它是

从字符串的最后开始向前查找的.

#! /usr/bin/env python
#_*_ coding : utf-8 _*_
def rfindchar():
        str_input = raw_input('please enter a string :')
        str_char = raw_input('please enter a char :')
        l = len(str_input)
        i = -1
        for a in range(i,-l-1,-1):
                while i >= -l:
                        if str_input[a] == str_char:
                                print a+l

c). 创建第三个函数, 名字叫做 subchr(), 声明如下:

def subchr(string, origchar, newchar)

subchr() 跟 findchr() 类似, 不同的是, 如果找到匹配的字符就用新的字符替换原先字符.返回修改后的字符.

#! /usr/bin/env python
#_*_ coding:utf-8 _*_
def subchar(string, origchar, newchar):
        l = len(string)
        i = 0
        while i < l:
                if string[i] == origchar:
                        string = string[:i]+newchar+string[i+1:]
                i += 1
        print string
if __name__ == '__main__':
        string = raw_input('please enter a string :')
        origchar = raw_input('input a origchar : ')
        newchar = raw_input('input a new char : ')
        subchar(string,origchar,newchar)

6-14. 随机数. 设计一个"石头,剪子,布"游戏,有时又叫"Rochambeau", 你小时候可能玩过,下面是规则. 你和你的对手, 在同一

时间做出特定的手势,必须是下面一种: 石头,剪子,布. 胜利者从下面规则中产生,这个规则本身是个悖论.

a). 布包石头;

b). 石头砸剪子

c). 剪子剪破布.

在你的计算机版本中, 用户输入她/他的选项, 计算机找一个随机选项,然后由你的程序来决定一个胜利者或者平手.

注意: 最好的算法是尽量少的使用if语句.

#!/usr/bin/env python
#_*_ coding : utf-8 _*_
def Rochambeau():
        text = {0 : 'Cloth', 1 : 'Scissor', 2 : 'Stone'}
        import random
        mac = random.randrange(0,3,1)
        humans = int(raw_input('your choice(0-Cloth, 1-Scissor, 2-Stone):'))
        nums = range(0,3,1)
        print "You: %s   Computer: %s " % (text[humans], text[mac])
        print 'the result is : '
        if humans not in nums:
                print 'Error:Wrong input!'
        elif humans-mac == 0:
                print 'Draw'
        elif humans-mac == 1 or humans-mac == -2:
                print 'You win !!!'
        else:
                print 'Computer win !!!'
if __name__ == '__main__':
        while True:
                Rochambeau()