Search code examples
pythonpython-3.xstring-formatting

python join,map and lambda methods


I am quite new to python. Can someone explain this line

exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

What does s[x::{0}] and range({0})) mean ?

in below piece of code in detail?

This code is a solution for below hackerrank question : https://www.hackerrank.com/challenges/encryption/problem

#!/bin/python3

import sys
from math import ceil, floor, sqrt


def encryption(s):
    exec("print(' '.join(map(lambda x: s[x::{0}], range({0}))))".format(ceil(sqrt(len(s)))))

if __name__ == "__main__":
    s = input().strip()
    result = encryption(s)

Solution

  • This is a simplified version of your code, which you should be able to follow:

    from math import ceil, sqrt
    
    s = 'hello'
    
    y = ceil(sqrt(len(s)))
    # 3
    
    res = ' '.join(map(lambda x: s[x::y], range(y)))
    # 'hl eo l'
    

    Essential points

    • y is the rounded-up square root of the length of s, in this case sqrt(5) is rounded up to 3.
    • lambda is an anonymous function which maps each value in range(y), i.e. 0, 1, 2 is mapped to s[x::y], i.e. return every yth element of sequence beginning from index x. See also Understanding Python's slice notation. x is arbitrary notation for a member of range(y).
    • Join all resulting values with a space to form a single string.
    • In your original code {0} and str.format are used to incorporate y in your string in one line. In this case, I consider it convoluted and bad practice.