จากสตริงตัวเลข สร้าง IP address ที่ถูกต้องทั้งหมดโดยวางจุด 3 จุด และตรวจสอบความถูกต้อง (0-255, ไม่มี leading zeros ยกเว้น 0)
ตัวอย่าง
Input: "25525522134" Output: ['255.255.22.134', '255.255.221.34']
อัลกอริทึม
- เช็คความยาวสตริง (ต้อง <= 12)
- วางจุด 3 จุด ทุกตำแหน่งที่เป็นไปได้ (3 nested loops)
- ตรวจสอบแต่ละ segment ว่าถูกต้องหรือไม่
- เก็บ IP ที่ถูกต้อง
โค้ดตัวอย่าง
def ipvalid(ip):
parts = ip.split(".")
for p in parts:
if len(p) > 3 or int(p) < 0 or int(p) > 255:
return False
if len(p) > 1 and int(p) == 0:
return False
if len(p) > 1 and p[0] == '0':
return False
return True
def ipconvert(A):
if len(A) > 12:
return []
res = []
for i in range(1, len(A)-2):
for j in range(i+1, len(A)-1):
for k in range(j+1, len(A)):
candidate = A[:i] + "." + A[i:j] + "." + A[j:k] + "." + A[k:]
if ipvalid(candidate):
res.append(candidate)
return res
A = input("Enter IP address digits: ")
print(ipconvert(A))
ผลลัพธ์
Enter IP address digits: 25525522134 ['255.255.22.134', '255.255.221.34']