Advertisement
kingbode

Untitled

Oct 8th, 2022
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. '''
  2. PYTHON CODING CHALLENGE - SUBTRACT NEAREST NUMBERS
  3. write code to subtract 2 numbers nearest each other.
  4. print results as shown
  5. nums = [25, 73, 42, 20, 95, 9, 27, 16, 55, 3]
  6. output: 'Difference of closest pair is: 27-25=2'
  7. bonus: subtract all numbers in closest pairs
  8. output:['27-25=2','20-16=4','9-3=6','55-42=13','95-73=22']
  9. share your code in some useful way, that makes testing your code easy for others in group.
  10. '''
  11.  
  12.  
  13. nums = [25, 73, 42, 20, 95, 9, 27, 16, 55, 3]
  14. nums.sort()
  15. print(nums)
  16.  
  17. output = []
  18.  
  19. [ [output.append( (str(x) + '-' + str(y) + '=' + str(x - y), x-y) )for x in nums if x > y and y==nums[nums.index(x)-1] ] for y in nums ]
  20. print(output)
  21.  
  22. output.sort(key=lambda x: x[1])
  23. print(output)
  24. print('Difference of closest pair is: ' + output[0][0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement