如何解决此python代码中缺少1个必需的位置参数?
在下面的python代码中,我正在测试这两个字符串是否为字符串置换,但在代码后面附加了一个错误如何解决此python代码中缺少1个必需的位置参数?,python,algorithm,data-structures,Python,Algorithm,Data Structures,在下面的python代码中,我正在测试这两个字符串是否为字符串置换,但在代码后面附加了一个错误 from collections import Counter str_1 = "driving" str_2 = "drivign" def check_permutation(str_1,str_2): if len(str_1) != len(str_2): return False counter = Coun
from collections import Counter
str_1 = "driving"
str_2 = "drivign"
def check_permutation(str_1,str_2):
if len(str_1) != len(str_2):
return False
counter = Counter()
for c in str_1:
counter[c] += 1
for c in str_2:
if counter[c] == 0:
return False
counter[c] -= 1
return True
print(check_permutation((str_1, str_2)))
错误:
Traceback (most recent call last):
TypeError: check_permutation() missing 1 required positional argument: 'str_2'
如何解决此错误并在控制台中打印输出?- 我猜您的代码中有额外的括号,在输入
和str_1
中有轻微的缩进问题:str_2
- 此外,最好在调用或使用变量的位置附近声明变量
- 您还可以稍微改进变量的命名
我想,以下代码可能就是您正在尝试执行的操作:
from collections import Counter
def check_permutation(str_1, str_2):
if len(str_1) != len(str_2):
return False
count_map_1 = Counter(str_1)
count_map_2 = Counter(str_2)
return count_map_2 == count_map_1
str_1 = "driving"
str_2 = "drivign"
尝试删除函数中的附加圆括号,例如,
print(检查置换(str\u 1,str\u 2))
附加圆括号使python认为您需要一个元组,这可能不是您的意图。效果很好。谢谢你的解释。
True
from collections import Counter
def check_permutation(str_1, str_2):
if len(str_1) != len(str_2):
return False
count_map_1 = Counter(str_1)
count_map_2 = Counter(str_2)
return count_map_2 == count_map_1
str_1 = "driving"
str_2 = "drivign"