lundi 13 juin 2016

Python TypeError: 'type' object does not support item assignment


I got error message TypeError: 'type' object does not support item assignment for "dict[n] = n". Any help or suggestion? Thank you so much!

Here is the purpose of this code.

Design and implement a TwoSum class. It should support the following operations: add and find.

add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value.

For example,

add(1);

add(3);

add(5);

find(4) -> true

find(7) -> false

  class TwoSum(object):

        dict = {}

        def add(self,n):
            dict[n] = n #TypeError: 'type' object does not support item assignment

        def find(self,n):
            for i in range(0,len(dict)+1):
                if dict[i] == None:
                    continue

                val = n - dict[i]
                if dict[val] != None and val != i+1:
                    return True
            return False


    test = TwoSum()
    test.add(1)
    test.add(3)
    test.add(5)
    print(test.find(4))
    print(test.find(7))

Aucun commentaire:

Enregistrer un commentaire