Home > Back-end >  How to get number and incrementing letter in a certain format?
How to get number and incrementing letter in a certain format?

Time:10-28

I am writing a code that asks for the users input for the number of rows and columns. When given the integer values, the program will print out the number of the row and the letter that will increment will be next to it, just like seat numbers in a theatre or stadium. What I am trying to do is to use a for loop and a while loop to try to split up the rows and numbers.

Here is an example (row is 2 and column is 3):

1A 1B 1C
2A 2B 2C

However that did not work, what I have tried is to use a double for loop for the values but that didnt work. So I tried using a while loop to try and get the second row but didnt work. I can only get the first row to print out

Here is the code im working on:

num_rows = int(input("Enter number of rows: "))
num_cols = int(input("Enter number of columns: "))

rangerows = num_rows   1
rangecols = num_cols
colsnow = 0
rowsnow = 1


for i in range(1, num_rows):
while colsnow < rangecols:
print(f'{i}{chr(colsnow   65)}', end=' ')
colsnow  = 1

print()

CodePudding user response:

You could use a nested list comprehension to iterate the rows and columns, joining the results with a space on rows and newline on columns:

seats = '\n'.join(' '.join(f'{row 1}{chr(col ord("A"))}' for col in range(num_cols))
                  for row in range(num_rows))
print(seats)

Output:

1A 1B 1C
2A 2B 2C

CodePudding user response:

You can iterate through the rows and output the seat names with a generator expression that iterates through the columns, separated by space:

from string import ascii_uppercase

for row in range(1, num_rows   1):
    print(*(f'{row}{ascii_uppercase[col]}' for col in range(num_cols)), sep=' ')

Demo: https://replit.com/@blhsing/PolishedScratchyDebuggers

  • Related