Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix is_ip_v4_address_valid.py #12394

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 38 additions & 15 deletions maths/is_ip_v4_address_valid.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
"""
wiki: https://en.wikipedia.org/wiki/IPv4

Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254
for example: 192.168.23.1, 172.254.254.254 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address
A valid IP address must be four numbers in the form of A.B.C.D,
where A,B,C and D are numbers from 0-255

for example:
192.168.23.1, 172.254.254.254 are valid IP address
192.168.01.0, 256.192.3.121 are invalid IP address
"""


def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
def is_ip_v4_address_valid(ip: str) -> bool:
"""
print "Valid IP address" If IP is valid.
or
Expand All @@ -17,12 +21,15 @@ def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
True

>>> is_ip_v4_address_valid("192.255.15.8")
False
True

>>> is_ip_v4_address_valid("172.100.0.8")
True

>>> is_ip_v4_address_valid("254.255.0.255")
>>> is_ip_v4_address_valid("0.0.0.0")
True

>>> is_ip_v4_address_valid("254.256.0.255")
False

>>> is_ip_v4_address_valid("1.2.33333333.4")
Expand All @@ -40,17 +47,33 @@ def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
>>> is_ip_v4_address_valid("1.2.A.4")
False

>>> is_ip_v4_address_valid("0.0.0.0")
True

>>> is_ip_v4_address_valid("1.2.3.")
>>> is_ip_v4_address_valid("1.2.3.05")
False
"""
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)

parts = ip.split(".")

if len(parts) != 4:
return False

for part in parts:
if not part:
return False

for i in range(len(part)):
if not part[i].isdigit():
return False

if part[0] == "0" and len(part) > 1:
return False

if not (0 <= int(part) <= 255):
return False

return True


if __name__ == "__main__":
ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.")
result = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {result} IPv4 address.")
Loading