yifeの日記

Supercalifragilisticexpialidocious

Excel列名変換問題

問題1

Excel列名変換問題で第2回社内プログラミングコンテストを開催してみた(前編) - ITは芸術だの1問目。
かーなーり汚いけど、とりあえず。

# -*- coding: utf-8 -*-

#targetAlphabetに変換したい列名を入れる
targetAlphabet = raw_input()

#変換辞書をつくる
convDict = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26}


#targetAlphabetのうしろから一文字ずつスライスして、重みをかける
#重みは(26)^((現在のスライス回数)-1)
howManyTimeSliced = 0
totalSum = 0
while targetAlphabet != "":
    slicedChar = targetAlphabet[-1:]
    targetAlphabet = targetAlphabet[:-1]
    totalSum = totalSum + ((26)**(howManyTimeSliced)) * convDict[slicedChar]
    howManyTimeSliced = howManyTimeSliced + 1


print totalSum

問題2

数字から文字へ変換できるロジック追加&入ってきた文字が数字かアルファベットか判定。

# -*- coding: utf-8 -*-
import re


def CharToNum(target,convDict):

    #targetのうしろから一文字ずつスライスして、重みをかける
    #重みは(26)^((現在のスライス回数)-1)
    howManyTimeSliced = 0
    totalSum = 0
    while target != "":
        slicedChar = target[-1:]
        target = target[:-1]
        totalSum = totalSum + ((26)**(howManyTimeSliced)) * convDict[slicedChar]
        howManyTimeSliced = howManyTimeSliced + 1

    print totalSum


def NumToChar(target,convDict):

    target = int(target)
    totalChar = "" #答え用の変数

    while True:
        #targetを26で割っていく
        if target < 26: #targetが26より小さいならそこで終了
            totalChar = convDict[target] + totalChar
            break

        else:           #targetが26以上なら割ってみる
            m = target % 26
            totalChar = convDict[m] + totalChar #totalCharに割り算のあまりを追加して続ける
        
            target = target / 26    #targetに割った商を入れて上に戻る

    print totalChar


def main():

    #targetに変換したい列名を入れる
    target = raw_input()

    #変換辞書をつくる
    convDict = {"A":1,"B":2,"C":3,"D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26}
    #convDictのキーと値を逆にしたやつもつくっておく
    revConvDict = dict(zip(convDict.values(), convDict.keys()))

    #文字から数字化、数字から文字化のどちらのロジックに飛ばすか
    if re.match('[A-Z]',target):
        CharToNum(target,convDict)
    else:
        NumToChar(target,revConvDict)

if __name__ == "__main__":
    main()

メモ

割り算

割り算

って文字化け?

さらにメモ

上のプログラム、まだ解けてない!
26を入れるとバグるよ!