上述代码仍然报错TypeError: unsupported operand type(s) for *: 'Link' and 'Link',能否只修改deep_map函数
时间: 2024-01-28 17:03:52 浏览: 24
当然可以。我们只需要在 `deep_map` 函数中将递归调用时的第二个参数改为 `deep_map(f, link.rest)`,即可保证在递归调用时,传递的参数都是链表类型。
下面是修改后的 `deep_map` 函数的代码:
```python
def deep_map(f, link):
if link.rest is Link.empty:
return Link(f(link.first))
else:
return Link(f(link.first), deep_map(f, link.rest))
```
现在再运行 `deep_map` 函数,就不会报错了。
相关问题
上述代码会报错TypeError: unsupported operand type(s) for *: 'Link' and 'Link'
这个错误是因为在 `__repr__` 方法中,如果 `rest` 不是空链表,我们在拼接字符串时没有考虑到 `rest` 也是一个链表,导致了错误。
为了解决这个问题,我们需要在拼接字符串时,对 `rest` 调用 `__repr__` 方法,而不是直接将其转换成字符串。
下面是修改后的 `__repr__` 方法的代码:
```python
class Link:
empty = ()
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is not Link.empty:
rest_repr = ', ' + self.rest.__repr__()
else:
rest_repr = ''
return 'Link(' + repr(self.first) + rest_repr + ')'
def __str__(self):
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'
```
现在再运行 `deep_map` 函数,就不会报错了。
仍然报错TypeError: unsupported operand type(s) for -: 'str' and 'int' 继续修改
这个错误可能还会出现在其他函数参数中,你需要检查一下每个函数的参数是否正确。可能还需要检查一下数据类型是否正确。
以下是一些可能需要检查的函数参数:
- `plot_contours()`函数中的`cmap`参数,需要传入一个颜色映射对象,例如`plt.cm.plasma`。
- `ax.scatter()`函数中的`c`参数,需要传入一个颜色序列,例如`y`。
- `ax.scatter()`函数中的`s`参数,需要传入一个整型变量,例如`20`。
- `ax.scatter()`函数中的`edgecolors`参数,需要传入一个颜色序列,例如`'k'`。
你可以检查一下这些函数的参数是否正确,或者将错误信息贴出来,以便更好地定位问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)