What is the purpose of comparing indexes in Python?

I came across the following:

r = random.randint(1,6) C = "o " s = '-----\n|' + C[r<1] + ' ' + C[r<3] + '|\n|' + C[r<5] print(s + C[r&1] + s[::-1]) 

When executed in IDLE, this yields an ASCII matrix with a random value.

How does this work, or rather, what do the comparison characters ( < and & ) inside the indexes do?

+5
source share
1 answer

Someone here is playing codes and using hacking tricks to minimize the amount of code used.

  • < - regular comparison operator; it returns True or False based on two operands. The Python bool type is a subclass of int and True is 1 , False is 0 when interpreted as integers. As such, C[r<1] either selects C[0] or C[1] .

  • & is a bit-wise operator, not a comparison operator; & 1 masks the number to the last bit, effectively testing whether the number is odd or even (the last bit is set or not). Therefore, if r is odd, C[1] , otherwise C[0] is.

Abort this:

  • C is a string with the characters o and a space
  • C[r<1] chooses either o or a space based on the fact that it is less than 1. It never ( random.randint(1,6) provides this), so there is always o . This is apparently a bug or oversight in the code.
  • C[r<3] selects a space for 1 and 2, and o otherwise.
  • C[r<5] selects o for 5 or 6, a space otherwise.
  • C[r&1] selects o for 2, 4, and 6, a space otherwise.

Altogether, it prints r plus one as a stamp. r = 1 gives two pips, and r = 6 gives you seven points, perhaps how stylized?

To fix the code, this requires an increment of all r tests and inversion of the odd / even test:

 s = '-----\n|' + C[r<2] + ' ' + C[r<4] + '|\n|' + C[r<6] print(s + C[1-r&1] + s[::-1]) 

Demonstration (completion of a string in a function):

 >>> import random >>> def dice(r, C='o '): ... s = '-----\n|' + C[r<2] + ' ' + C[r<4] + '|\n|' + C[r<6] ... print(s + C[1-r&1] + s[::-1]) ... >>> for i in range(1, 7): ... dice(i) ... ----- | | | o | | | ----- ----- |o | | | | o| ----- ----- |o | | o | | o| ----- ----- |oo| | | |oo| ----- ----- |oo| | o | |oo| ----- ----- |oo| |oo| |oo| ----- 
+7
source

Source: https://habr.com/ru/post/1245160/


All Articles