Python: Finding differences between elements of a list
>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])] # or use itertools.izip in py2k
[2, 3]
Get difference between two lists
To get elements which are in temp1
but not in temp2
:
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']
Beware that it is asymmetric :
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])
where you might expect/want it to equal set([1, 3])
. If you do want set([1, 3])
as your answer, you can use set([1, 2]).symmetric_difference(set([2, 3]))
.
Basic Python - finding difference between elements in a list - IndexError
acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98]
acct_increase = []
for index, value in enumerate(acct_balance):
if index == 0:
continue
acct_increase.append(acct_balance[index] - acct_balance[index - 1])
They say there are two hard things in computer science: naming conventions, cache misses, and off-by-one errors.
Instead of looking forward in the array (which is causing you to look over the end), always look backwards after skipping the 0th element. Also dont use while loops for looping over arrays in python, always use for-each loops. Do I get your homework credit :)
Python: Maximum difference between elements in a list
Your second solution still recalculates the max value of the prefix list on every iteration, which you don't need to do.
I think both of your solutions are correct, but the second one is still at least quadratic O(n^2) since you are performing linear-time operations (such as max()
) in your for loop. So to answer your question: No, it's likely not an optimal solution.
If I understood the problem correctly, it can be solved using dynamic programming. Consider the following code:
def maxDiff(a):
vmin = a[0]
dmax = 0
for i in range(len(a)):
if (a[i] < vmin):
vmin = a[i]
elif (a[i] - vmin > dmax):
dmax = a[i] - vmin
return dmax
Here we are simply keeping track of the smallest value encountered so far, and the largest difference, thus allowing us to iterate only once through the list without the need for storing any additional lists or doing any nested looping. The runtime of this should therefore be linear, O(n), in terms of comparison operations.
Difference between consecutive elements in list
You could utilize enumerate
, zip
and list comprehensions:
>>> a = [0, 4, 10, 100]
# basic enumerate without condition:
>>> [x - a[i - 1] for i, x in enumerate(a)][1:]
[4, 6, 90]
# enumerate with conditional inside the list comprehension:
>>> [x - a[i - 1] for i, x in enumerate(a) if i > 0]
[4, 6, 90]
# the zip version seems more concise and elegant:
>>> [t - s for s, t in zip(a, a[1:])]
[4, 6, 90]
Performance-wise, there seems to be not too much variance:
In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:]
1000000 loops, best of 3: 1.34 µs per loop
In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0]
1000000 loops, best of 3: 1.11 µs per loop
In [7]: %timeit [t - s for s, t in zip(a, a[1:])]
1000000 loops, best of 3: 1.1 µs per loop
Finding an element difference between two lists efficiently
You can do it in O(n log(n))
time using a sort. After sorting, you can do a linear traversal to find the first difference. Duplicate elements complicate binary search, which would otherwise be possible.
def ldiff(a, b):
a.sort()
b.sort()
for i, j in zip(a, b):
if i != j:
break
else:
i, j = a[-1], b[-1]
return i if len(a) > len(b) else j
If you object to the in-place modification preformed by the sort
method, use the sorted
function instead.
Find elements in list with difference of 1
You can step along the input list and start adding elements to an output list. Any time the difference is greater than 1, start a new output list. If the prior output is length 1, remove it:
out = []
current = []
prev = None
for i in lst:
if prev is None or i - prev != 1:
if len(current) > 1:
out.append(current)
current = []
current.append(i)
prev = i
if len(current) > 1:
out.append(current)
How to find difference of 2nd element and first element in the list python
[l[i] - l[i - 1] for i in range(1, len(l))]
Related Topics
How to Detach Matplotlib Plots So That the Computation Can Continue
Error Unicodedecodeerror: 'Utf-8' Codec Can't Decode Byte 0Xff in Position 0: Invalid Start Byte
Split Cell into Multiple Rows in Pandas Dataframe
How to Create a Copy of an Object in Python
What's the Simplest Way of Detecting Keyboard Input in a Script from the Terminal
How to Turn a Python Datetime into a String, with Readable Format Date
The 'Is' Operator Behaves Unexpectedly with Non-Cached Integers
How to Convert Surrogate Pairs to Normal String in Python
How to Print Original Variable's Name in Python After It Was Returned from a Function
Python Selenium Wait for Several Elements to Load
Generate Random Numbers Summing to a Predefined Value
How to Extract the N-Th Elements from a List of Tuples
Skip the Headers When Editing a CSV File Using Python
Python Append() VS. + Operator on Lists, Why Do These Give Different Results
Convert Datetime Object to a String of Date Only in Python
Random.Seed(): What Does It Do