What IP Addresses Are Possible?
A valid IP address consists of four integers separated by periods. Each integer is between 0 and 255 (inclusive) and cannot have leading zeroes. Given a string containing only digits, return all possible valid IP addresses that can be formed by inserting periods.
A solution for possible IP addresses.
Solution
""" ip_addresses.py """
# usage: python3 ip_addresses.py digits
# e.g. python3 ip_addresses.py 12101970
import sys
def octets(digits_text):
""" combinations of octets from digits_text """
size = len(digits_text)
if size == 0 or size > 12:
return []
output = [digits_text[:1]]
if output != ['0']:
if size > 1:
output.append(digits_text[:2])
if size > 2:
text_num = digits_text[:3]
if int(text_num) < 256:
output.append(text_num)
return [(i, octets(digits_text[len(i):])) for i in output]
def ip_addresses(digits_text):
""" sieve for valid ip combinations that use entire digits_text """
return ['.'.join([h0, i0, j0, k0])
for h0, h1 in octets(digits_text)
for i0, i1 in h1
for j0, j1 in i1
for k0, k1 in j1 if k1 == []]
print(ip_addresses(sys.argv[1]))