The Python Oracle

Order a list by all item's digits in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi

--

Chapters
00:00 Order A List By All Item'S Digits In Python
02:17 Answer 1 Score 4
02:30 Accepted Answer Score 7
03:03 Answer 3 Score 2
03:17 Answer 4 Score 4
03:24 Thank you

--

Full question
https://stackoverflow.com/questions/1079...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sorting

#avk47



ACCEPTED ANSWER

Score 7


First, make a list of integers from myCmpItem to make subtraction possible.

myCmpItem = map(int, myCmpItem)

Then, define a function that calculates the distance between an item and myCmpItem. We need to map the items to lists of integers as well. The rest is just the vanilla formula for L1 distance (the mathematical name of the "difference" you're computing).

def dist(item):
    item = map(int, item)
    return sum(abs(item[i] - myCmpItem[i]) for i in xrange(len(item)))

Then, use this function as a key function for sorting.

sorted(myList, key=dist)

(PS: are you sure L1 distance makes sense for this application? Using it expresses the assumption that answer 1 is more similar to answer 2 than to answer 3, etc. If that's not the case, Hamming distance might be more appropriate.)




ANSWER 2

Score 4


def cmpWith(num):
    def compare(item):
        """ calculate the difference between num and item """
        return sum(
            abs(int(n) - int(x)) # cast to int to make the substraction possible
            for x,n in zip(item, num) # zip makes pairs from both lists 
        )

    return compare

lst = ['111','222','333','444','555','123']
print sorted(lst, key=cmpWith('511'))



ANSWER 3

Score 4


With lambda and list comprehension:

sorted(myList, key=lambda item: sum([abs(int(x) - int(y)) for x, y in zip(item, myCmpItem)])



ANSWER 4

Score 2


How about this?

myCmpItem = '511'
myList = ['111','222','333','444','555','123']

def make_key(x):
    diff = 0
    for a, b in zip(x, myCmpItem):
        diff += abs(int(a)-int(b))
    return diff

mySortedList = sorted(myList, key=make_key)

print mySortedList