Code Snippet

270 阅读2分钟

记录各种语言下的遇到的code snippets以及算法模板。按语言和框架等分类。

Python

计算两向量夹角

import numpy as np
def angle(vec1, vec2):
   eps = 1e-6  # 消除除零和溢出问题
   unit_vector_1 = vec1 / (np.linalg.norm(vec1) + eps)
   unit_vector_2 = vec2 / (np.linalg.norm(vec2) + eps)
   dot_product = np.dot(unit_vector_1, unit_vector_2)
   if 1.0 < dot_product < 1.0 + eps:
       dot_product = 1.0
   elif -1.0 - eps < dot_product < -1.0:
       dot_product = -1.0
   angle = np.arccos(dot_product)
   return angle

参考的基础上添加eps来解决除零和溢出问题,经项目测试可以达到目的。

python string swap 元素

如果直接s[i], s[j] = s[j], s[i]会报错'str' object does not support item assignment,因为python里str是不可变对象。可以这么写:

def swap(s, i, j):
    s = list(s)  # listify str
    s[i], s[j] = s[j], s[i]
    return ''.join(s)

四舍五入问题

Python 自带的round()'{:.2f}.format(num)',其实不是我们所说的四舍五入,stackoverflowsegmentfault 因为官方doc:

values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice.

举个栗子,round(123.45, 1),首先,10 to the power minus ndigits 是指 pow(10, -1)multiple of 是指 0.1, 0.2, ..., 0.9 这些。所以123.45123.4123.5同样近,使用最后一条规则 rounding is done toward the even choice,故结果是123.4

但这和我们常说的四舍五入是有所不同的,如果想要四舍五入,可以这么写。

from decimal import Decimal, ROUND_HALF_UP
# ROUND_HALF_UP 舍入到最接近的数,同样接近则舍入到零的反方向。
print(Decimal(123.45).quantize(Decimal('.1'),rounding=ROUND_HALF_UP))

其他 flag 见docdecimal.

call a script from another script

也就是在另一个python脚本去批次运行另一个脚本的方法。假设被运行的脚本实现了argparse

import subprocess
x = subprocess.Popen(['python', 'scripts/inference.py',
        '--cfg', 'to/cfg/path', '--input', 'to/input/file name'])
# 如果比如使用到了GPU,最好加上下面这句话
x.wait()

这个方法的好处是,python脚本写着顺手,而且对于传入的参数不需要像shell中需要用引号包起来.