How to Solve ‘isMAC48Address’ in CodeFights

The Problem:

A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.

The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).

Example

  • For inputString = "00-1B-63-84-45-E6", the output should be
    isMAC48Address(inputString) = true;
  • For inputString = "Z1-1B-63-84-45-E6", the output should be
    isMAC48Address(inputString) = false;
  • For inputString = "not a MAC-48 address", the output should be
    isMAC48Address(inputString) = false.

Input/Output

  • [time limit] 4000ms (py)
  • [input] string inputStringConstraints:
    15 ≤ inputString.length ≤ 20.
  • [output] booleantrue if inputString corresponds to MAC-48 address naming rules, false otherwise.

The Solution:

def isMAC48Address(inputString):
r = inputString.split('-')
if len(r)!=6:
return 0
for x in r:
if len(x)!=2:
return 0
try:
int(x,16)
except:
return 0
return 1

The Explanation:

We get the input as a string, so, we should be able to split it by “-” and we should have 6 parts. First if statement checks this. Then, for each of these parts, we should be able to typecast it to hexadecimal integer. If we get error while converting, then it contains an illegal character. Sometimes, we can get something like, 3-4-5-6-7-8. This has 6 parts and each of them can be converted to hexadecimal numbers but is an illegal mac address. The correct form would be 03-04-05-06-07-08. Therefore, we need to check if these are all length=2 or not, too.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s