Shorten an IPv6 address

IPv6 addresses are long, so they have a short form. Write the shortest standard form.

What to build

A program that shortens a full IPv6 address.

Requirements

  • Write all letters in lower case and drop the leading zeros of every group (an all-zero group becomes 0).
  • Replace the longest run of two or more all-zero groups with ::. If two runs have the same length, replace the first one.
  • Use :: at most once. Do not shorten a single zero group.

Input

One line: a full IPv6 address, eight groups of four hex digits separated by colons.

Output

The shortened address.

Constraints

Digits may be upper or lower case.

Example

Input:

2001:0db8:0000:0000:0000:ff00:0042:8329

Output:

2001:db8::ff00:42:8329

Why it works

Dropping leading zeros is always safe. The :: stands for exactly one run of zero groups, so choosing the longest run saves the most space, and choosing the first on a tie makes the answer unique.

Examples

Example 1 · Input
2001:0db8:0000:0000:0000:ff00:0042:8329
Expected output
2001:db8::ff00:42:8329
Example 2 · Input
0000:0000:0000:0000:0000:0000:0000:0001
Expected output
::1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Remove leading zeros from each group, but keep a single 0 when the group is all zeros.

Hint 2

Find the longest run of groups equal to 0. If two runs tie, use the first. A run of one group is not shortened.

Hint 3

Join the groups before the run with ":", add "::", then join the groups after it. Handle runs at the start and at the end.

Solution

Show one correct solution (try it yourself first)
text = input().strip().lower()
groups = [g.lstrip("0") or "0" for g in text.split(":")]
best_start, best_len = -1, 1
i = 0
while i < 8:
    if groups[i] == "0":
        j = i
        while j < 8 and groups[j] == "0":
            j += 1
        if j - i > best_len:
            best_start, best_len = i, j - i
        i = j
    else:
        i += 1
if best_start < 0:
    print(":".join(groups))
else:
    left = ":".join(groups[:best_start])
    right = ":".join(groups[best_start + best_len:])
    print(left + "::" + right)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: IP addresses →