take a char and print out from char to 'a'

2019-03-05 21:56发布

问题:

this code should take a char as an argument and print out that char in alphabetically order to 'a' and reverse to char.

>>> characters('d')
d c b a b c d

this is what Ii wrote so far but it is not the correct output

def characters(char):
    numb=ord(char)
    while numb>ord('a'):
>>      print chr(numb),
        numb=numb-1

    return


>>> characters('h')
g f e d c b a

回答1:

def characters(c):
  print ' '.join(map(chr, range(ord(c), ord('a'), -1) + range(ord('a'), ord(c)+1)))

>>> characters('d')
d c b a b c d

or

def characters(c):
  for n in xrange(ord(c), ord('a'), -1):
    print chr(n),
  for n in xrange(ord('a'), ord(c)+1):
   print chr(n),
  print


回答2:

Well, you're halfway there as it stands. Now you just have to figure out how to take numb back to your letter.

In order to make it go backwards in the alphabet, you're using numb=numb-1. So in order to make it go forward in the alphabet, what would be the opposite of that? Then you could put that in another loop afterwards.