piyush singh piyush singh - 2 months ago 5
Python Question

How to optimize sorting program in Python?

I need to write a program that takes a list of strings containing integers and words and returns a sorted version of the list. The output should maintain the positions of strings and numbers as they appeared in the original string.

data=raw_input("Enter data").split(" ")
alpha=[]
num=[]
for item in data:
if item.isalpha():
alpha.append(item)
else:
num.append(item)
alpha.sort()
num.sort()

i=0
j=0
result=""
for item in data :
if item.isalpha():
result +=alpha[i]+" "
i +=1
else:
result +=num[j]+" "
j +=1

print result


Above code is working fine for me, but I want to use minimum memory. How can I reduce the above code and get the correct result with a single list and least iteration?

input


car truck 8 4 bus 6 1


output


bus car 1 4 truck 6 8

Answer

I reduced code to a single list.

 def inplace_sort(input_string):

 int_index, output_string, input_string_list = 0,"",[]

      for item in input_string.split(' '):
   if item.isdigit():
    input_string_list.append(int(item))
   else:
    input_string_list.append(item)

    input_string_list = sorted(input_string_list)

 for alpha_index, value in enumerate(input_string_list):
   if isinstance(value, str):
    break

 for item in input_string.split():
   if item.isdigit():
    output_string += str(input_string_list[int_index]) + " "
    int_index += 1
else:
    output_string += input_string_list[alpha_index] + " "
    alpha_index += 1

  return "\nOutput:\n"+output_string

     if __name__ == "__main__":
     output_string = inplace_sort(raw_input("\nInput:\n"))
      print output_string
Comments