Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5852

RE: Python sets which support multiple same elements

From Andreas Tawn <andreas.tawn@ubisoft.com>
Date 2011-05-20 13:53 +0200
Subject RE: Python sets which support multiple same elements
References <f7760e6f-b176-4c13-8285-08d7689ece02@f31g2000pri.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1838.1305892439.9059.python-list@python.org> (permalink)

Show all headers | View raw


> For example, I was writing a program to detect whether two strings are
> anagrams of each other. I had to write it like this:
> 
> def isAnagram(w1, w2):
>   w2=list(w2)
>   for c in w1:
>     if c not in w2:
>       return False
>     else:
>       w2.remove(c)
>   return True
> 
> But if there was a data structure in python which supported duplicate
> elements(lets call it dset), then I could just write:
> 
> def inAnagram(w1,w2):
>   return dset(w1)==dset(w2)
> 
> Example of some dset methods:
> {1,2,3,3} intersection {4,1,2,3,3,3}  == {1,2,3,3}
> {1,2,3,3} union {4,1,2,3,3,3} == {1,2,3,3,3,4}
> {4,1,2,3,3,3} difference {1,2,3,3} == {4,3}
> 
> Do you think that it would be a good idea to add this kind of data
> structure to python? Or did I overlook some other easy way to solve
> this kind of problems?

Just to do the anagram problem you could do...

def isAnagram(w1, w2):
    return sorted(w1) == sorted(w2)

To do the set-like operations, I guess that unless there's some itertools witchcraft available, you'd have to make your own dset type that inherits from list. Then you can define your own intersection/union etc. methods.

Cheers,

Drea

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Python sets which support multiple same elements ErichCart ErichCart <erichcart@gmail.com> - 2011-05-20 04:37 -0700
  RE: Python sets which support multiple same elements Andreas Tawn <andreas.tawn@ubisoft.com> - 2011-05-20 13:53 +0200
  Re: Python sets which support multiple same elements Chris Angelico <rosuav@gmail.com> - 2011-05-20 21:57 +1000

csiph-web