PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# The post this answers is here:
# https://www.sololearn.com/Discuss/2240507/how-do-i-jump-or-to-shuffle-the-next-value-in-a-list
def f(a, b):
assert len(a) == len(b) # some error catching, because the two lists are expected to have the same lenght
i = 0
while i < len(a): # iterate through the lists:
if a[i] <= b[i]:
# We will search for the lowest number that is greater than b[i]:
j = i + 1
# The order of the 2 following conditions is important: if we swap it, it would cause an IndexError, because if j = len(b), a[j] would not exist.
# But Python has got a features, that makes it behaving so that when it has a false expression, followed by a "and",
# it will know that the bigger evaluation will be false anyway. So it does not calculate a[j] <= b[i], so it will not cause any exception.
while j < len(b) and a[j] <= b[i]:
j += 1
# Now, we need to know which of the two above conditions made the loop stop.
# If it is the second (" j < len(b) "), it means that there is no number in the list greater than b[i], so we can do nothing.
# But if it is the first condition (" a[j] <= b[i] ") that made the loop stop, there is such a number.
if j < len(b):
# Then we would need to swap it with a[i]:
a[i], a[j] = a[j], a[i]
# And now, we must increment i, because we have nothing else to do with the old a[i].
i = i + 1
a = [1, 2, 3, 3, 5, 5, 6, 6, 7, 9]
b = [0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
f(a, b)
print(a)
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run