2016-10-15 9 views
0

私のクラスは、intのリストを扱い、再帰的な値を持たないように計算します。私は2つのintSetオブジェクトを取り込み、両方のオブジェクトリスト(vals)に現れる値で新しいオブジェクトを作成する新しいメソッド 'intersect'を実装しました。クラス内のメソッドの内部でクラスのインスタンスを作成する方法、Python

元々私はオブジェクトの代わりに新しいリストを作成して両方のリストにあるintを追加しましたが、私は新しいオブジェクトを作成し、その値を新しいオブジェクトのvalに追加するのに適していると思いました。

class intSet(object): 
    """An intSet is a set of integers 
    The value is represented by a list of ints, self.vals. 
    Each int in the set occurs in self.vals exactly once.""" 

    def __init__(self): 
     """Create an empty set of integers""" 
     self.vals = [] 

    def insert(self, e): 
     """Assumes e is an integer and inserts e into self""" 
     if not e in self.vals: 
      self.vals.append(e) 

    def member(self, e): 
     """Assumes e is an integer 
      Returns True if e is in self, and False otherwise""" 
     return e in self.vals 

    def remove(self, e): 
     """Assumes e is an integer and removes e from self 
      Raises ValueError if e is not in self""" 
     try: 
      self.vals.remove(e) 
     except: 
      raise ValueError(str(e) + ' not found') 

    def __str__(self): 
     """Returns a string representation of self""" 
     self.vals.sort() 
     return '{' + ','.join([str(e) for e in self.vals]) + '}' 

    def intersect(self, other): 
     #intersected = [] 
     intersected = inSet() 
     for x in self.vals: 
      if x in other.vals: 
       #intersected.append(x) 
       intersected.insert(x) 
     return intersected 


a= {-15,-14,-5,-2,-1,1,3,4,11,18} 
b= {-12,-3,3,8,12,16,18,20} 
set1 = intSet() 
set2 = intSet() 
[set1.insert(x) for x in a] 
[set2.insert(x) for x in a] 

print set1.intersect(set2) 

ボーナス質問、ほとんどのコードはMOOC、6.00.1xのための管理者によって書かれました。しかし、私はエラーにNameError: global name 'inSet' is not defined

を取得することはここに私のコードです。私はちょうど '交差'メソッドを実装する必要がありました。 list []中かっこの代わりに辞書目的の中括弧が使われているのはなぜですか?

+0

名前 'inSet'で' t'を忘れました – furas

+2

ボーナス回答: 'set'を作るためにPythonで' set() 'や' {} 'を使うことができます。 '{1,2,3,2,5}' – furas

+0

OMG、ScalaはPythonでエクササイズしますか? – volcano

答えて

1

これはintSetで、inSetではなく、交差メソッドでスペルミスしています。そして、習慣としては、資格を持ってクラスを始める方がよい(固定規則はないが、これは広く守られている習慣である)。

中括弧については、辞書だけでなく、Pythonセットにも当てはまります。だから__str__メソッドでそれらを使うことで、あなたのクラスのインスタンスが本当に一種のセットであることが示されます。

関連する問題