廖雪峰——作业

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 20:02   11   0

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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP