xylz,imxylz

关注后端架构、中间件、分布式和并发编程

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  111 随笔 :: 10 文章 :: 2680 评论 :: 0 Trackbacks

6-13. Strings. The string module contains three functions, atoi(), atol(), and atof(), that convert strings to integers, long integers, and floating point numbers, respectively. As of Python 1.5, the Python built-in functions int(), long(), and float() can also perform the same tasks, in addition to complex(), which can turn a string into a complex number. (Prior to 1.5, however, those built-in functions converted only between numeric types.)

An atoc() was never implemented in the string module, so that is your task here. atoc() takes a single string as input, a string representation of a complex number, e.g., '-1.23e+4-5.67j', and returns the equivalent complex number object with the given value. You cannot use eval(), but complex() is available. However, you can only use complex() with the following restricted syntax: complex(real, imag) where real and imag are floating point values.
 

 1#!/usr/bin/env python
 2#-*- coding:utf-8 -*-
 3#$Id: p0613.py 148 2010-06-01 04:31:56Z xylz $
 4
 5'''
 6This is a 'python' study plan for xylz.
 7Copyright (C)2010 xylz (www.imxylz.info)
 8'''
 9
10def atoc(s):
11    """Take a single string as input, a string representation of a complex number, e.g., '-1.23e+4-5.67j', and returns the equivalent complex number object with the given value.
12    """
13    if not s:raise ValueError
14    if 'j' != s[-1]: return complex(float(s),0)
15    #process '+5j'
16    ns = s.replace('e+','xx').replace('e-','yy')
17    f = ns.find('+',1)
18    if f == -1: f = s.find('-',1)
19    if f == -1:
20        return complex(0,float(s[:-1]))
21    return complex(float(s[0:f]),float(s[f:-1]))
22
23if __name__ == '__main__':
24    print atoc('+1.0')
25    print atoc('+2.3e+10+10.2j')
26    print atoc('-2.3j')
27    print atoc('-1-2.j')
28



6-14. *Random Numbers. Design a "rock, paper, scissors" game, sometimes called "Rochambeau," a game you may have played as a kid. Here are the rules. At the same time, using specified hand motions, both you and your opponent have to pick from one of the following: rock, paper, or scissors. The winner is determined by these rules, which form somewhat of a fun paradox:

the paper covers the rock,

the rock breaks the scissors,

the scissors cut the paper. In your computerized version, the user enters his/her guess, the computer randomly chooses, and your program should indicate a winner or draw/tie. Note: The most algorithmic solutions use the fewest number of if statements.
 

 1#!/usr/bin/env python
 2#-*- coding:utf-8 -*-
 3#$Id: p0614.py 149 2010-06-03 14:19:43Z xylz $
 4
 5from random import randint
 6
 7'''
 8This is a 'python' study plan for xylz.
 9Copyright (C)2010 xylz (www.imxylz.info)
10'''
11
12(rock,paper,scissors) = (-1,0,1)
13ret = {-2:'win',-1:'loss',0:'draw',1:'win',2:'loss'}
14
15def check(select):
16    'a "rock, paper, scissors" game'
17    return ret[select - randint(-1,1)]
18    
19
20
21if __name__ == '__main__':
22    while True:
23        s = raw_input("select 'rock','page','scissors' as -1,0,1: ")
24        try:
25            select = int(s)
26            if -1<=select<=1:
27                print "You ",check(select),"!"
28            else:
29                break
30        exceptbreak
31




6-15. Conversion.

Given a pair of dates in some recognizable standard format such as MM/DD/YY or DD/MM/YY, determine the total number of days that fall between both dates.

Given a person's birth date, determine the total number of days that person has been alive, including all leap days.

Armed with the same information from (b) above, determine the number of days remaining until that person's next birthday.
 

 1#!/usr/bin/env python
 2#-*- coding:utf-8 -*-
 3#$Id: p0615.py 150 2010-06-03 15:45:09Z xylz $
 4
 5from datetime import datetime
 6
 7'''
 8This is a 'python' study plan for xylz.
 9Copyright (C)2010 xylz (www.imxylz.info)
10'''
11
12mondays = (31,28,31,30,31,30,31,31,30,31,30,31)
13leapmondays = (31,29,31,30,31,30,31,31,30,31,30,31)
14
15def isleap(year):
16    return year%400==or (year%4==and year%100!=0)
17
18def getmondays(month,year):
19    return leapmondays[month-1if isleap(year) else mondays[month-1]
20
21def checkday1(day):
22    'check day in "01/01/1970 ~ 31/12/2030" '
23    (sm,sd,sy) = day.split('/')
24    (m,d,y) = ( int(sm),int(sd),int(sy) )
25    if 1<=m<=12 and 1<=d<=31 and (70<=y<=99 or 0<=y<=30):
26        if y>=70: y += 1900
27        if y<=30: y += 2000
28        for ys in range(1970,y,1):
29            d += 366 if isleap(ys) else 365
30        for ms in range(1,m,1):
31            d += getmondays(ms,y)
32        return d
33    raise ValueError,'Error Date'
34
35def getdaysbetweentwodate(date1,date2):
36    return checkday1(date2) - checkday1(date1)
37    
38def getdaysbetweentwodate2(date1,date2):
39    return (datetime.strptime(date2,'%m/%d/%y'- datetime.strptime(date1,'%m/%d/%y')).days
40    
41def getbirthdays(day):
42    return (datetime.now() - datetime.strptime(day,'%m/%d/%y')).days
43
44def getnextbirthdays(day):
45    birthday = datetime.strptime(day,'%m/%d/%y')
46    now = datetime.now()
47    nextbirthday = now.replace(month=birthday.month,day=birthday.day)
48    if nextbirthday <= now: nextbirthday=nextbirthday.replace(year=nextbirthday.year+1)
49    return (nextbirthday - now).days
50
51
52if __name__ == '__main__':
53    print getdaysbetweentwodate('02/02/84','03/03/84')
54    print getdaysbetweentwodate('12/02/84','03/03/85')
55    print getbirthdays('12/04/84')
56    print getnextbirthdays('12/04/84')
57    print getnextbirthdays('06/03/84')
58    print getnextbirthdays('06/02/84')
59




6-16. Matrices. Process the addition and multiplication of a pair of M by N matrices.
 

 1#!/usr/bin/env python
 2#-*- coding:utf-8 -*-
 3#$Id: p0616.py 151 2010-06-03 16:35:22Z xylz $
 4
 5'''
 6This is a 'python' study plan for xylz.
 7Copyright (C)2010 xylz (www.imxylz.info)
 8'''
 9
10def mulmatrice(a,b):
11    r = []
12    for i in range(len(a)):
13        rij = []
14        r.append(rij)
15        for j in range(len(b[0])):
16            x=0
17            for m in range(len(a[i])):
18                x += (a[i][m]*b[m][j])
19            rij.append(x)
20    return r
21                
22            
23def addmatrice(a,b):
24    for i in range(len(a)):
25        for j in range(len(a[i])):
26            a[i][j] += b[i][j]
27    return a
28
29
30if __name__ == '__main__':
31    print mulmatrice([[1,2],[3,4]], [[2,3],[4,5]]) 
32    print addmatrice([[1,2],[3,4]], [[2,3],[4,5]]) 
33
34




©2009-2014 IMXYLZ |求贤若渴
posted on 2010-06-04 17:03 imxylz 阅读(16891) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航:
 

©2009-2014 IMXYLZ