fork(3) download
  1. # declare string s to test
  2. s = 'ghaaawxyzijbbbklccc'
  3. # s = 'edxeducation'
  4.  
  5. # declare 26 x 26 matrix m to hold letter counts
  6. m = [[0 for j in range(0,26+1)] for i in range(0,26+1)]
  7.  
  8. # declare dictionary a2n to convert alphabet to number so a --> 1, b --> 2, etc.
  9. a2n = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, \
  10. 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, \
  11. 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20, \
  12. 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26}
  13.  
  14. # declare list n2a to convert number to alphabet
  15. n2a = [0,'a','b','c','d','e','f','g','h','i','j','k','l','m'\
  16. ,'n','o','p','q','r','s','t','u','v','w','x','y','z']
  17.  
  18. # step functions takes the next letter and adds it to m
  19. def step(a):
  20. # look up number from letter
  21. n = a2n[a]
  22.  
  23. # remember the position and count of the longest string so far
  24. long_pos = 0
  25. long_ct = 0
  26. for i in range(1, n + 1):
  27. if m[i][0] > long_ct:
  28. long_pos = i
  29. long_ct = m[i][0]
  30.  
  31. # if the longest is not the same as n
  32. if n != long_pos:
  33. # copy longest to n
  34. for i in range(0,len(m[n])):
  35. m[n][i] = m[long_pos][i]
  36.  
  37. # and add letter
  38. m[n][0] += 1
  39. m[n][n] += 1
  40.  
  41. # else just add letter
  42. else:
  43. m[n][0] += 1
  44. m[n][n] += 1
  45.  
  46. # return the last string you modified
  47. return m[n]
  48.  
  49. # longest function returns the longest string
  50. def longest():
  51. # remember position and count of the longest string
  52. long_pos = 0
  53. long_ct = 0
  54. for i in range(1,len(m)):
  55. if m[i][0] >= long_ct:
  56. long_pos = i
  57. long_ct = m[i][0]
  58.  
  59. # return longest string
  60. out = ''
  61. # iterate through letter counter for longest position
  62. for i in range(1,len(m[long_pos])):
  63. # and add letter that number of times
  64. for j in range(0,m[long_pos][i]):
  65. out += n2a[i]
  66.  
  67. return out
  68.  
  69. # iterate through string
  70. for i in range(0,len(s)):
  71. step(s[i])
  72.  
  73. # print longest string
  74. print longest()
  75.  
  76.  
Success #stdin #stdout 0.01s 7692KB
stdin
Standard input is empty
stdout
aaabbbccc