[Tutor] implementing set operations [was Re: (no subject)]
wesley chun
wescpy at gmail.com
Wed Jul 29 22:27:23 CEST 2009
> could this be done in a more elegant fashion?
in addition to alan's obvious solution, if you wanted to roll your
own, you have a good start. my comments below.
> def Unite(set1, set2): # evaluate 2 lists, join both into 1 new list
> newList = []
> for item in set1:
> newList.append(item)
> for item in set2:
> newList.append(item)
> newList.sort()
> return newList
- as a style point, use lowercase for all function and variable names.
Capping the first letter is recommended only for class names.
- changing it from "unite" to "union" would make it slightly more accurate
- why the sort()? sets, are by default, unordered data structures...
think of drawing its elements inside the circles in Venn diagrams.
- if you do end up using Python sets, use the set() factory function
in 2.x, i.e, newSet = set(set1) + set(set2); or set literals in Python
3.x, i.e., mySet = {1, 5, -4, 42}, if you have the exact elements
> def Intersect(set1, set2): # evaluate 2 lists, check for
> commonalities, output commonalities to 1 new list
> newList = []
> for item in set1:
> if item in set1 and item in set2:
> newList.append(item)
> newList.sort()
> return newList
- the "item in set1 and " in the if-statement is redundant. blow it away
- i think you can build it using a listcomp
> def Negate(set1, set2): # evaluate 2 lists, return negation of 1st list
> newList = []
> for item in set1:
> if item in set2:
> set1.remove(item)
> newList = set1
> return newList
- you probably don't want to call set1.remove(). lists are immutable,
and you would've change the contents of set1. it's best if you made
newList a copy of set1, i.e., newList = list(set1) or newList =
set1[:], and *then* did your for-loop
- better yet, use a list comp with an if to build newList to avoid all
of the shenanigans i just described
hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list