このようなものは明白な方法のように思えます:
#!/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$
各桁の数に関係なく真に一致させたい場合は、次を使用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<d:
から要素を削除するたびlist_bに、 の長さlist_bは変わりますが、変わりdません。d毎回新しい長さに等しくなるように更新しない限り、数字が同じでない場合は範囲外にlist_bなり、 の終わりに達する前に が空になったかどうかを確認しますlist_a。