Advent Calendar - December 23, 2022

Friday, Dec 23, 2022| Tags: Python

Advent Calendar 2022

|   Day 22   |   Day 23   |   Day 24   |


The gift is presented by E. Alvarez. Today he is talking about his solution to “The Weekly Challenge - 191”. This is re-produced for Advent Calendar 2022 from the original post by him.



Lambdas & Printf


Task I: Binary String


Ok, another great week and I was glad that it did not require too much effort on my part, as I’ve started participating in AoC, AoCyber, and also doing Gabor Szabo’s 2022 December CI Challenge. Thus without further ado, let’s get into the code.


#!/usr/bin/env python3

def bit_str(n):
    limit = 1 << n
    for i in range(limit):
        value = i
        width = f'0{n}'
        print(f'{value:{width}b}')


if __name__ == "__main__":
    bit_str(2)
    print('\n')
    bit_str(3)

It was a very straightforward implementation using Python & Go’s mini string formatting language.


Task II: Odd String



For this task, it was simply a matter of giving Python’s builtin sort() function, an anonymous comparison function, in which we compare the difference of each of the following ordinal values of the individual chars in words list.


#!/usr/bin/env python3

def odd_str(_list):
    def diff(x): return [ord(x[i]) - ord(x[i - 1]) for i in range(1, len(x))]
    _list.sort(key=diff)

    fst = _list[0]
    snd = _list[1]
    last = _list[-1]

    return fst if diff(fst) != diff(snd) else last


def main():
    words = ["adc", "wzy", "abc"]
    print(odd_str(words))


if __name__ == "__main__":
    exit(main())

Happy hacking!


P.S: I originally had a lambda function for diff() a la:


diff = lambda x: [ord(x[i]) = ord(x[i - 1]) for i in range(1, len(x))]

However, my linter was screaming at me for not following some weird PEP-8 rule.



If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.

|   Advent Calendar 2022   |

SO WHAT DO YOU THINK ?

If you have any suggestions or ideas then please do share with us.

Contact with me