Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.1 KiB

  1. def extraSpace(S, M, i, j):
  2. """
  3. Computes the number of extra characters at the end of
  4. the line.
  5. Between each word there is only once space.
  6. :param S: List of words
  7. :param M: Max length of line
  8. :param i: start word index
  9. :param j: end word index
  10. """
  11. extraSpaces = M - j + i
  12. for x in range(i, j + 1):
  13. extraSpaces -= len(S[x])
  14. return extraSpaces
  15. def badnessLine(S, M, i, j):
  16. """
  17. Computes Line badness. This is the number of
  18. extra spaces or infinity if the length exceeds M
  19. :param S: List of words
  20. :param M: Max length of line
  21. :param i: start word index
  22. :param j: end word index
  23. """
  24. es = extraSpace(S, M, i, j)
  25. if es < 0:
  26. return float("infinity")
  27. return es
  28. def minBad(S, M, i):
  29. """
  30. Computes the badness of a paragraph as the
  31. badness of the worst line in the paragraph not
  32. including the last line.
  33. *this is recursive
  34. :param S: List of words
  35. :param M: Max length of line
  36. :param i: start word index
  37. """
  38. if len(S) == 0:
  39. return 0
  40. # Calculate the current line's badness
  41. curBad = 0
  42. k = i
  43. while curBad > badnessLine(S, M, i, k):
  44. curBad = badnessLine(S, M, i, k)
  45. k = k + 1
  46. return max(curBad, badnessLine(S, M, k))
  47. def minBadDynamic(S, M):
  48. """
  49. Write a procedure minBadDynamic that implements
  50. the function mb' using dynamic program-
  51. ming. It should take only two parameters: S and M
  52. :param S: List of words
  53. :param M: Max length of line
  54. """
  55. pass
  56. def minBadDynamicChoice(S, M):
  57. """
  58. Write a procedure minBadDynamicChoice that implements
  59. the function mb 0 using dynamic
  60. programming. In addition to returning mb(S, M ), it
  61. should also return the choices made
  62. :param S: List of words
  63. :param M: Max length of line
  64. """
  65. pass
  66. def printParagraph(S, M):
  67. """
  68. which takes two parameters: S and M that displays the words in S on
  69. the screen using the choices of minBadDynamicChoice.
  70. What is the asymptotic running time of your
  71. algorithm?
  72. :param S: List of words
  73. :param M: Max length of line
  74. """
  75. pass