it was a bit tricky, thanks :)<br><br><div class="gmail_quote">On Tue, Nov 24, 2009 at 9:00 AM, Lie Ryan <span dir="ltr"><<a href="mailto:lie.1296@gmail.com">lie.1296@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div class="im">Shashwat Anand wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
I intended to sort a list which sorts according to user-defined custom sorting-order.<br>
For example: If sorting-order is "zabc...wxy", then the output will be in lexicographically sorted order but z will always be given priority over rest others.<br>
as a test case i took sorting order as reverse of normal sorting, hence i defined user_key as string.ascii_lowercase. It should sort in reverse manner but I'm not getting expected output.<br>
(Even though it could have just been sorted as reverse=True, but my intention is to generalize it for this is just a test-case). I'm not able to find where the bug lies nor am i exactly sure how the key function works, even though i use it in a regular fashion. Can you guys help me out ?<br>
</blockquote>
<br></div>
Your code is not wrong. It's your expected output (or your need) that's different from a typical definition of "lexicographical sorting". In a typical lexicographical sorting "a" comes before "ab" since "a" is shorter than "ab".<br>
<br>
<br>
So, if you want this:<div class="im"><br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
expected output: ['cba', 'cab', 'abc', 'ab', 'aa', 'a']<br>
</blockquote></div>
you must use a custom cmp= argument to reverse the shorter substring case:<br>
<br>
<br>
like this:<br>
<br>
import string<br>
<br>
def my_cmp(s1, s2):<br>
if s1.startswith(s2):<br>
return -1<br>
elif s2.startswith(s1):<br>
return 1<br>
else:<br>
return cmp(s1, s2)<div class="im"><br>
<br>
def userdef_sort(l, user_key):<br></div>
table = string.maketrans("".join(sorted(user_key)), user_key)<br>
trans = lambda x: x.translate(table)<br>
return sorted(l, cmp=my_cmp, key=trans)<div class="im"><br>
<br>
#user_key = raw_input()<br>
user_key = string.ascii_lowercase[::-1]<br>
l = ['a', 'aa', 'ab', 'abc', 'cba', 'cab']<br>
<br>
print userdef_sort(l, user_key)<br>
<br></div>
_______________________________________________<br>
Tutor maillist - <a href="mailto:Tutor@python.org" target="_blank">Tutor@python.org</a><br>
To unsubscribe or change subscription options:<br>
<a href="http://mail.python.org/mailman/listinfo/tutor" target="_blank">http://mail.python.org/mailman/listinfo/tutor</a><br>
</blockquote></div><br>