题解 | #判断两个IP是否属于同一子网#

判断两个IP是否属于同一子网

https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218

#判断255.255.0.1形式的字符串是否符合四位在0到255之间的数字且以.号分隔的格式。
def valid_ip(str_ip):
    a = str_ip.split('.')
    if len(a) != 4:
        return False
    try:
        for i in a:
            if (0 <= int(i) <= 255) and (not (((int(i) != 0) and (i.find('0') == 0)))) and (not ' ' in i):
                pass
            else:
                return False
        return True
    except:
        return False

#判断255.255.0.1形式的字符串是否符合掩码1在前0在后的格式。
def valid_yanma(str_yanma):
    b = str_yanma.split('.')
    str_yanma = ''
    for i in b:
        str_yanma += bin(int(i))[2:].rjust(8 ,'0')
    a = str_yanma.rfind('1')
    c = str_yanma.find('0')
    if (a + 1 == c) and (a != -1) and (c != -1):
        return True
    return False

#计算192.168.0.1字符串形式的ip和掩码计算之后的0001整数。
def cal_ip(str_ip, str_yanma):
    a = str_ip.split('.')
    b = str_yanma.split('.')
    c = ''
    d = ''
    
    for i in a:
        c += bin(int(i))[2:].rjust(8, '0')
    for i in b:
        d += bin(int(i))[2:].rjust(8, '0')
    a = int(c, 2)
    b = int(d, 2)
    return a & b
  
while True:
    try:
        yanma = input()
        ip1 = input()
        ip2 = input()
        if valid_ip(yanma) and valid_ip(ip1) and valid_ip(ip2) and valid_yanma(yanma):
            if cal_ip(ip1, yanma) == cal_ip(ip2, yanma):
                print('0')
            else:
                print('2')
        else:
            print('1')
    except:
        break

全部评论

相关推荐

在debug的柠檬精很迷人:好消息:现在HR挑三拣四 15年后 HR跪着求要简历 坏消息:被挑的是这代人,到时候求人的也是这代人。真好。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务