《程序员编程艺术:面试和算法心得》http://taop.marchtea.com/

https://github.com/julycoding/The-Art-Of-Programming-By-July/tree/master/ebook/code/python

1.1 旋转字符串

   1:  def simpleShift(str, n):
   2:      tmpStr = str[n:] + str[:n]
   3:      return tmpStr
   4:   
   5:  def LeftShiftOne(str):
   6:      char = str[0]
   7:   
   8:      tmpStr = ''
   9:      for i in range(1, len(str)):
  10:          tmpStr += str[i]
  11:      tmpStr += char
  12:   
  13:      return tmpStr
  14:   
  15:  def LeftRotateString(str, n):
  16:      for i in range(n):
  17:          str = LeftShiftOne(str)
  18:      return str
  19:   
  20:  def ReverseString(str):
  21:      l = len(str)
  22:      for i in range(l/2):
  23:          char = str[i]
  24:          # reversed + right + to be reversed + left + reversed
  25:          str = str[:i ] + str[l - i - 1] + str[i + 1: l - i - 1] + char + str[l - i:]
  26:      return str
  27:   
  28:  def ReverseWords(str):
  29:      words = str.split()
  30:      l = len(words)
  31:      for i in range(l/2):
  32:          word = words[i]
  33:          words[i] = words[l - i - 1]
  34:          words[l - i - 1] = word
  35:   
  36:      str = ''
  37:      for word in words:
  38:          str += word + ' '
  39:      return str
  40:   
  41:  def main():
  42:      s = 'abcdefg'
  43:      n = 3
  44:   
  45:      print '1. Simple shift'
  46:      str = simpleShift(s, n)
  47:      print str
  48:   
  49:      print '2. Left rotate string'
  50:      str = LeftRotateString(s, n)
  51:      print str
  52:   
  53:      print '3. reverse string'
  54:      str = ReverseString(s[:n])
  55:      str = str + ReverseString(s[n:])
  56:      str = ReverseString(str)
  57:      print str
  58:   
  59:      print '4. reverse words'
  60:      s = 'I am a student.'
  61:      str = ReverseWords(s)
  62:      print str
  63:   
  64:  if __name__ == '__main__':
  65:      main()

反转字符串

str = 'abc'
 
def reverseString(str):
    return str[::-1]
 
print str