python比较两个数的大小如果位数不同_两个数字的比较

这样的事情似乎是显而易见的:#!/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是否变为空,则当数字不相同时,将超出界限。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值