# Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)

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

x=''
for i in tmp:
x+=i
print(x)


Second:

adress = "255.100.50.0"


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)

• 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). – riskypenguin Apr 10 at 16:08
• I'd definitely always create a function and not use the print statement from the function, as I/O should be separated. – Maarten Bodewes Apr 10 at 16:10
• Both are bad. You should just use address.replace('.', '[.]'). – Manuel Apr 10 at 18:59

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 = []

def defang(ip_address):