Last active
September 12, 2019 22:14
-
-
Save AMeng/330c36fee5ddb4d6016bf14349b57978 to your computer and use it in GitHub Desktop.
Codility
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
def solution(A): | |
highest_distance = 0 | |
earliest_seen = {} | |
for index, value in enumerate(A): | |
if earliest_seen.get(value): | |
distance = index - earliest_seen[value] + 1 | |
if distance > highest_distance: | |
highest_distance = distance | |
else: | |
earliest_seen[value] = index + 1 | |
return highest_distance |
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
def solution(S): | |
max_integer = 2 ** 20 - 1 | |
is_valid_int = lambda n: 0 <= n <= max_integer | |
ERROR_CODE = -1 | |
stack = [] | |
try: | |
for token in S.split(): | |
if token == "POP": | |
stack.pop() | |
elif token == "DUP": | |
temp_token = stack.pop() | |
stack.append(temp_token) | |
stack.append(temp_token) | |
elif token == "+": | |
result = stack.pop() + stack.pop() | |
if is_valid_int(result): | |
stack.append(result) | |
else: | |
return ERROR_CODE | |
elif token == "-": | |
result = stack.pop() - stack.pop() | |
if is_valid_int(result): | |
stack.append(result) | |
else: | |
return ERROR_CODE | |
else: | |
result = int(token) | |
if is_valid_int(result): | |
stack.append(result) | |
else: | |
return ERROR_CODE | |
return stack.pop() | |
except IndexError: | |
return ERROR_CODE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment