2016-10-15 3 views
0

제 수업에서는 int 목록을 처리하고 다시 계산하여 값을 다시 계산하지 않습니다. 두 개의 intSet 객체를 사용하고 두 객체 목록 (vals)에 나타나는 값을 사용하여 새 객체를 만드는 새로운 메소드 인 'intersect'를 구현했습니다.클래스 내에서 클래스의 인스턴스를 만드는 법, 파이썬

원래는 (개체 대신) 새 목록을 만들었습니다. 두 목록에있는 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'을 만들려면'set()'또는'{}'를 사용할 수 있습니다. '{1,2,3,2,5}' – furas

+0

OMG, 스칼라는 파이썬으로 연습합니까?! – volcano

답변

1

intSet이 아니라 inSet입니다. 교차 메서드에서 잘못 입력했습니다. 그리고 습관으로 수도로 수업을 시작하는 것이 더 낫습니다 (고정 된 규칙은 없지만, 이것은 널리 준수되는 습관입니다).

중괄호는 사전뿐만 아니라 Python 세트에도 해당됩니다. 그래서 __str__ 메쏘드에서 그것들을 사용함으로써, 여러분의 클래스의 인스턴스가 참으로 일종의 세트라는 것을 알 수 있습니다.

관련 문제