码迷,mamicode.com
首页 > 编程语言 > 详细

Python核心编程 第六章课后习题

时间:2014-12-14 13:24:23      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:des   style   ar   color   使用   sp   for   on   bs   

6–1.

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

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

Answer:in     not in

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)


Python核心编程 第六章课后习题

标签:des   style   ar   color   使用   sp   for   on   bs   

原文地址:http://my.oschina.net/u/2003106/blog/355948

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!