-5

私の試験問題では、入力として 2 文字を取り、2 つの入力の間にあるアルファベットのすべての文字を (包括的に) 表示するよう求められます。また、ユーザーが入力した順序でこれを行う必要があります (したがって、GA は を生成しGFEDCBAませんABCDEFG)。このタスクにどのようにアプローチしますか?

4

2 に答える 2

2

私はこれが答える価値があるとは本当に思っていませんでしたが、@ martineauが彼のコメントで言ったように、コメントにそれほど多くのコードを入れるのは良い考えではありません...

>>> begin="A"
>>> end="G"
>>> print "%s" % list((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin))))) 
['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> begin="G"
>>> end="A"
>>> print "%s" % list((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin))))) 
['G', 'F', 'E', 'D', 'C', 'B', 'A']

わずかに関連する部分はchrordだけであり、 begin>end(ord(end)-ord(begin))/abs(ord(end)-ord(begin))の場合に-1を取得するための「トリック」は...

編集:@martineauが別のコメントで指摘したように、join使用して、さらに大きな(!)1つのライナーを作成し、(リストではなく)文字列を取得できます。

>>> begin="G"
>>> end="A"
>>> print "".join((chr(i) for i in range(ord(begin), ord(end) + 1 * (ord(end)-ord(begin))/abs(ord(end)-ord(begin)), (ord(end)-ord(begin))/abs(ord(end)-ord(begin)))))
GFEDCBA

...これはコードの些細なチャンクです... :D

于 2012-12-03T23:43:57.047 に答える
1
>>> import string
>>> def letterList (start, end):
        # add a character at the beginning so str.index won't return 0 for `A`
        a = ' ' + string.ascii_uppercase

        # if start > end, then start from the back
        direction = 1 if start < end else -1

        # Get the substring of the alphabet:
        # The `+ direction` makes sure that the end character is inclusive; we
        # always need to go one *further*, so when starting from the back, we
        # need to substract one. Here comes also the effect from the modified
        # alphabet. For `A` the normal alphabet would return `0` so we would
        # have `-1` making the range fail. So we add a blank character to make
        # sure that `A` yields `1-1=0` instead. As we use the indexes dynamically
        # it does not matter that we have changed the alphabet before.
        return a[a.index(start):a.index(end) + direction:direction]

>>> letterList('A', 'G')
'ABCDEFG'
>>> letterList('G', 'A')
'GFEDCBA'
>>> letterList('A', 'A')
'A'

このソリューションでは、あらゆる種類のアルファベットが許可されることに注意してください。a = ' ' + string.ascii_uppercase + string.ascii_lowercaseこのような結果を設定して取得できます。

>>> letterList('m', 'N')
'mlkjihgfedcbaZYXWVUTSRQPON'

Unicode を完全にサポートしているのに、ASCII を必要とする人がいるでしょうか?

>>> a = ' あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわを'
>>> letterList('し', 'ろ')
'しすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろ'
于 2012-12-03T21:52:25.080 に答える