Advertisement
makispaiktis

Dynamic Programming - Καλαίσθητη εκτύπωση

May 15th, 2020 (edited)
1,176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""
  2.  
  3. # Initialization
  4. M = 20
  5. words = text.split(" ")
  6. print(words)
  7. # l = [len(word) for word in words]
  8. l = list()
  9. for i in range(len(words)):
  10.     l.append(len(words[i]))
  11. print(l)
  12.  
  13. # Problem
  14. n = len(l)
  15. extra = [[0 for _ in range(n)] for __ in range(n)]
  16. line_cost = [[0 for _ in range(n)] for __ in range(n)]
  17.  
  18. # Η extra βρίσκει πόσο εξω βγαινω απο το οριο των Μ χαρακτηρων
  19. # αν ψαξω απο την i στην j λεξη
  20. for i in range(n):
  21.     # Πρέπει να είναι πάντα l[i] < M, για να δουλέψει αυτό
  22.     extra[i][i] = l[i] - M
  23.     if extra[i][i] > 0:
  24.         line_cost[i][i] = float('inf')
  25.     else:
  26.         line_cost[i][i] = extra[i][i]**2
  27.     for j in range(i+1, n):
  28.         # extra[i, j] = sum(l[k]+1 for k in range(i, j+1)) - M
  29.         extra[i][j] = extra[i][j-1] + l[j] + 1
  30.         if extra[i][j] > 0:
  31.             line_cost[i][j] = float('inf')
  32.         else:
  33.             line_cost[i][j] = extra[i][j]**2     # Για να γίνει θετικό
  34.  
  35.  
  36.  
  37. # total_cost = [[None for _ in range(n)] for __ in range(n)]
  38. '''
  39. for i in range(n):
  40.    for j in range(i):
  41.        total_cost[i][j] = 0
  42.    total_cost[i][i] = line_cost[i][i]
  43. '''
  44.  
  45.  
  46.  
  47. # Ορίζω αλλιώς την μεταβλητή
  48. # total_cost[0][j] = cost to go up to word j = total_cost[j]
  49. # 1. Δέσμευση πίνακα
  50. total_cost = [None for _ in range(n)]
  51.  
  52. # 2. Αρχικές τιμές
  53. total_cost[0] = line_cost[0][0]
  54.  
  55. # 3. For-loops και σειρά προσπέλασης στοιχείων
  56. for j in range(1, n):
  57.     total_cost[j] = min(total_cost[k] + line_cost[k+1][j] for k in range(j))
  58.  
  59. print(total_cost[n-1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement