Tang - 1 year ago 82

Python Question

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))

Answer

Lot of issues here, I'll try to go through them one by one

```
dict = {}
```

Not only is this ~~overwriting python's dict~~, (see mgilson's comment) but this is the wrong data structure for the project. You should use a list instead (or a set if you have unique unordered values)

The data structure is an instance variable, it needs to be defined with `self`

and inside the `__init__`

function. You should be using something like this:

```
class TwoSum(object):
def __init__(self):
self.numbers = []
```

```
def add(self,n):
dict[n] = n
```

Assigning items to a dictionairy is not the way to do it. You should instead append to your list. Additionally you need to append to the list for that instance using `self.variableName = value`

That range is wrong, and you would need a nested range, or itertools.combinations since you have to check for any two numbers that sum to a certain value, pythons `sum()`

is handy here.

To loop through the numbers you can use two ranges or itertools.combinations

```
import itertools
class TwoSum(object):
def __init__(self):
self.numbers = []
def add(self, num):
self.numbers.append(num)
def find(self, desiredSum):
for 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(self, desiredSum):
for num1 in self.numbers:
for num2 in self.numbers:
if num1 + num2 == desiredSum and num1 != num2:
return True
return False
```

Source (Stackoverflow)