my code:
a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error
memoize function:
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]#<------t开发者_StackOverflow中文版his
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result#<-----and this
return result
In the memoize
function, I'm assuming cache
is a dict
. Also, since a is a list
, b will also be a list
, and lists are not hashable. Use a tuple
.
Try
a = (1, 2, 3, 4) # Parens, not brackets
b = a[:2]
c = {} # Curly braces, not brackets
c[b] = 'sss'
What has your question got to do with the memoize function you post?
Presumably (although we have to guess, since you didn't post the actual error) you're getting a TypeError. This is due to two mistakes.
Firstly, c
is a list. So you can't use arbitrary keys, you can only use integer indexes. Presumably you meant to define a dictionary here: c = {}
Secondly, you're getting a list in statement 2 - b
equals [1, 2]
- and this is not a valid dictionary index. a
should have been a tuple: a = (1, 2, 3, 4)
.
I must reiterate the advice that other people have been giving you. Please find an introduction to programming and read that before trying to copy advanced Python code that you don't understand.
精彩评论