patternpythonMinor
Review implementation for Partial Ordering of Vectors
Viewed 0 times
vectorsorderingforpartialimplementationreview
Problem
Partial ordering may be useful in some scientific contexts. This is quick prototype in Python, which I believe works correctly.
Do you notice any flaws? Can you provide a counter-example of wrong results? Additional test cases will be also rewarded with +1.
Edit: redefining the
Proved to be working with the same unit test.
Same result, but using short-circuit logic and avoiding to scan both lists:
As suggested in comment, equivalent version, more natural:
Do you notice any flaws? Can you provide a counter-example of wrong results? Additional test cases will be also rewarded with +1.
#!/usr/bin/env python3
import unittest as ut
def leq (L1, L2):
assert len(L1) == len(L2)
l = g = 0
for v1, v2 in zip(L1, L2):
if v1 v2:
g += 1
return l >= 0 and g == 0
class Test (ut.TestCase):
def test1 (self):
V1 = [1, 2, 3]
V2 = [1, 2, 2]
self.assertFalse(leq(V1, V2))
self.assertTrue(leq(V2, V1))
def test2 (self):
V1 = [1, 2, 3]
V2 = [2, 2, 3]
self.assertTrue(leq(V1, V2))
self.assertFalse(leq(V2, V1))
def test3 (self):
V1 = [1, 2, 3]
self.assertTrue(leq(V1, V1))
def test4 (self):
V1 = [1, 2, 3]
V2 = [3, 2, 1]
self.assertFalse(leq(V1, V2))
self.assertFalse(leq(V2, V1))Edit: redefining the
leq function (thanks to Cary for the comment)leq = lambda L1, L2: sum(v1 > v2 for v1, v2 in zip(L1, L2)) == 0Proved to be working with the same unit test.
Same result, but using short-circuit logic and avoiding to scan both lists:
leq = lambda L1, L2: not any (v1 > v2 for v1, v2 in zip(L1, L2))As suggested in comment, equivalent version, more natural:
leq = lambda L1, L2: all(v1 > v2 for v1, v2 in zip(L1, L2))Solution
Not much to say about it, good job!
(And +1 to the comments who should become an answer.)
- Documentation: explain the mathematical explanation of your partial ordering unless it's really that obvious for your intended readers
- Names:
- In Python, names starting with uppercase letters are for class names: of course you're free to use your own convention, but this one makes it easy to share code between Python developers
- Explicit is better than implicit:
lessis better thanlwhich could also mean left or leave or whatever.
- Style: In Python (see PEP8), we usually don't but spaces before function definitions.
- Test cases: always add a test case for degenerate cases, eg. the empty list and lists of different lengths: those are the ones which usually fail.
(And +1 to the comments who should become an answer.)
Context
StackExchange Code Review Q#41433, answer score: 3
Revisions (0)
No revisions yet.