入坑codewars第15天-Regexp Basics - is it IPv4 address?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_37341950/article/details/85000337

题目:

Implement String#ipv4_address?, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots.

It should only accept addresses in canonical representation, so no leading 0s, spaces etc.

题意:

题意:
就是判断ip地址是否符合ipv4的规则;

思路:

思路就是
(1)先将字符串按照“.”分割成列表
(2)然后判断每一个元素是不是数字
(3)处理特殊情况:
        "10.20.030.40", False 这种情况就是030不对的格式;因此我是这样处理的,如果<10,且位数大于1则返回错误;如果小于100且位数大于2则返回false
        还有就是输入的格式不是四段的都返回false

代码如下: 

我的代码:
def ipv4_address(address):
    list1=address.split('.')
    if len(list1) < 4 or len(list1)>4:
        return False
    for x in list1:
        if x.isdigit()==False:
            return False
        else:
            if int(x)>255 or int(x)<0:
                return False
            if int(x)<10 and len(x)>=2:
                return False
            if int(x)<100 and len(x)>2:
                return False
    return True

看看大神的代码:

大神用的正则表达式:

from re import compile, match

REGEX = compile(r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){4}$')#以 . 结尾


def ipv4_address(address):
    # refactored thanks to @leonoverweel on CodeWars
    return bool(match(REGEX, address + '.'))

代码的意思我琢磨了一下发现正则表达式是这个意思: 

点与点之间有一个数;

(1到9之间)的两位数、1开头的三位数、2开头的三位数<250的数、2开头的<=255的数

每个数后面加个 ' . ',然后占位4个意思就是连续4个这样的

第二题:

https://www.codewars.com/kata/second-variation-on-caesar-cipher/train/python

猜你喜欢

转载自blog.csdn.net/sinat_37341950/article/details/85000337