From a28ad3f759ba4b69e58e65db60eb26f0fd9756cc Mon Sep 17 00:00:00 2001 From: Luke Banicevic <60857954+banaboi@users.noreply.github.com> Date: Tue, 24 May 2022 11:18:50 +1000 Subject: [PATCH] Add Microsoft Excel Column Title to Column Number Conversion (#4849) * Added excel column title to number algorithm as part of conversions * Renamed file to better reflect algorithm function * Removed duplicate file * Update excel_title_to_column.py * Update excel_title_to_column.py Co-authored-by: John Law --- conversions/excel_title_to_column.py | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 conversions/excel_title_to_column.py diff --git a/conversions/excel_title_to_column.py b/conversions/excel_title_to_column.py new file mode 100644 index 000000000..d77031ec2 --- /dev/null +++ b/conversions/excel_title_to_column.py @@ -0,0 +1,33 @@ +def excel_title_to_column(column_title: str) -> int: + """ + Given a string column_title that represents + the column title in an Excel sheet, return + its corresponding column number. + + >>> excel_title_to_column("A") + 1 + >>> excel_title_to_column("B") + 2 + >>> excel_title_to_column("AB") + 28 + >>> excel_title_to_column("Z") + 26 + """ + assert column_title.isupper() + answer = 0 + index = len(column_title) - 1 + power = 0 + + while index >= 0: + value = (ord(column_title[index]) - 64) * pow(26, power) + answer += value + power += 1 + index -= 1 + + return answer + + +if __name__ == "__main__": + from doctest import testmod + + testmod()