Advertisement
nher1625

arbitrary length unpacking with throwaway variables

Mar 25th, 2015
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. __author__ = 'Work'
  2.  
  3. '''
  4. You need to unpack N-elements from an iterable, but the iterable may be longer than N elements, causing a
  5. "too many values to unpack" exception.
  6. '''
  7. # Python "star expressions" is an option to address this problem.
  8. '''
  9. Ex: You run a course and decide at the end of the semester that you're going to drop the first and last hw grades,
  10. and only average the rest of them. If there are only 4 assignments, maybe you simply unpack all 4, but what if there
  11. where 24? A star expression makes this easy:
  12. '''
  13. import statistics
  14.  
  15. def drop_first_last(grades):
  16.     first, *middle, last = grades
  17.     return statistics.mean(middle)
  18.  
  19. def drop_lowest_double_highest(grades):
  20.     grades.sort()
  21.     first, *middle, last = grades
  22.     middle.append(2 * last)
  23.     return statistics.mean(middle)
  24.  
  25. #x = drop_first_last([3,3,3,1])
  26. # x = drop_lowest_double_highest([3,4,6,2,3,1,8,3,2,5,6])
  27. #
  28. # y = [3,4,6,2,3,1,8,3,2,5,6]
  29. # print('Length of list y: ',len(y))
  30. # y.sort()
  31. # print('Sorted list y: ',y)
  32. # y.remove(1) # Drop lowest
  33. # print('List y lowest popped: ', y)
  34. #
  35. # print('Mean: ', sum(y)/len(y))
  36. #
  37. # y[-1] *= 2
  38. # print('Average with last grade doubled: ', sum(y)/len(y))
  39. # print('X: ', x)
  40.  
  41. '''
  42. Use Case #2:
  43. Suppose you have user records that consist of a name and email address, followed by an arbitrary number of phone numbers.
  44. You could unpack the records like this:
  45. '''
  46.  
  47. record = ('Dave', '[email protected]', '773-555-1212', '847-555-1212')
  48. name, email, *phone_numbers = record
  49.  
  50. print(name)
  51. print(phone_numbers)
  52. # Worth noting that phone_numbers variable will always be a list no matter how many variables are unpacked.
  53.  
  54. '''
  55. Starred variable can also be the first one in the list.
  56. Ex: You have a sequence of values representing your company's sales figures for the last eight quarters.
  57. If you want to see how the most recent quarter stacks up to the average of the first seven, try this:
  58. '''
  59. # Psuedocode
  60. # *trailing_qtrs, current_qtr, = sales_record
  61. # trailing_avg = sum(trailing_qtrs)/ len(trailing_qtrs)
  62. # return avg_comparison(trailing_avg, current_qtr)
  63.  
  64. *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
  65. print(trailing)
  66. print(current)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement