标签:ips ble ali 并且 gre variable put 相减 iter
题目:
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.
ips_between("10.0.0.0", "10.0.0.50") == 50
ips_between("10.0.0.0", "10.0.1.0") == 256
ips_between("20.0.0.10", "20.0.1.0") == 246
我的答案:604ms
def ips_between(start, end): num = 0 re = [] st = list(map(int, start.split("."))) en = list(map(int, end.split("."))) print(st,en) for i in range(len(st)): re.append(en[i] - st[i]) re = re[::-1] for k in range(len(re)): num = num + 256**k * re[k] return num
将字符串转换为列表后,将两个列表对应未知相减,得到的值再按位数计算
1、需要将字符串转换为列表,可使用.split()方法
2、将列表中的字符串转换为整形,使用map(int,XXX)方法
3、转换出来之后为生成器,需使用list打开
方法二:616ms
def ips_between(start, end): a = sum([int(e)*256**(3-i) for i, e in enumerate(start.split(‘.‘))]) b = sum([int(e)*256**(3-i) for i, e in enumerate(end.split(‘.‘))]) return abs(a-b)
思路大致不变,优化代码。
分别计算出start和end时的地址个数,然后将个数相减。
方法三:655ms
def ips_between(start, end): return sum((int(b) - int(a)) * 256 ** i for i, (b, a) in enumerate(reversed(list(zip(end.split(‘.‘), start.split(‘.‘))))))
思路一致,使用enumerate+zip同时取出两列表的内容,并且可以保留i,再进行计算
注意:zip是iterator,不可以直接使用reversed进行翻转,需要先list()手动转换
标签:ips ble ali 并且 gre variable put 相减 iter
原文地址:https://www.cnblogs.com/lsh-1225/p/14658913.html