这样的事情似乎是显而易见的:#!/usr/bin/python
def same_digits(a, b):
if sorted(str(a)) == sorted(str(b)):
print "{0} and {1} contain the same digits".format(a, b)
else:
print "{0} and {1} do not contain the same digits".format(a, b)
same_digits(232, 232)
same_digits(232, 223)
same_digits(232, 233)
输出:paul@local:~/src/python/scratch$ ./testnum.py
232 and 232 contain the same digits
232 and 223 contain the same digits
232 and 233 do not contain the same digits
paul@local:~/src/python/scratch$
如果不考虑每个数字的数字而希望匹配true,请使用set来消除重复项:#!/usr/bin/python
def same_digits(a, b):
if sorted(set(str(a))) == sorted(set(str(b))):
print "{0} and {1} contain the same digits".format(a, b)
else:
print "{0} and {1} do not contain the same digits".format(a, b)
same_digits(232, 232)
same_digits(232, 223)
same_digits(232, 233)
same_digits(232, 2333332232)
same_digits(232, 2)
same_digits(232, 234)
输出:paul@local:~/src/python/scratch$ ./testnum2.py
232 and 232 contain the same digits
232 and 223 contain the same digits
232 and 233 contain the same digits
232 and 2333332232 contain the same digits
232 and 2 do not contain the same digits
232 and 234 do not contain the same digits
paul@local:~/src/python/scratch$
如果您真的必须这样做,那么这将复制第一个示例,而不使用sorted():#!/usr/bin/python
def same_digits_loop(a, b):
a_alpha = str(a)
b_alpha = str(b)
if len(a_alpha) != len(b_alpha):
return False
for c in a_alpha:
b_alpha = b_alpha.replace(c, "", 1)
return False if len(b_alpha) else True
def same_digits(a, b):
if same_digits_loop(a, b):
print "{0} and {1} contain the same digits".format(a, b)
else:
print "{0} and {1} do not contain the same digits".format(a, b)
same_digits(232, 23)
same_digits(232, 232)
same_digits(232, 223)
same_digits(232, 233)
same_digits(232, 2333)
以及输出:paul@local:~/src/python/scratch$ ./testnum3.py
232 and 23 do not contain the same digits
232 and 232 contain the same digits
232 and 223 contain the same digits
232 and 233 do not contain the same digits
232 and 2333 do not contain the same digits
paul@local:~/src/python/scratch$
对于您在最新编辑中有疑问的代码,只需更改:if i == list_b[j]:
致:if list_a[i] == list_b[j]:
它会起作用的。也就是说,它不会总是工作,因为当你这样做时:while j
每次从list_b中删除元素时,list_b的长度都会更改,但d不会更改。如果每次更新d以等于新长度,并在到达list_a结尾之前检查list_b是否变为空,则当数字不相同时,将超出界限。