Last active
May 3, 2017 10:36
-
-
Save kvbik/451a1eb7db509b252b4545ee4252752d to your computer and use it in GitHub Desktop.
min() a max() tatuv ukol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WeNeedArgumentsException(Exception): | |
pass | |
def min(*args, key=lambda x: x): | |
sequence = args | |
if len(args) == 1: | |
sequence = args[0] | |
if len(sequence) == 0: | |
raise WeNeedArgumentsException('we need arguments') | |
minimum = sequence[0] | |
for item in sequence[1:]: | |
if key(item) < key(minimum): | |
minimum = item | |
return minimum | |
# max() is just an oposit of min() | |
def max(*args, key=lambda x: x): | |
return min(*args, key=lambda x: -key(x)) | |
# test cases from https://py.checkio.org/mission/min-max/ | |
assert max(3, 2) == 3 | |
assert min(3, 2) == 2 | |
assert max([1, 2, 0, 3, 4]) == 4 | |
assert min("hello") == "e" | |
assert max(2.2, 5.6, 5.9, key=int) == 5.6 | |
assert min([[1,2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0] | |
# checking some more constraints | |
try: | |
min() | |
assert False | |
except WeNeedArgumentsException: | |
assert True | |
try: | |
min(1) | |
assert False | |
except TypeError: | |
assert True | |
assert min([1]) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment