Advertisement
SimeonTs

SUPyF Lists - Extra 03. Sum Adjacent Equal Numbers

Jun 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. Lists
  3. Проверка: https://judge.softuni.bg/Contests/Practice/Index/423#2
  4.  
  5. 03. Sum Adjacent Equal Numbers
  6.  
  7. Условие:
  8. Write a program to sum all adjacent equal numbers in a list of decimal numbers, starting from left to right.
  9. - After two numbers are summed, the obtained result could be equal to some of its neighbors and should be
  10. summed as well (see the examples below).
  11. - Always sum the leftmost two equal neighbors (if several couples of equal neighbors are available).
  12. Examples
  13. Input           Output      Explanation
  14. 3 3 6 1         12 1        3 3 6 1  6 6 1  12 1
  15. 8 2 2 4 8 16    16 8 16     8 2 2 4 8 16      8 4 4 8 16  8 8 8 16  16 8 16
  16. 5 4 2 1 1 4     5 8 4       5 4 2 1 1 4  5 4 2 2 4  5 4 4 4  5 8 4
  17.  
  18. Hints
  19. 1.  Read the input and parse it to list of numbers.
  20. 2.  Find the leftmost two adjacent equal cells.
  21. 3.  Replace them with their sum.
  22. 4.  Repeat (1) and (2) until no two equal adjacent cells survive.
  23. 5.  Print the processed list of numbers.
  24. """
  25.  
  26. nums = [float(item) for item in input().split(" ")]
  27.  
  28. i = 0
  29. while i != len(nums):
  30.     if len(nums) == 1:
  31.         break
  32.     f = nums[i - 1]
  33.     s = nums[i]
  34.     if f == s:
  35.         nums[i] = f + s
  36.         nums.remove(nums[i - 1])
  37.         i = 0
  38.     i += 1
  39.  
  40. if len(nums) <= 1:
  41.     print(nums[0])
  42. else:
  43.     print(" ".join(map(str, nums)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement