'Python - Pothole Fixing machine
I recently worked on an online problem. Unfortunately, I do not remember the description precisely, but I will try my best to explain it. There are a similar versions of this task, but I haven't found answer to this particular one. Basically, there are two roads L1 and L2. The have the same length. The road can consist of a pothole ('X') and a normal concrete ('.'). Your task is to find the most optimal way to cross the road from left to right while finding the maximum number of potholes that can be fixed.
Consider the example:
L1 = '.xxx...x'
L2 = '..x.xxxx'
In this scenario the maximum number of potholes we can fix is 6. Here is my solution:
def solution(L1, L2):
count = 0
for i in range(len(L1)):
if L1[i] == 'x' and L2[i] == 'x':
count += 1
elif (L1[i] == 'x' and L2[i] == '.') or (L2[i] == 'x' and L1[i] == '.'):
count += 1
else:
pass
return count
It works in some cases, but it doesn't take into account the 'special' case, where if for instance
L1[0] = 'x', L2[0] = '.' and L1[1] = '.', L2[1] = 'x'
we should only count once because we cannot go diagonally. I have tried to make a special case that would solve this but I couldn't do it. Is there an elegant solution that you can think of?
Solution 1:[1]
This is probably not the most efficient or elegant solution, but it does solve the issue that you are having.
All I did was add variable j to check the previous position whenever you encounter a position with 1 pothole and one concrete to see if the opposite is true. If it is, then it isn't then it adds 1 to count if it isn't then it moves on to next space.
I also checked the first position before the loop and started it and index 1 so the j variable wouldn't consider the -1 index as coming before the 0 position.
L1 = '.xxx...x'
L2 = '..x.xxxx'
def solution(L1, L2):
count = 0
if 'x' in [L2[0],L1[0]]:
count += 1
for i in range(1, len(L1)):
j = i - 1
if L1[i] == 'x' and L2[i] == 'x':
count += 1
elif (L1[i] == 'x' and L2[i] == '.'):
if L1[j] == '.' and L2[j] == 'x':
continue
count += 1
elif (L2[i] == 'x' and L1[i] == '.'):
if L1[j] == 'x' and L2[j] == '.':
continue
count += 1
return count
print(solution(L1, L2))
output = 6
Edit:
Here is a similar solution although much more readable in my opinion.
def solution2(L1,L2):
count = 0
if 'x' in [L2[0],L1[0]]:
count += 1
for i in range(1, len(L1)):
if 'x' not in [L1[i],L2[i]]:
continue
if all([L1[i] == 'x', L2[i] == 'x']):
count += 1
if [L1[i],L2[i]] == [L1[i-1],L2[i-1]]:
count += 1
return count
print(solution(L1,L2))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
