廖雪峰——作业

来源:互联网 发布:java怎么上传图片 编辑:程序博客网 时间:2024/05/21 05:41

datetime module:

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431937554888869fb52b812243dda6103214cd61d0c2000#0

>>> def to_timestamp(dt_str, tz_str):dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')m = re.match(r'^UTC(\+|-)0?(\d+):\d+$', tz_str).groups()if m[0] == '+':tz = timezone(timedelta(hours = int(m[1])))else:tz = timezone(timedelta(hours = -int(m[1])))print(dt.replace(tzinfo = tz))print(tz)print(dt)return dt.timestamp()
>>> now = datetime.now()>>> print(now)2017-11-16 14:37:57.240873>>> t3 = to_timestamp('2017-11-16 14:37:57', 'UTC+8:00')2017-11-16 14:37:57+08:00UTC+08:002017-11-16 14:37:57>>> now.timestamp()1510814277.240873>>> assert t3 == 1510814277.240873, t3Traceback (most recent call last):  File "<pyshell#52>", line 1, in <module>    assert t3 == 1510814277.240873, t3AssertionError: 1510814277.0>>> assert t3 == 1510814277.0, t3>>> 

base64 module:

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431954588961d6b6f51000ca4279a3415ce14ed9d709000

>>> import base64>>> def safe_base64_decode(s):if (len(s) % 4) != 0:s = s + b'='*(4 - len(s) % 4)return base64.b64decode(s)>>> assert b'abcd' == safe_base64_decode(b'YWJjZA=='), safe_base64_decode('YWJjZA==')>>> assert b'abcd' == safe_base64_decode(b'YWJjZA'), safe_base64_decode('YWJjZA')>>>>>> base64.b64encode(b'abcd')b'YWJjZA=='>>> base64.b64encode(b'abcd').strip(b'=')b'YWJjZA'

切片:

def trim(s):if len(s) == 0:return selif s[0] == ' ':return trim(s[1:])elif s[-1] == ' ':return trim(s[:-1])else:return s


高级函数——map/reduce: 

#python式反转字符串 http://www.jianshu.com/p/c61279736a03

>>> def to_int(x, y):return x*10 + y>>> def to_dec(x, y):return x/10 + y>>> def char2num(s):    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]>>> def str2float(s):part1, part2 = s.split('.')part2 = part2[::-1]                          #num1 = reduce(to_int, map(char2num, part1))num2 = reduce(to_dec, map(char2num, part2))/10num = num1+num2return num>>> str2float('123.456')123.456>>> assert abs(str2float('123.456') - 123.456) < 0.00001>>> 


itertools 算圆周率:

>>> def f(num):return (-1)**((num+1)/2+1)*4/num>>> def pi(N):nums = itertools.count(1, 2)odds = itertools.takewhile(lambda num:num <= N*2-1, nums)return sum(map(f, odds))>>> p = pi(10)>>> p3.0418396189294032>>> assert 3.04 < pi(10) < 3.05>>> assert 3.13 < pi(100) < 3.14>>> assert 3.140 < pi(1000) < 3.141>>> assert 3.1414 < pi(10000) < 3.1415>>> pi(10000)3.1414926535900345



阅读全文
0 0
原创粉丝点击