algorithm - Efficient way to make two pairs in python -
i make 2 pairs pairs. pair consists of 2 elements, , two-pair consists of 2 pairs. here list of constraints:
- in pair, order of elements important: (element1, element2) != (element2, element1)
- in two-pair, order of pairs not important: (pair1, pair2) == (pair2, pair1)
i wrote pseudo code satisfies above constraints follows:
class pair: def __init__(self, element1, element2): assert isinstance(element1, element) assert isinstance(element2, element) self.element1 = element1 self.element2 = element2 def __eq__(self, other): if not isinstance(other, pair): return false if self.element1 != other.element1: return false if self.element2 != other.element2: return false return true def __ne__(self, other): return not (self.__eq__(other)) def __hash__(self): return hash(self.element1) ^ hash(self.element2) def getfirst(self): return self.element1 def getsecond(self): return self.element2
class twopair: def __init__(self, pair1, pair2): assert isinstance(pair1, pair) assert isinstance(pair2, pair) self.pair1 = pair1 self.pair2 = pair2 def __eq__(self, other): if not isinstance(other, twopair): return false if self.pair1 == other.pair1 , self.pair2 == other.pair2: return true if self.pair1 == other.pair2 , self.pair2 == other.pair1: return true return false def __ne__(self, other): return not (self.__eq__(other)) def __hash__(self): return hash(self.pair1) ^ hash(self.pair2) def getfirst(self): return self.pair1 def getsecond(self): return self.pair2
def maketwopairs(allpairs): alltwopairs = set([]) pair1 in allpairs: pair2 in allpairs: if pair1 == pair2: continue twopair = twopair(pair1, pair2) if twopair in alltwopairs: continue else: alltwopairs.add(twopair) return alltwopairs
the function maketwopairs
takes long time in code. there other representation 2 pairs? or, can above code improved?
you better off sticking standard python datastructures. tuple
pair
, set
twopair
(although might write set
subclass add __hash__
method).
for example:
import operator class twopairs(set): def __hash__(self): return reduce(operator.xor, map(hash, self))
regarding fact maketwopairs
function takes long time execute, can rewrite :
def make_two_pairs(all_pairs): all_two_pairs = set() # uniqify pairs list all_pairs = list(set(all_pairs)) in range(len(all_pairs)-1): j in range(i+1, len(all_pairs)): all_two_pairs.add(twopairs(all_pairs[i], all_pairs[j])) return all_two_pairs
you produce unique twopairs
, without combinatorial explosion or overhead of testing everytime before adding new pair result set.
Comments
Post a Comment