如果我有一个函数的引用,我可以检查它的代码对象f.__code__,获取签名,然后对此签名执行后续检查以查看代码是否更改.这很好.但是,如果其中一个功能的依赖项发生了变化呢?例如
def foo(a, b):
return bar(a, b)
Run Code Online (Sandbox Code Playgroud)
让我们说foo保持不变,但bar改变了.有没有办法可以foo通过foo.__code__对象检查'依赖''live' (与解析文本和使用AST)?
I encountered this problem when doing some enthusiastic programming. The problem can be expressed as follows:
For a multiset A, let P(A) denote the set of all possible permutations of A. P(A) is naturally divided into disjoint subsets that are equivalence classes, with the equivalence relation being "can be related by circular shifts." Enumerate all these equivalence classes by generating exactly one member from each of them.
例如,考虑多集{0,1,1,2}.排列"0112"和"1201"是唯一的排列,但后者可以通过对前者进行循环移位来找到,反之亦然.所需的算法不应生成两者.
当然,蛮力方法是可能的:只需生成排列 - 无论循环重复 - 使用任何多重排列算法,并丢弃与先前结果相比较的重复.然而,这在实践中往往效率低下.如果不是零记账,所需算法应该要求最少.
深刻理解对此问题的任何见解.
我试图围绕PEP3118的numpy实现.缓冲区访问究竟是如何在numpy中工作的.
>>> p = numpy.getbuffer(numpy.arange(10))
>>> p
<read-write buffer for 0x1003e5b10, size -1, offset 0 at 0x1016ab4b0>
>>> numpy.frombuffer(p)
array([ 0.00000000e+000, 4.94065646e-324, 9.88131292e-324,
1.48219694e-323, 1.97626258e-323, 2.47032823e-323,
2.96439388e-323, 3.45845952e-323, 3.95252517e-323,
4.44659081e-323])
Run Code Online (Sandbox Code Playgroud)
所以我得到了意想不到的回报.我希望看到一个包含0-9的10个元素的数组.我可以进入数组并进行读/写.
>>> j = numpy.frombuffer(p)
>>> j
array([ 0.00000000e+000, 4.94065646e-324, 9.88131292e-324,
1.48219694e-323, 1.97626258e-323, 2.47032823e-323,
2.96439388e-323, 3.45845952e-323, 3.95252517e-323,
4.44659081e-323])
>>> j += 1
>>> j
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Run Code Online (Sandbox Code Playgroud)
所以看起来缓冲区正在初始化为全零,然后我可以写入.我期望的功能是能够使用getbuffer将数组(使用arange或asarray)直接构建到缓冲区.这不可能吗?
我添加了三个正态分布以获得如下所示的新分布,如何在 python 中根据此分布进行采样?
import matplotlib.pyplot as plt
import scipy.stats as ss
import numpy as np
x = np.linspace(0, 10, 1000)
y1 = [ss.norm.pdf(v, loc=5, scale=1) for v in x]
y2 = [ss.norm.pdf(v, loc=1, scale=1.3) for v in x]
y3 = [ss.norm.pdf(v, loc=9, scale=1.3) for v in x]
y = np.sum([y1, y2, y3], axis=0)/3
plt.plot(x, y, '-')
plt.xlabel('$x$')
plt.ylabel('$P(x)$')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,有没有更好的方法来绘制这样的概率分布?
我正在添加单元测试和一种“传统”Python 包。一些模块包含嵌入在 docstrings 中的自己的 doctests。我的目标是运行这些文档测试和新的专用单元测试。
下面这个Q&A(“如何让py.test运行文档测试以及正常的测试目录?”)我使用的--doctest-modules选项pytest。当从源存储库运行时,pytest确实从src目录下的 Python 模块中发现了嵌入的 doctests 。
但是,我的目标是测试源发行版是否完全构建和安装,然后针对已安装的包测试所有内容。为此,我正在使用toxwhich 自动构建sdist(源代码分发)tarball 的过程,将其安装在虚拟环境中,并针对已安装的版本运行测试。为了确保它是已安装的版本,而不是源存储库中由测试导入的版本,我遵循本文中的建议,存储库现在如下所示:
repo/
src/
my_package/
__init__.py
module_a.py
module_b.py
...
tests/
test_this.py
test_that.py
requirements.txt
setup.py
tox.ini
Run Code Online (Sandbox Code Playgroud)
(下面的测试脚本tests将包导入为 in import my_package,它会命中已安装的版本,因为存储库布局确保src/my_package目录不在模块搜索路径中。)
在tox配置文件中,相关部分看起来像
[tox]
envlist = py27,py36,coverage-report
[testenv]
deps =
-rrequirements.txt
commands =
coverage run -p -m pytest --
[pytest]
addopts = --doctest-modules
Run Code Online (Sandbox Code Playgroud)
到目前为止,测试运行良好,并且 doctests …
示例代码:
import numpy as np
a = np.zeros((5,5))
a[[0,1]] = 1 #(list of indices)
print('results with list based indexing\n', a)
a = np.zeros((5,5))
a[(0,1)] = 1 #(tuple of indices)
print('results with tuple based indexing\n',a)
Run Code Online (Sandbox Code Playgroud)
结果:
results with list based indexing
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
results with tuple based indexing
[[ 0. 1. 0. 0. …Run Code Online (Sandbox Code Playgroud) 因此,正如标题所示,我正在尝试确定并复制大目录中的最新文件。我发现的大多数解决方案要么首先列出目录,要么使用glob.glob, 然后使用max(file, key=os.path.getmtime)来确定最新的文件。
我的问题是我试图搜索的目录有超过 10,000 个文件,列出所有这些文件需要很长时间。
有没有办法可以“取消”列表,可以这么说,一旦我确定了第一个(最近的)文件是什么?或者我不知道的另一种方法?
我当然知道它用于输出带参数的指针.
我读过迈克尔霍华德和大卫勒布朗的书" 编写安全代码".
书中的一个程序演示了堆栈溢出是如何工作的 strcpy()
注意printf()没有参数.
#include <stdio.h>
#include <string.h>
void foo(const char* input)
{
char buf[10];
//What? No extra arguments supplied to printf?
//It's a cheap trick to view the stack 8-)
//We'll see this trick again when we look at format strings.
printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n");
//Pass the user input straight to secure code public enemy #1.
strcpy(buf, input);
printf("%s\n", buf);
printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}
void bar(void)
{
printf("Augh! I've been hacked!\n"); …Run Code Online (Sandbox Code Playgroud) 为什么这个用于计算两个向量的内积的代码产生双重释放或损坏错误,当编译时:
ejspeiro@Eduardo-Alienware-14:~/Dropbox/HPC-Practices$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
Run Code Online (Sandbox Code Playgroud)
代码来自此参考.
// Computation of the inner product of vectors aa and bb.
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t nn = 100000000;
size_t total_mem_array = nn*sizeof(double);
double *aa;
double *bb;
double ss = 0.0;
aa = (double *) malloc(total_mem_array);
bb = (double *) malloc(total_mem_array);
int ii = 0;
for (ii = 0; ii < nn; ++ii) {
aa[ii] = 1.0;
bb[ii] = 1.0;
}
double sum1 = 0.0;
double …Run Code Online (Sandbox Code Playgroud) 我正在开展一个学校项目,要求我对单精度浮点数做一些数学计算.我以为我会在numpy中使用float32格式,因为python实际上是我所知道的唯一通用语言.IMO这个数字格式应该能够处理数字1.0000001,但它一直将我的答案截断为1.0.我能得到的最接近的是1.00001.任何人都可以对此有所了解吗?我是这个浮点格式和Python的新手.
import numpy as np
keyInput=np.float32(input("Enter a number and i'll float 32 it: "))
print(keyInput)
print(np.float32(keyInput))
print("This is of type: ",type(keyInput))
input('Press ENTER to exit')
Run Code Online (Sandbox Code Playgroud) 嗨,我是Python的新手,我编写了一个简单的程序来查找给定数字的平方根.
n = int(input("ENTER YOUR NUMBER: "))
g = n/2
t = 0.0001
def findRoot(x):
if ((x * x > n - t) and (x * x <= n + t)):
return x
else:
x = (x + n / x) / 2
findRoot(x)
r = findRoot(g)
print("ROOT OF {} IS {}".format(n, r))
Run Code Online (Sandbox Code Playgroud)
t 是最大错误.
我知道使用while循环很容易,但我无法弄清楚这段代码有什么问题.我调试了代码,在返回值x(第7行)后,第10行再次运行,产生"无"值.
控制台输出为任何n,n > 0(除了4)是ROOT OF (Given Number) IS None
知道如何纠正代码吗?
在我的python中,我正在编写一个需要的函数**kwargs.我遇到的问题是我经常None作为关键字值传递,这感觉就像糟糕的风格.例如:
def foo(**kwargs):
if 'bar' in kwargs:
return kwargs['bar']
def baz(x=None):
print(foo(bar=x))
Run Code Online (Sandbox Code Playgroud)
这里的问题是,如果x是None,那么我希望它只是不打印.kwargs如果关键字参数为None,如何将其添加到关键字参数中?
python ×8
python-3.x ×4
numpy ×3
c ×2
algorithm ×1
arrays ×1
buffer ×1
doctest ×1
double-free ×1
indexing ×1
montecarlo ×1
multiset ×1
necklaces ×1
permutation ×1
plot ×1
printf ×1
pytest ×1
random ×1
recursion ×1
reflection ×1
testing ×1
tox ×1