pythonlistsum

What is [1:] and sum(b'%a'%s)%34 in Python?


Consider:

for s in[*open(i:=0)][1:]:i+=1;print(f'Case #{i}:',sum(b'%a'%s)%34)

I can't understand the above code... I searched and now I know that open(0) is the same as sys.stdin and := is the walrus operator, but what are [1:] and sum(b'%a'%s)%34, and how does this code work?


Solution

  • Here's a more readable version:

    for s in [*open(i:=0)][1:]:
        i += 1
        print(f'Case #{i}:', sum(b'%a' % s) % 34)
    

    As you said, open(0) opens stdin to read from.
    [*open(0)] unpacks all stdin input into a list, with one line per entry.
    i:=0 also initialises the variable i to 0 at the same time; this is just a code golfing shorthand.
    [1:] slices that list to omit the first line.

    The %a formatter converts lines using ascii:

    [..] return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that returned by repr() in Python 2.

    >>> '%a' % 'foobar'
    "'foobar'"
    

    Using a b'' string makes the result bytes.
    bytes are really just sequences of integers (byte values).
    sum sums that sequence of integers.
    % 34 mod-34s the result:

    >>> sum(b'%a' % 'foobar')
    711
    >>> sum(b'%a' % 'foobar') % 34
    31
    

    So, this prints the 34-modded sum of the byte values of each line of input (except the first). Whatever that's good for…