물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

IP Validation

BEstyle 2022. 10. 11. 12:51

DESCRIPTION:

Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.

Valid inputs examples:

Examples of valid inputs:
1.2.3.4
123.45.67.89

Invalid input examples:

1.2.3
1.2.3.4.5
123.456.78.90
123.045.067.089

Notes:

  • Leading zeros (e.g. 01.02.03.04) are considered invalid
  • Inputs are guaranteed to be a single string

def is_valid_IP(strng):
    alist=strng.split(".")
    if len(alist)!=4:
        return False
    for i in range(len(alist)):
        try:
            int(alist[i])
        except:
            return False
        if int(alist[i])<0:
            return False
        elif int(alist[i])>255:
            return False
        elif ' ' in alist[i]:
            return False
        elif '\n' in alist[i]:
            return False
        elif alist[i][0]=="0" and len(alist[i])>1:
            return False
    return True

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Sum of Parts  (0) 2022.10.12
Make the Deadfish Swim  (0) 2022.10.11
Give me a Diamond  (0) 2022.10.11
Greed is Good  (0) 2022.10.11
WeIrD StRiNg CaSe  (0) 2022.10.11