Alexis
Alexis

Reputation: 95

How to permute the numbers correctly?

My data set is a text file of 8 numbers each under this format:

   76768,766846646,979,3290,5244,69797,8080,3414
   7643,73467346,826382,827382,3,826,864,686

There is 2 special things about these numbers:

  1. Each line has exactly 8 numbers seperated by a comma
  2. They are all positive values.

The way i should see my data is as x and y

so taking the first line as example x can be seen as 76768,979,5244,8080 and y as 766846646,3290,69797,3414

What i have to do is add the highest term of x near the highest term of y and the smallest term of x near the smallest term of y so the value i should get for the first line is 76768,766846646,979,3290

the code:

from functools import reduce

text = "76768,766846646,979,3290,5244,69797,8080,3414"  # input text
s = text.split(",")  # make it into a list of strings

from operator import add
output = list(
    reduce(
        add,
        zip(
            sorted(s[::2], reverse=True)[::(len(s)//2)-1],
            sorted(s[1::2], reverse=True)[::(len(s)//2)-1]
        )
    )
)
print (output)

the output i'm getting is however ['979', '766846646', '5244', '3290'] but i'm getting correct values occasionally with other example and not able to understand where the issue is or fix it.

Upvotes: 0

Views: 32

Answers (1)

trincot
trincot

Reputation: 350290

You are sorting strings (alphabetically), while you really need to sort the values as numbers. Start with this:

s = [int(i) for i in text.split(",")]  # make it into a list of numbers

Now the output for the example will be:

[76768, 766846646, 979, 3290]

Upvotes: 2

Related Questions