A list of ints is entered into the program 1 at a time, for example:
[1, 3, 1, 4, 4, 3, 1]
Task:
Print a list that contains exactly the same numbers as the given list,
but rearranged so that every 3 is immediately followed by a 4. The 3's must not move index places, but every other number may move.
The output of the example should read:
[1, 3, 4, 1, 1, 3, 4]
My code so far is only able to complete the rules 1 and 2. How could my code be modified to cater to this?
newList=[]
n=0
numCount= int(input())
while True:
try:
n = int(input())
except:
break
if len(newList) !=(numCount):
if n == 3:
newList.append(3)
newList.append(4)
else:
newList.append(n)
print(newList)
I suggest you to first get all the indexes of 3 and 4 in the input list, then swap each element following a 3 with a 4. It gives the following code, which is quite short and easily readable:
a = [1, 3, 1, 4, 4, 3, 1]
# Get the indexes of 3 and 4 in the list
indexesOf3 = [i for i,elem in enumerate(a) if elem == 3]
indexesOf4 = [i for i,elem in enumerate(a) if elem == 4]
# Swap each element following a 3 with a 4
for i3,i4 in zip(indexesOf3,indexesOf4):
a[i3+1], a[i4] = a[i4], a[i3+1]
print(a)
# [1, 3, 4, 1, 1, 3, 4]
Note: this code example modifies the input list, but obviously it can be easily updated into a function returning a new list and keeping the input list as it is.