Python Forum
a.sort() == b.sort() all the time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a.sort() == b.sort() all the time
#1
Photo 
Hi!

Why a.sort() is equal with b.sort() all the time?

words = ['aabb', 'abcd', 'bbaa', 'dada']
word = 'abba'
def anagram(word, words):
    l = []
    a = sorted(word)
    for n in words:
        b = sorted(n)
        if a.sort() == b.sort():
            l.append(n)
    
    return l

print(anagram(word, words ))
This is the problem:
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
Reply
#2
When a is a list, a.sort() sorts the list in place, but the call to a.sort() returns None
>>> a = [1, 8, 4, 2]
>>> a.sort()
>>> a
[1, 2, 4, 8]
>>> a.sort() is None
True
Hence you are testing None == None, which always returns True.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list.sort() returning None SmallCoder14 8 410 Mar-19-2024, 09:49 PM
Last Post: SmallCoder14
  sort search results by similarity of characters jacksfrustration 5 367 Feb-16-2024, 11:59 PM
Last Post: deanhystad
  Sort a list of dictionaries by the only dictionary key Calab 1 453 Oct-27-2023, 03:03 PM
Last Post: buran
  How to sort .csv file test log which item first fail and paint color SamLiu 24 4,708 Sep-03-2022, 07:32 AM
Last Post: Pedroski55
  'dict_items' object has no attribute 'sort' Calli 6 4,352 Jul-29-2022, 09:19 PM
Last Post: Gribouillis
  Sort Differences in 2.7 and 3.10 Explained dgrunwal 2 1,330 Apr-27-2022, 02:50 AM
Last Post: deanhystad
  list sort() function bring backs None CompleteNewb 6 4,006 Mar-26-2022, 03:34 AM
Last Post: Larz60+
  How to perform DESC table sort on dates stored as TEXT type. hammer 7 2,127 Mar-15-2022, 01:10 PM
Last Post: hammer
  [solved] Sort list paul18fr 5 2,806 Aug-18-2021, 06:34 AM
Last Post: naughtyCat
  How to sort values descending from a row in a dataframe using python sankarachari 1 1,397 Aug-16-2021, 08:55 AM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020