所以下面的代码应该讨论msg中的唯一字符和唯一字符,并制作一个包含两个子列表的列表。例如
crack_the_code('hello there', 'abccd eabfb')
你应该回来
[['h', 'e', 'l', 'o', 't', 'r'], ['a', 'b', 'c', 'd', 'e', 'f']].
我在下面尝试做的是创建三个列表,然后运行for循环来检查我是否在新列表中(unique),如果不在新列表中,则将其添加到列表中,对unique\u代码也是这样做的。你知道吗
最后把这两张单子放在一起并返回,但当我打印出来时一张也没有。任何帮助都将不胜感激。你知道吗
def crack_the_code(msg, code):
unique = []
unique_code = []
cracked = []
for i in msg:
if i not in unique:
unique.extend(i)
for item in code:
if item not in unique_code:
unique_code.extend(item)
cracked = unique.append(unique_code)
return cracked
print(crack_the_code('hello there', 'abcd eabfb'))
您得到
None
,因为unique.append(unique_code)
变异unique
,并且不返回修改后的列表,而是None
(所有变异输入的函数都应该如此)。你可以做return [unique, unique_code]
。你知道吗在确定了回报率之后,你应该使用更好的算法。每当您检查
if i not in unique
时,这会线性地检查列表unique
中的值i
,使其总计O(n^2)
。你知道吗这是使用^{} recipe ^{} ,它保持原始顺序,是
O(n)
,因为它使用set
来跟踪已经看到的字母:如果您不能使用
itertools
,您也可以自己编写(可能稍微慢一点):如果您不关心顺序,只需使用
set
:用append交换extend,用extend交换append。我想你把它们的功能搞糊涂了。你知道吗
将元素附加到列表中。 您可以将一个列表扩展到另一个列表。你知道吗
另外,您在第二个for循环中使用了[item],但将[i]添加到列表中。将其更改为[项目],然后以下代码起作用:
相关问题 更多 >
编程相关推荐