[Tutor] Str method

Ashley Fowler afowler2 at broncos.uncfsu.edu
Mon Nov 5 03:01:49 CET 2012


I have code for a Set ADT. The Set ADT is a container that stores a collection of values or elements.




Below is some of my code...I have run into two problems so far.




First I have to modify  __init__ method so that new sets can be initialized to a list of elements. This modification adds a starred parameter, *initElements. But somehow I still need to initialize a list to several elements and I have no clue what to do. The other problem is I had to add the str method to allow a user to print the contents of the set... meaning I must construct a string from the elements of the set one by one, and with curly braces at the beginning and at the end.




class Set :
  
  def __init__( self, *initElements ):
    self._theElements = list()
    
  def __len__( self ):
    return len( self._theElements )
    
  def __contains__( self, element ):
    return element in self._theElements   
    
  def add( self, element ):                  
    if element not in self :
      self._theElements.append( element ) 
      
  def remove( self, element ):
    assert element in self, "The element must be in the set."
    self._theElements.remove( item )




  def __iter__( self ):
    return _SetIterator( self._theElements )




  def __str__(self):
    for element in str(self._theElements):
      return element
    
________________________________________
From: Oscar Benjamin [oscar.j.benjamin at gmail.com]
Sent: Sunday, November 04, 2012 8:52 PM
To: Ashley Fowler
Cc: tutor at python.org
Subject: Re: [Tutor] Str method

On 5 November 2012 01:45, Ashley Fowler <afowler2 at broncos.uncfsu.edu> wrote:
> I'm trying to  initialize a list to several elements using the string
> method. I have some idea that you use a for loop I suppose...
>
> Could anybody help me out?

I'm afraid not. Your question is too vague for anyone receiving your
message to know what it is you are trying to do (I have no idea what
"the string method" is).

Can you please:
1) Post the code that you tried
2) Explain what output you were hoping for
3) Show the exact output that you got (if it is an error message then
please post the entire exact error message).


Oscar




More information about the Tutor mailing list