- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRestoreIP.py
More file actions
Latest commit
46 lines (39 loc) · 1.12 KB
/
Copy pathRestoreIP.py
File metadata and controls
46 lines (39 loc) · 1.12 KB
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
#!/usr/bin/env python
'''
Given a string containing only digits,
restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
'''
ips= []
defrestore_ip(ip_str, num_segment):
'''
Args:
ip_str:a string represent ip
num_segment: number segments of the ip
Return:
list of possible ip
'''
solutions= []
ifnotnum_segment:
raiseException("Should never happen")
foriinrange(1, len(ip_str) +1):
segment=ip_str[0:i]
segment_value=int(segment)
ifsegment_value>255: # like '2551'
break
eliflen(segment) >=2andsegment.startswith('0'): # like '01'
break
else:
ifnum_segment==1:
ifnotip_str[i:]:
# It's empty, so this is a solution.
solutions.append(segment)
else:
sub_segments=restore_ip(ip_str[i:], num_segment-1)
ifsub_segments:
solutions.extend([segment+"."+sforsinsub_segments])
returnsolutions
printrestore_ip("25525511135", 4)
printrestore_ip("21111", 4)