'Python Longest Arithmetic Sequence
I am trying to code solution to the following problem:
"Given a non-empty list items of positive integers in strictly ascending order, find and return the longest arithmetic progression whose values exist inside that sequence. Return the answer as a tuple (start, stride, n) for the three components that define an arithmetic progression. Whenever there exist several progressions of the same length, this function should return the one with the lowest start. If several progressions of equal length emanate from the lowest start, return the progression with the smallest stride."
Here is my code:
def arithmetic_progression(items):
dp = {}
tot = 0
count = 0
if len(items)==1:
dp[items[0]]=items[0]
return dp
for i in range(1, len(items)):
for j in range(i):
diff = items[i] - items[j]
if diff not in dp:
dp[diff] = []
for key in dp:
for i in items[count:]:
tot = key + i
if tot in items and tot not in dp[key]:
dp[key].append(tot)
count += 1
for i in range(1, len(dp[key])):
try:
if dp[key][i] - dp[key][i - 1] == key:
continue
else:
del (dp[key][i - 1])
except:
continue
count = 0
for key in dp:
try:
if (dp[key][0]-key) in items:
dp[key].insert(0,dp[key][0]-key)
except:
continue
if len(dp)==1:
return(items[0],0,len(dp))
else:
listing = {key: len(value) for (key, value) in dp.items()}
new_value = max(listing.values())
listing = {key: value for (key, value) in listing.items() if value == new_value}
min_val = min(listing, key=listing.get)
first_val = dp[min_val][0]
return(first_val, min_val, listing[min_val])
I've tested my code against a few tests but I can't get it to run for an input of range(1000000). How can I correct this?
Some of the items I used as a test and there expected result are below:
Test->[42] Expected Result->(42, 0, 1)
Test->[2, 4, 6, 7, 8, 12, 17] Expected Result-> (2, 2, 4)
Test->[1, 2, 36, 49, 50, 70, 75, 98, 104, 138, 146,
148, 172, 206, 221, 240, 274, 294, 367, 440]
Expected Result->(2, 34, 9)
Test->[2, 3, 7, 20, 25, 26, 28, 30, 32, 34, 36, 41,
53, 57, 73, 89, 94, 103, 105, 121, 137, 181,
186, 268, 278, 355, 370, 442, 462, 529, 554,
616, 646, 703]
Expected Result->(7, 87, 9)
Test->range(1000000) Expected Result-> (0, 1, 1000000)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
