patternpythonMinor
Finding the largest absolute difference in a list
Viewed 0 times
thelargestdifferenceabsolutefindinglist
Problem
I'm moving away from map, reduce and filter in favour of list comprehensions. I like list comps but I feel like this is getting on the unreadable side.
Is this the most idiomatic way of achieving this? Is it easy enough to read?
Is this the most idiomatic way of achieving this? Is it easy enough to read?
int_list = [-1,-3,5,7]
absolute_diffs = [max( [abs( int_2 ) - abs( int_1 ) for int_2 in int_list] ) for int_1 in int_list]
print max( absolute_diffs )Solution
A more idiomatic and readable solution would be to use
However, that is O(n2). A smarter O(n) solution would be to subtract the minimum absolute value from the maximum absolute value.
itertools.combinations(list, 2) to take all pairs.max(abs(a) - abs(b) for a, b in itertools.combinations(int_list, 2))However, that is O(n2). A smarter O(n) solution would be to subtract the minimum absolute value from the maximum absolute value.
absolutes = [abs(elem) for elem in int_list]
print max(absolutes) - min(absolutes)Code Snippets
max(abs(a) - abs(b) for a, b in itertools.combinations(int_list, 2))absolutes = [abs(elem) for elem in int_list]
print max(absolutes) - min(absolutes)Context
StackExchange Code Review Q#131764, answer score: 6
Revisions (0)
No revisions yet.