Example:
myCmpItem = '511'
myList = ['111','222','333','444','555','123']
(some magic)
mySortedList = ['111', '222', '333', '123', '444', '555']
I could code this with alot of for-loops, but I am actually looking for a faster way to do this. Is there any algorithm that does something like that? Fast?
All item's digits are answers to questions and I want to find the most similar answer-set to a given answer-set. So "123" means that a user answered to Questions 1 = Answer 1, Question 2 = Answer 2, Question 3 = Answer 3. They are multiple choice questions with 25 questions in total (= length of 25) and there are always 5 different possibilites to answer (Those are the digits 1-5).
PS: This is the first question I asked on Stackoverflow so please be kind with me. I already googled for hours but I could not find any solution, so I asked here. I hope that is fine. Also english is not my native language.
@larsmans' answer (https://stackoverflow.com/a/10790714/511484) explains very well how to solve this with reasonable speed. You can even speed up the algorithm by calculating the distances between every digit in advance, see @gnibbler's post (https://stackoverflow.com/a/10791838/511484) All the other answers were also nice and correct, but I found that @larsmans had the best explanation. Thanks everybody once again for the help!
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.)
With lambda
and list comprehension:
sorted(myList, key=lambda item: sum([abs(int(x) - int(y)) for x, y in zip(item, myCmpItem)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With