-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuestion 34
54 lines (39 loc) · 1.47 KB
/
Question 34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#Instructions from your teacher:
#Given a string s containing only digits. Return all possible valid IP addresses that can be obtained from s.
#You can return them in any order.
#A valid IP address consists of exactly four integers, each integer is between 0 and 255,
#separated by single points and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses
#and "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses.
#Input: s = "1111"
#Output: ["1.1.1.1"]
#Input: s = "101023"
#Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
def valid_ip1(ip):
ip=ip.split(".")
for i in ip:
if len(i) > 3 or int(i) < 0 or int(i) > 255:
return False
if len(i) > 1 and int(i) == 0:
return False
if len(i) > 1 and int(i) != 0 and i[0] == '0':
return False
return True
def valid_ip(s):
sz = len(s)
if sz > 12:
return []
snew = s
res = []
for i in range(1, sz - 2):
for j in range(i + 1, sz - 1):
for k in range(j + 1, sz):
snew = snew[:k] + "." + snew[k:]
snew = snew[:j] + "." + snew[j:]
snew = snew[:i] + "." + snew[i:]
if valid_ip1(snew):
res.append(snew)
snew = s
return res
if __name__ == "__main__":
input_string = "0000"
print(valid_ip(input_string))