廖雪峰——作业

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:00
UTC+08:00
2017-11-16 14:37:57
>>> now.timestamp()
1510814277.240873
>>> assert t3 == 1510814277.240873, t3
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert t3 == 1510814277.240873, t3
AssertionError: 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 s
	elif 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))/10
	num = num1+num2
	return 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)
>>> p
3.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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值