Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
  2.  
  3. def symmetrical_sum(a):
  4. '''Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list
  5.  
  6. Example: symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)
  7.  
  8. Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the
  9. ith element at the end of the list'''
  10.  
  11. #extract duplicate value
  12. dupe = [x for n, x in enumerate(a) if x in a[:n]]
  13.  
  14. #if no duplicate values found, do the following:
  15. if dupe == []:
  16. middle = float(len(a))/2
  17. if middle % 2 != 0:
  18. sym = a[int(middle - .5):int(middle + .5)]
  19. ans = a[int(middle - .5)]
  20. tuple1 = (sym,ans)
  21. elif middle % 2 == 0:
  22. sym = a[int(middle - 1):int(middle + 1)]
  23. ans = sum(a[int(middle - 1):int(middle + 1)])//2
  24. tuple1 = (sym,ans)
  25. return tuple1
  26. else:
  27. d_to_i = int("".join(map(str, dupe))) #convert duplicate value to integer
  28. p1 = a.index(d_to_i) #get index of first duplicate
  29. p2 = a.index(d_to_i, p1+1) #get index of second duplicate
  30. sym = a[p1:p2+1] #[symmetrical-portion]
  31. ans = sum(sym) #sum-of-symmetrical-portion
  32. tuple2 = (sym, ans)
  33.  
  34. return tuple2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement