Long story short, I'm taking Intro Python and this is the problem in question:

Given num_rows and num_cols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat.

Sample output with inputs: 2 31A 1B 1C 2A 2B 2C

num_rows = int(input())num_cols = int(input())# Note 1: You will need to declare more variables# Note 2: Place end=' ' at the end of your print statement to separate seats by spaces'''Insert your solution here'''print()

pythonzybooksnestedloop

Someone else had already posted the question and I tweaked the code from that post to get the following with soft-coded variables to run with user input and verified it works:

num_rows = int(input())num_cols = int(input())# Note 1: You will need to declare more variables# Note 2: Place end=' ' at the end of your print statement to separate seats by spacesrow = 1while row <= num_rows:col = 'A'while col < chr(ord('A') + num_cols):print('{}{}'.format(row, col), end=' ')col = chr(ord(col) + 1)row += 1print()

My question is WHAT is going with the column/string in this example? The rows are easy, it's a simple integer initialized with 1, easy to understand how it behaves and why '<=' is used for the outer while loop. The columns, in other words the string-to-ASCII-to-string conversion kind of breaks my brain. Can anyone break this down Barney style for me? Specifically, why does only '<' work?

1

Best Answer


The uppercase letters (A to Z) have consecutive ASCII values (65 to 90). For each row, the question requires printing out the first num_cols uppercase characters of the alphabet concatenated with the row number.

The consecutive range of integers starting from a number n of length l ends at n + l - 1. (You can try a few examples to convince yourself.)

ord('A') returns the Unicode code point of the character 'A', which is 65. After adding num_cols to it, we get the code point of the character right after the range of characters. (<= could be used if 1 was subtracted to get the actual endpoint of the range.) chr converts the code point to the actual character. < will be True until the col character reaches the character chr(ord('A') + num_cols), which is one past the end of the range.

Along the same vein, col = chr(ord(col) + 1) advances col to the character with a code point that has a value one greater than the code point of the current col character. This is just like incrementing an index variable when iterating over a list.