pythonstringoctal

octal to string - trouble


I just cannot seem to understand the solution to this problem given in an online course. I found the actual code that solves it, but I still don't understand it. Could anyone explain to me a bit more in detail why this does what it does? I would be extremely grateful.

The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or - when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: "rw-r-----" 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: "rwxr-xr-x" Fill in the blanks to make the code convert a permission in octal format into a string format. I am mostly confused about the line with the for loop - I just simply don't understand it.

Soultion I found on the internet (which works correctly):

def octal_to_string(octal):
 result = ""
 value_letters = [(4,"r"),(2,"w"),(1,"x")]
 # Iterate over each of the digits in octal
 for i in [int(n) for n in str(octal)]:
    # Check for each of the permissions values
    for value, letter in value_letters:
        if i >= value:
            result += letter
            i -= value
        else:
            result += '-'
 return result
    
print(octal_to_string(755)) # Should be rwxr-xr-x
print(octal_to_string(644)) # Should be rw-r--r--
print(octal_to_string(750)) # Should be rwxr-x---
print(octal_to_string(600)) # Should be rw-------

Solution

  • As I'm sure you've realized, each octal digit(oit? octit?) corresponds to a set of permissions given by the sum of the individual permissions.

    0 = ---
    1 = --x
    2 = -w-
    3 = -wx
    4 = r--
    5 = r-x
    6 = rw-
    7 = rwx
    

    We can derive this string by subtracting the value corresponding to each permission from our octal digit.

    (6, '') -> (2, 'r') -> (0, 'rw') -> (0, 'rw-')

    As for the looping line, since the octal variable is a 3-(octal)digit integer, we first convert it to a string, separate each character to get the individual octal digits, then convert them back to integers so we can process them. Instead of writing a separate statement for each of the operations, we use a list comprehension to generate the list of octal digits over which we will loop.