我正在查看sorted_containers的来源,并惊讶地看到这一行:
self._load, self._twice, self._half = load, load * 2, load >> 1
Run Code Online (Sandbox Code Playgroud)
这load
是一个整数.为什么在一个地方使用位移,在另一个地方使用乘法?似乎合理的是,位移可能比积分除以2更快,但为什么不用乘法替换乘法呢?我对以下案例进行了基准测试:
并发现#3始终比其他替代品更快:
# self._load, self._twice, self._half = load, load * 2, load >> 1
import random
import timeit
import pandas as pd
x = random.randint(10 ** 3, 10 ** 6)
def test_naive():
a, b, c = x, 2 * x, x // 2
def test_shift():
a, b, c = x, x << 1, x >> 1
def test_mixed(): …
Run Code Online (Sandbox Code Playgroud) 我使用 Python/Numpy 中的函数来解决组合博弈论中的问题。
\nimport numpy as np\nfrom time import time\n\ndef problem(c):\n start = time()\n N = np.array([0, 0])\n U = np.arange(c)\n \n for _ in U:\n bits = np.bitwise_xor(N[:-1], N[-2::-1])\n N = np.append(N, np.setdiff1d(U, bits).min())\n\n return len(*np.where(N==0)), time()-start \n\nproblem(10000)\n
Run Code Online (Sandbox Code Playgroud)\n然后我用 Julia 编写它,因为我认为由于 Julia 使用即时编译,它会更快。
\nfunction problem(c)\n N = [0]\n U = Vector(0:c)\n \n for _ in U\n elems = N[1:length(N)-1]\n bits = elems .\xe2\x8a\xbb reverse(elems)\n push!(N, minimum(setdiff(U, bits))) \n end\n \n return sum(N .== 0)\nend\n\n@time problem(10000)\n …
Run Code Online (Sandbox Code Playgroud) 在我的电脑上,我可以检查一下
(0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3)
Run Code Online (Sandbox Code Playgroud)
评估为False
。
更一般而言,我可以使用以下模拟估算公式在统一且独立地选择时(a + b) + c == a + (b + c)
大致失败17%
的时间:a,b,c
[0,1]
import numpy as np
import numexpr
np.random.seed(0)
formula = '(a + b) + c == a + (b + c)'
def failure_expectation(formula=formula, N=10**6):
a, b, c = np.random.rand(3, N)
return 1.0 - numexpr.evaluate(formula).mean()
# e.g. 0.171744
Run Code Online (Sandbox Code Playgroud)
我想知道是否有可能手动得出这种概率,例如使用浮点标准中的定义以及对均匀分布的一些假设。
给定以下答案,我认为至少到现在为止,原始问题的以下部分是遥不可及的。
有没有一种工具可以在不运行模拟的情况下计算给定公式的失效概率。
可以假定公式很简单,例如,使用括号,加法,减法以及可能的乘除运算。
(以下内容可能是numpy
随机数生成的产物,但似乎仍然很有趣。)
奖励问题基于NPE的观察。我们可以使用以下代码为一系列范围内的均匀分布生成故障概率[[-n,n] for n in …
我正在尝试生成具有给定数量节点的所有有向图,直至图同构,以便我可以将它们输入到另一个 Python 程序中。这是一个使用 NetworkX 的简单参考实现,我想加快速度:
from itertools import combinations, product
import networkx as nx
def generate_digraphs(n):
graphs_so_far = list()
nodes = list(range(n))
possible_edges = [(i, j) for i, j in product(nodes, nodes) if i != j]
for edge_mask in product([True, False], repeat=len(possible_edges)):
edges = [edge for include, edge in zip(edge_mask, possible_edges) if include]
g = nx.DiGraph()
g.add_nodes_from(nodes)
g.add_edges_from(edges)
if not any(nx.is_isomorphic(g_before, g) for g_before in graphs_so_far):
graphs_so_far.append(g)
return graphs_so_far
assert len(generate_digraphs(1)) == 1
assert len(generate_digraphs(2)) == 3
assert …
Run Code Online (Sandbox Code Playgroud) 我想将“黑匣子”Python 函数f
应用于大数组arr
。额外的假设是:
f
是“纯的”,例如是确定性的,没有副作用。arr
具有少量唯一元素。我可以使用一个装饰器来实现这一点,该装饰器f
为每个唯一元素计算arr
如下:
import numpy as np
from time import sleep
from functools import wraps
N = 1000
np.random.seed(0)
arr = np.random.randint(0, 10, size=(N, 2))
def vectorize_pure(f):
@wraps(f)
def f_vec(arr):
uniques, ix = np.unique(arr, return_inverse=True)
f_range = np.array([f(x) for x in uniques])
return f_range[ix].reshape(arr.shape)
return f_vec
@np.vectorize
def usual_vectorize(x):
sleep(0.001)
return x
@vectorize_pure
def pure_vectorize(x):
sleep(0.001)
return x
# In [47]: %timeit usual_vectorize(arr)
# 1.33 s …
Run Code Online (Sandbox Code Playgroud) 在Haskell中,我可以通过调用以获得无限的顺序函数应用程序列表:
iterate :: (A -> A) -> A -> [A]
Run Code Online (Sandbox Code Playgroud)
假设我有scala f(x: A): A
.是否有一个函数会产生顺序函数应用程序流?喜欢iter(f: A => A, x: A): Stream[A]
?
我在Scala中编写了一个项目Euler问题#59的解决方案,我不明白为什么在Vector和List之间切换会增加我认为的内存泄漏.
这是一个使用向量的工作强力解决方案.
val code = scala.io.Source.fromFile("e59.txt").getLines()
.flatMap(l => l.split(',')).map(_.toInt).toVector
val commonWords = scala.io.Source.fromFile("common_words.txt").getLines().toVector
def decode(k: Int)(code: Vector[Int])(pswd: Vector[Int]): Vector[Int] = {
code.grouped(k).flatMap(cs => cs.toVector.zip(pswd).map(t => t._1 ^ t._2)).toVector
}
def scoreText(text: Vector[Int]): Int = {
if (text.contains((c: Int) => (c < 0 || c > 128))) -1
else {
val words = text.map(_.toChar).mkString.toLowerCase.split(' ')
words.length - words.diff(commonWords).length
}
}
lazy val psswds = for {
a <- (97 to 122);
b <- (97 to 122);
c <- (97 to 122) …
Run Code Online (Sandbox Code Playgroud) 我对枚举的定义如下。我想将枚举的每个实例映射到相应的符号中。我可以通过手动构造一个数组symbols
并为其建立索引来做到这一点。有没有一种方法可以在不手动指定符号数组的情况下完成此任务?
@enum MyEnum A=1 B=2 C=3
symbols = [:A, :B, :C]
function enumToSymbol(x::MyEnum) :: Symbol
return symbols[Int(x)]
end
@assert enumToSymbol(A) == :A
Run Code Online (Sandbox Code Playgroud) 说我有2个numpy数组
a = [0, 2, 4, 6]
Run Code Online (Sandbox Code Playgroud)
和
b = [0.03, 0.78, 0.25, 0.47, 0.98, 0.58, 0.63]
Run Code Online (Sandbox Code Playgroud)
我想返回一个第3个数组,它检查数组a的索引在b中的位置,并返回b中的索引值,如下所示:
c = [0.3, 0.25, 0.98, 0.63]
Run Code Online (Sandbox Code Playgroud)
我试过了
for i in range(len(b)):
if b[i] == a.any():
c=[I]
Run Code Online (Sandbox Code Playgroud)
但得到全0.
我试图根据每列的分位数在DataFrame中剪切异常值.让我们说吧
df = pd.DataFrame(pd.np.random.randn(10,2))
0 1
0 0.734355 0.594992
1 -0.745949 0.597601
2 0.295606 0.972196
3 0.474539 1.462364
4 0.238838 0.684790
5 -0.659094 0.451718
6 0.675360 -1.286660
7 0.713914 0.135179
8 -0.435309 -0.344975
9 1.200617 -0.392945
Run Code Online (Sandbox Code Playgroud)
我目前正在使用
df_clipped = df.apply(lambda col: col.clip(*col.quantile([0.05,0.95]).values))
0 1
0 0.734355 0.594992
1 -0.706865 0.597601
2 0.295606 0.972196
3 0.474539 1.241788
4 0.238838 0.684790
5 -0.659094 0.451718
6 0.675360 -0.884488
7 0.713914 0.135179
8 -0.435309 -0.344975
9 0.990799 -0.392945
Run Code Online (Sandbox Code Playgroud)
这有效,但我想知道是否有更优雅的熊猫/ numpy方法.
我在python中有两个列表
名称:
['Test 1', 'Test 2']
Run Code Online (Sandbox Code Playgroud)
是真的:
[False, True]
Run Code Online (Sandbox Code Playgroud)
我想将列表合并到一个列表中,结果是:
[{name: 'Test 1', isTrue: False}, {name: 'Test 2', isTrue: True}]
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
list = []
thisdict = {}
for name in names:
thisdict['name'] = name
thisdict['isTrue'] = True
list.append(thisdict)
Run Code Online (Sandbox Code Playgroud)
问题是我不知道如何获得动态布尔值或如何更有效地执行此操作.
任何帮助将不胜感激.
python ×8
numpy ×4
julia ×2
list ×2
pandas ×2
performance ×2
python-3.x ×2
scala ×2
algorithm ×1
arrays ×1
bit-shift ×1
boolean ×1
dictionary ×1
enums ×1
game-theory ×1
graph-theory ×1
haskell ×1
ieee-754 ×1
memory ×1
networkx ×1
probability ×1
symbols ×1
unique ×1
vector ×1