是否有更有效/更优雅的方式来编写函数' equal'?
def equal(v,u):
if not v.D==u.D:
return False
if v.f=={} or u.f=={}:
if not sum(v.f.values())==sum(u.f.values()):
return False
else:
return True
if not v.f.keys()==u.f.keys():
if not sum(v.f.values())+sum(u.f.values())==0:
return False
if not sum(v.f.values())==sum(u.f.values()):
return False
if not v.D==u.D:
return False
return True
这是预期的输出:
>>> Vec({'a', 'b', 'c'}, {'a':0}) == Vec({'a', 'b', 'c'}, {'b':0})
True
>>> Vec({'a', 'b', 'c'}, {'a': 0}) == Vec({'a', 'b', 'c'}, {})
True
>>> Vec({'a', 'b', 'c'}, {}) == Vec({'a', 'b', 'c'}, {'a': 0})
True
请确保equal(u, v)
检查来自u.f
和v.f
的所有密钥的均等性,即使u.f
中v.f
中的某些密钥不存在(或>>> Vec({'x','y','z'},{'y':1,'x':2}) == Vec({'x','y','z'},{'y':1,'z':0})
False
>>> Vec({'a','b','c'}, {'a':0,'c':1}) == Vec({'a','b','c'}, {'a':0,'c':1,'b':4})
False
>>> Vec({'a','b','c'}, {'a':0,'c':1,'b':4}) == Vec({'a','b','c'}, {'a':0,'c':1})
False
# The keys matter:
>>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'b':1})
False
# The values matter:
>>> Vec({'a','b'},{'a':1}) == Vec({'a','b'},{'a':2})
False
"""
亦然)
Vec
以下是class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
self.D = labels
self.f = function
类:
INSERT INTO table2
(Name, Company, ProductName, Status, cron_modified_date, count)
SELECT Name, Company, ProductName, Status, created_date, 1
FROM table1
ON DUPLICATE KEY UPDATE
count = count + 1
cron_modified_date = created_date;
答案 0 :(得分:0)
您似乎想要做的是,如果属性D
相等且f
相等,排除值为0
的条目,则将向量定义为相等。这就是你如何做到的。
def equal(v, u):
# We will remove the entries with value zero for comparison
non_zero_v_f = {key: val for key, val in v.f.items() if val != 0}
non_zero_u_f = {key: val for key, val in u.f.items() if val != 0}
return v.D == u.D and non_zero_v_f == non_zero_u_f
此外,您可以将其设为特殊的类方法,以便==
实际上将其用于相等。
class Vec:
def __init__(self, labels, function):
self.D = labels
self.f = function
def __eq__(v, u):
non_zero_v_f = {key: val for key, val in v.f.items() if val != 0}
non_zero_u_f = {key: val for key, val in u.f.items() if val != 0}
return v.D == u.D and non_zero_v_f == non_zero_u_f