Something like this seems like an obvious way:
#!/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)
Output:
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$
If you want to match true regardless of the number of each digit, then use set
to eliminate duplicates:
#!/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)
Output:
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$
If you really must do it the hard way, then this replicates the first example without using 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)
and outputs:
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$
For the code you have in your question in your latest edit, just change:
if i == list_b[j]:
to:
if list_a[i] == list_b[j]:
and it'll work. That being said, it won't always work, because when you do this:
while j<d:
every time you remove an element from list_b
, the length of list_b
will change, but d
will not. You'll be going out of bounds when the digits are not the same unless you update d
to equal the new length each time, and check if list_b
has become empty before you've reached the end of list_a
.