Home > OS >  Reverse List without using extra space/list/array in memory in Python
Reverse List without using extra space/list/array in memory in Python

Time:10-15

Here is the list I have:

l = ['m','o','b','i','l','e', ' ','a','l','i',' ']

The output I need:

out = ['e','l','i','b','o','m', ' ','i','l','a',' ']

So, far I have come up with this solution

start = 0
end = len(lst)-1
for i in range(start,end 1):
    if lst[i]==" ":
        break    
    temp = lst[i] # first
    lst[i] = lst[end]
    lst[end] = temp
       
    start  =1
    end -=1

What I am doing is that I am only replacing the first values till the '' with the last element. But with I will have to create another for loop for the remaining values. Can anyone suggest a better solution?

Storing values in a Separate array is not allowed only you can replace it within this array but temp variables are allowed

CodePudding user response:

I have another answer that may work for you, and it doesn't use any map or list magic, and doesn't create any extra lists. All it does is move values around within the starting list.

l = ['m','o','b','i','l','e', ' ','a','l','i',' ']
start = 0

for a in range(len(l)):
    if l[a] == ' ':
        start = a   1
        
    if a > start:
        for b in range(a, start, -1):
            if b > 0:
                temp = l[b]
                l[b] = l[b - 1]
                l[b - 1] = temp
                
print(l)

This answer is slightly more complicated than my other answer. Basically what happens is it moves through the array, moving the last element to the front. For example, the first iteration will start with ['m'], and do nothing. The second will start with ['m', 'o'], and move the 'o' to the front, so it will end with ['o', 'm]. The third iteration will start with ['o', 'm', 'b'], and move the 'b' to the front, ending with ['b', 'o', 'm']. And every time it see's a space, it will reset the "front," so it flips words but not the entire array.

CodePudding user response:

Here is my solution. It is easier to read and understand.

l = ['m','o','b','i','l','e', ' ','a','l','i',' ']

first = 0
end = len(l)-1
mid = 0

for i in range(len(l)):
    if l[i]==" ":
        mid = i
        break
def Rev(l, start, end):
    while start<end:
        l[start],l[end] = l[end], l[start]
        start  =1
        end -=1

Rev(l, first, mid-1)
Rev(l, mid, end)
print(l)

CodePudding user response:

You can do it a pretty simple way using array magic, without any imported functions.

l = ['m','o','b','i','l','e', ' ','a','l','i',' ']
        
wordsList = "".join(l).split(" ")
reversedWordsList = [e[::-1] for e in wordsList]
outputArray = list(" ".join(reversedWordsList))

print(outputArray)

This joins the array into a string, and splits it on space to create an array with each of the words. Then it manually reverses each word, then rejoins the words into a string, and splits the string into an array of characters.

  • Related