[英]HOW TO ITERATE IN THIS QUESTION.ACTUALLY I FOUND THAT FROM A to Z WE WOULD RECIEVE INDEX 1-26 AND FROM AA TO ZZ IT IS AS 26+26^2.BUT HOW TO PROCEED?
In spreadsheets, columns are labeled as follows:在电子表格中,列的标签如下:
Label Number
A 1
... ...
Z 26
AA 27
... ...
AZ 52
BA 53
... ...
ZZ 702
AAA 703
... ...
AAZ 728
ABA 729
A is the first column, B is the second column, Z is the 26th column, and so on. A 是第一列,B 是第二列,Z 是第 26 列,依此类推。 The three dots represent the missing labels and their column numbers.
三个点代表缺失的标签及其列号。 Using the table given above, deduce the mapping between column labels and their corresponding numbers.
使用上面给出的表格,推断列标签与其对应编号之间的映射。 Accept the column label as input and print the corresponding column number as output.
接受列标签作为输入并打印相应的列号作为输出。
I started as:我开始是:
n=input()
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if len(n)==1:
print(alpha.index(n.upper())+1)
elif len(n)==2
but I know it won't work.但我知道这行不通。
First, we want to write a function which gives the position of a letter (which you already did more or less).首先,我们想写一个函数来给出一个字母的位置(你已经或多或少做了)。
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def position(letter):
return alpha.index(letter.upper())+1
You then have 2 cases:那么你有两种情况:
This gives us the following program:这给了我们以下程序:
def column_number(label):
if len(label) == 1:
return position(label)
elif len(label) == 2:
return 26*position(label[0]) + position(label[1])
else:
print("incorrect label format")
Since we have to continue as many times as the input requires, it's ideal to make use of recursion:由于我们必须根据输入的需要继续多次,因此使用递归是理想的:
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# retrieve position of a letter in the alphabet set
def position(letter):
pos = alpha.index(letter) + 1
return pos
# function to recursively find the column number
def column_number(label, n):
if n==1:
return position(label)
else:
return ((26**(n-1)) * position(label[0])) + column_number(label[1:], n-1)
# main code
label = input().upper()
n = len(label)
col_n = column_number(label, n)
print(col_n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.