Python 面试题求解

魔神翼 发布于 2014/07/27 18:03
阅读 628
收藏 3
完成下面的类C,使得所有断言都正确。 

class C(object):         
    def __init__(self, a, b):                 
        self.a = a                 
        self.b = b 未完成... 

a = C(1, 'a') 
b = C(1, 'a') 
c = C(1, 'b')

l = [a, b, c] 

r = {} 

for i in l:         
    if i not in r:                 
        r[i] = 1         
    else:                 
        r[i] += 1 

assert r[a] == 2 
assert r[b] == 2 
assert r[c] == 1



加载中
1
魔神翼
魔神翼

我想出来了,和Java一样,重载了hash函数,还要重载equals函数

class C(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        
    def __hash__(self):
        return self.b.__hash__()

    def __eq__(self, other):
      return self.b == other.b



svice
svice
赞 !
0
Xsank
Xsank
题目的意思应该就是让a和b的hashcode相等,楼上正解
0
不必在乎朕是谁
不必在乎朕是谁

我来娱乐一下:

class C(object):         
    def __init__(self, a, b):                 
        self.a = a              
        self.b = b
 
a = C(1, 'a') 
b = C(1, 'a') 
c = C(1, 'b')
 
l = [a, b, c] 
 
r = {a: 1, b: 1} 
 
for i in l:         
    if i not in r:                 
        r[i] = 1        
    else:                 
        r[i] += 1
 
assert r[a] == 2
assert r[b] == 2
assert r[c] == 1



返回顶部
顶部