Python TypeError: 'type' object does not support item assignment -
i have design , implement twosum
class. should support following operations:
add
- add number internal data structure.find
- find if there exists pair of numbers sum equal value.
here code:
class twosum(object): dict = {} def add(self,n): dict[n] = n #typeerror: 'type' object not support item assignment def find(self,n): in range(0,len(dict)+1): if dict[i] == none: continue val = n - dict[i] if dict[val] != none , val != i+1: return true return false test = twosum() test.add(1) test.add(3) test.add(5) print(test.find(4)) # true print(test.find(7)) # false
i got error message
typeerror: 'type' object not support item assignment "dict[n] = n"
any or suggestion? thank much!
lot of issues here, i'll try go through them 1 one
the data structure
dict = {}
not overwriting python's dict, (see mgilson's comment) wrong data structure project. should use list instead (or set if have unique unordered values)
using data structure
the data structure instance variable, needs defined self
, inside __init__
function. should using this:
class twosum(object): def __init__(self): self.numbers = []
def add
def add(self,n): dict[n] = n
assigning items dictionairy not way it. should instead append list. additionally need append list instance using self.variablename = value
def find
that range wrong, , need nested range, or itertools.combinations since have check 2 numbers sum value, pythons sum()
handy here.
to loop through numbers can use 2 ranges or itertools.combinations
the code
import itertools class twosum(object): def __init__(self): self.numbers = [] def add(self, num): self.numbers.append(num) def find(self, desiredsum): nums in itertools.combinations(self.numbers, 2): if sum(nums) == desiredsum: return true return false test = twosum() test.add(1) test.add(3) test.add(5) print(test.find(4)) print(test.find(7)) #true #false
def find without itertools
def find(self, desiredsum): num1 in self.numbers: num2 in self.numbers: if num1 + num2 == desiredsum , num1 != num2: return true return false
Comments
Post a Comment