我试图了解引擎盖下的python哈希函数.我创建了一个自定义类,其中所有实例都返回相同的哈希值.
class C(object):
def __hash__(self):
return 42
Run Code Online (Sandbox Code Playgroud)
我只是假设上面的类中只有一个实例可以随时出现在一个集合中,但实际上一个集合可以有多个具有相同散列的元素.
c, d = C(), C()
x = {c: 'c', d: 'd'}
print x
# {<__main__.C object at 0x83e98cc>:'c', <__main__.C object at 0x83e98ec>:'d'}
# note that the dict has 2 elements
Run Code Online (Sandbox Code Playgroud)
我进行了一些实验,发现如果我重写__eq__方法使得类的所有实例比较相等,那么该集只允许一个实例.
class D(C):
def __eq__(self, other):
return hash(self) == hash(other)
p, q = D(), D()
y = {p:'p', q:'q'}
print y
# {<__main__.D object at 0x8817acc>]: 'q'}
# note that the dict has only 1 element
Run Code Online (Sandbox Code Playgroud)
所以我很想知道dict有多个具有相同哈希的元素.谢谢!
注意:编辑问题以给出dict(而不是set)的例子,因为答案中的所有讨论都是关于dicts的.但这同样适用于集合; 集合也可以有多个具有相同散列值的元素.
我正在优化一些Python代码,并尝试了以下实验:
import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
Run Code Online (Sandbox Code Playgroud)
第二个循环可靠地更快,从晶须到10%,取决于我运行它的系统.我已经尝试改变循环的顺序,执行次数等,它似乎仍然有效.
陌生人,
for i in range(10000000, 0, -1):
Run Code Online (Sandbox Code Playgroud)
(即向后运行循环)比快
for i in range(10000000):
Run Code Online (Sandbox Code Playgroud)
即使循环内容相同.
是什么给了,这里有更一般的编程课程?
考虑以下功能:
def fact1(n):
if n < 2:
return 1
else:
return n * fact1(n-1)
def fact2(n):
if n < 2:
return 1
return n * fact2(n-1)
Run Code Online (Sandbox Code Playgroud)
它们应该是等价的.但是有一个性能差异:
>>> T(lambda : fact1(1)).repeat(number=10000000)
[2.5754408836364746, 2.5710129737854004, 2.5678811073303223]
>>> T(lambda : fact2(1)).repeat(number=10000000)
[2.8432059288024902, 2.834425926208496, 2.8364310264587402]
Run Code Online (Sandbox Code Playgroud)
没有的版本else慢了10%.这非常重要.为什么?
在Python中,我经常以类似于此的方式重用变量:
files = files[:batch_size]
Run Code Online (Sandbox Code Playgroud)
我喜欢这种技术,因为它可以帮助我减少需要跟踪的变量数量.
没有任何问题,但我想知道我是否缺少潜在的缺点,例如性能等.
[编辑]更改return 0为return。Beaa Python n00b的副作用。:)
我正在定义一个函数,正在执行约20行处理。在处理之前,我需要检查是否满足特定条件。如果是这样,那么我应该绕过所有处理。我已经用这种方式定义了函数。
def test_funciton(self,inputs):
if inputs == 0:
<Display Message box>
return
<20 line logic here>
Run Code Online (Sandbox Code Playgroud)
请注意,20行逻辑不返回任何值,并且我不使用第一个“ if”中返回的0。
我想知道这是否比使用以下类型的代码更好(就性能,可读性或任何其他方面而言),因为上述方法对我来说很好,因为它减少了一个缩进:
def test_function(self,inputs):
if inputs == 0:
<Display Message box>
else:
<20 line logic here>
Run Code Online (Sandbox Code Playgroud) python ×5
performance ×2
addition ×1
dictionary ×1
equality ×1
hash ×1
recursion ×1
set ×1
subtraction ×1