-5

我的考试问题要求我将两个字母作为输入,并在两个输入之间(包括)显示字母表中的所有字母。它还需要按照用户输入它们的顺序执行此操作(因此 GA 生成GFEDCBAnot 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获取一个字符串(而不是列表) 。

>>> 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 回答