2
\$\begingroup\$

I just started doing preparation for interviews, but im having trouble recognizing the optimal solution

Problem: For a given IP Address, replace every "." with "[.]"

Example:

Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

My solutions:

First:

def defang(x):
    lst = []
    for i in x:
        if i == ".":
             lst.append("[" + i + "]")
        else:
            lst.append(i)
    return lst

adress = "255.100.50.0"
tmp = defrang(adress)
x=''
for i in tmp:
    x+=i
print(x)

Second:

adress = "255.100.50.0"
print("[.]".join(adress.split('.')))

Which one you think is better? The first doesnt rely on built-in methods but it creates a new list (more memory wasted?)

The second seems better but is it a problem that it relies on built-in methods?

In general idk what level of abstraction is requested by the interviewers, so any advice is welcome (regarding this specific solution or whatever else)

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Using built-in functions is generally good practice and it's really (!) hard to beat their performance with self-written Python code (since they are implemented in C, not Python). \$\endgroup\$ – riskypenguin Apr 10 at 16:08
  • 1
    \$\begingroup\$ I'd definitely always create a function and not use the print statement from the function, as I/O should be separated. \$\endgroup\$ – Maarten Bodewes Apr 10 at 16:10
  • 5
    \$\begingroup\$ Both are bad. You should just use address.replace('.', '[.]'). \$\endgroup\$ – Manuel Apr 10 at 18:59
2
\$\begingroup\$

If you are in an interview using Python, assume that the interviewer is reasonable and wants you to write fluent Python code. That means, among other things, taking advantage of the language's built-in powers:

def defrang(ip):
    return ip.replace('.', '[.]')

But let's suppose that the interviewer explicitly directs you to ignore built-ins and write your own implementation that does the work character-by-character. Your current implementation is reasonable, but I would suggest a few things. (1) Especially at interface points (for example, a function's signature) use substantive variable names when they make sense. (2) Don't make the caller re-assemble the IP address. (3) There is no need to use concatenation to create a literal: just use '[.]' directly. (4) The logic is simple enough for a compact if-else expression (this is a stylistic judgment, not a firm opinion).

def defang(ip_address):
    chars = []
    for c in ip_address:
        chars.append('[.]' if c == '.' else c)
    return ''.join(chars)

A final possibility is to distill further and just use a comprehension.

def defang(ip_address):
    return ''.join(
        '[.]' if c == '.' else c 
        for c in ip_address
    )
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.