Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- PYTHON CODING CHALLENGE - SUBTRACT NEAREST NUMBERS
- write code to subtract 2 numbers nearest each other.
- print results as shown
- nums = [25, 73, 42, 20, 95, 9, 27, 16, 55, 3]
- output: 'Difference of closest pair is: 27-25=2'
- bonus: subtract all numbers in closest pairs
- output:['27-25=2','20-16=4','9-3=6','55-42=13','95-73=22']
- share your code in some useful way, that makes testing your code easy for others in group.
- '''
- nums = [25, 73, 42, 20, 95, 9, 27, 16, 55, 3]
- nums.sort()
- print(nums)
- output = []
- [ [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 ]
- print(output)
- output.sort(key=lambda x: x[1])
- print(output)
- print('Difference of closest pair is: ' + output[0][0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement