Question

Arithmetic progression def arithmetic_progression(elems): An arithmetic progression is a numerical sequence so that the stride between...

Arithmetic progression

def arithmetic_progression(elems):

An arithmetic progression is a numerical sequence so that the stride between each two consecutive elements is constant throughout the sequence. For example, [4, 8, 12, 16, 20] is an arithmetic progression of length 5, starting from the value 4 with a stride of 4.

Given a list of elems guaranteed to consist of positive integers listed in strictly ascending order, find and return the longest arithmetic progression whose all values exist somewhere in that sequence. Return the answer as a tuple (start, stride, n) of the values that define the progression. To ensure that the answer is unique for automated testing, if there exist several progressions of the same length, return the one with the smallest start. If there exist several progressions of equal length from the same start, return the progression with the smallest stride.

elems

Expected result

[42]

(42, 0, 1)

[2, 4, 6, 7, 8, 12, 17]

(2, 2, 4)

[1, 2, 36, 49, 50, 70, 75, 98, 104, 138, 146, 148, 172, 206, 221, 240, 274, 294, 367, 440]

(2, 34, 9)

[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]

(7, 87, 9)

list(range(1000000))

(0, 1, 1000000)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Approach used:

The longest length of an arithmetic progression can be solved using dynamic programming. Before moving into solving it use dynamic programming. We need to remember following end cases and points:

  • if length of input is 1, then answer is simply (a1, 0, 1)
  • if length of input is 2, then answer is simply (a1, a2-a1, 2)
  • Any 2 numbers in the input can form an AP of length 2. So if length >= 2, max AP length is going to be greater then or equal to 2.
  • We are going to solve it using bottom-up approach moving right to left

In order to solve it, we are going to make a table dp[n][n], where n = input length. We initialize all the values in table with 0. The value stored at dp[i][j] will indicate the length of the longest AP with numbers at position i and j as first two elements of AP. Hence, dp[i][n-1] is always going to be 2.

To fill the remaining table, we do the folloing:

  • Iterate j from n-2 to 1
  • For each index j, find index i (i<j) and index k (k>j) such that ai, aj, ak are in AP.
  • when we find them, we update our table as dp[i][j] = dp[j][k]+1

Now some may ask why dp[i][j] = dp[j][k]+1? Why not update dp[j][k] or dp[i][k]? It is because the value stored at dp[i][j] will indicate the length of the longest AP with numbers at position i and j as first two elements of AP.

----------------------------------------------------

Below is the python code:

Screenshot:def longestAP(set): I. This function accepts a list and returns a tuple (start, stride, n) n = len(set) if n==1: #end case whfor j in range(n 2, 0, -1): *j iterates over values n-2 to 1 #we try to find i, j and k such that set[i], set[i] and set[k] o

Code as text:

def longestAP(set):
'''
This function accepts a list and
returns a tuple (start, stride, n)
'''
n = len(set)
  
if n==1: #end case when n=1
return (set[0], 0, 1)
  
if n==2: #end case when n==2
return (set[0],set[1]-set[0],2)
  
#when n>2 :
dp = [[0 for x in range(n)] for y in range(n)] #create nxn table
  
for i in range(n-1):
dp[i][n - 1] = 2 #numbers at i and n-1 will always form an AP of length 2.
  

for j in range(n - 2, 0, -1): #j iterates over values n-2 to 1
#we try to find i, j and k such that set[i], set[j] and set[k] are in AP
i = j - 1
k = j + 1
while(i >= 0 and k <= n - 1):
if (set[i] + set[k] < 2 * set[j]):
k += 1
elif (set[i] + set[k] > 2 * set[j]):
dp[i][j] = 2 #set dp[i][j] = 2 because table filling is done using i and j in bottom up manner
i -= 1
else:
#i, j and k are found
dp[i][j] = dp[j][k] + 1 #update result in dp table
#j can be part of many APs so decrease i and increase k
i -= 1
k += 1
#if loop ends because of k>n-1 fill table dp[i][j] for remaining i
while (i >= 0):
dp[i][j] = 2 #i and j will form AP of length 2
i -= 1
  
lap = 0
maxi = 0
maxj = 0
  
for i in range(n):
for j in range(n):
if dp[i][j] > lap: #find max AP length
lap = dp[i][j]
maxi = i
maxj = j
  
return (set[maxi],set[maxj]-set[maxi],lap)

-------------------------------------------------

Output:print(longestAP([42])) (42, 0, 1) print(longestAP([2, 4, 6, 7, 8, 12, 17])) (2, 2, 4) print(longestAP([1, 2, 36, 49, 50, 70,

=========== END ============

The last test list(range(1000000)) was unable to run on my computer

PLEASE DON'T FORGET TO LIKE.. ..IT IS OF MUCH IMPORTANCE TO ME*****†****""""""

Add a comment
Know the answer?
Add Answer to:
Arithmetic progression def arithmetic_progression(elems): An arithmetic progression is a numerical sequence so that the stride between...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C# 1. Given two lengths between 0 and 9, create an rowLength by colLength matrix with...

    C# 1. Given two lengths between 0 and 9, create an rowLength by colLength matrix with each element representing its column and row value, starting from 1. So the element at the first column and the first row will be 11. If either length is out of the range, simply return a null. For exmaple, if colLength = 5 and rowLength = 4, you will see: 11 12 13 14 15 21 22 23 24 25 31 32 33 34...

  • GetNumber and Getarray parts are working but I need help figuring out part 7_4 and 7_5...

    GetNumber and Getarray parts are working but I need help figuring out part 7_4 and 7_5 (I do not need Printarray). My professor provided the sections in which we need to fill in with code to make them run and pass the test files provides by the professor in Visual Studio. GetNumber Reuse the GetNumber0 method that you have been refining in the previous two labs Get Array Using your GetNumber0 method, create a method that will read in an...

  • Questions 1. How to create a comment in python? 2. The way to obtain user input...

    Questions 1. How to create a comment in python? 2. The way to obtain user input from command line 3. List standard mathematical operators in python and explain them 4. List comparison operators in python 5. Explain while loop. Give example 6. Explain for loop. Give example 7. How to create infinite loop? And how to stop it? 8. Explain a built-in function ‘range’ for ‘for’ loop 9. Explain break statement 10. Explain continue statement 11. Explain pass statement 12....

  • In C++ Programming: Using a single for loop, output the even numbers between 2 and 1004...

    In C++ Programming: Using a single for loop, output the even numbers between 2 and 1004 (inclusive) that iterates (loops) exactly 502 times. The outputted numbers be aligned in a table with 10 numbers per row. Each column in the table should be 5 characters wide. Do not nest a loop inside of another loop. Hint: First create and test the code that output the numbers all on one line (the command line will automatically wrap the output to new...

  • This is the sequence 1,3,6,10,15 the pattern is addin 1 more than last time but what is the name for this pattern These are called the triangular numbers The sequence is 1 3=1+2 6=1+2+3 10=1+2+3+4 15=1+2+3+4+5 You can also observe this pattern

    This is the sequence 1,3,6,10,15 the pattern is addin 1 more than last time but what is the name for this patternThese are called the triangular numbers The sequence is 1 3=1+2 6=1+2+3 10=1+2+3+4 15=1+2+3+4+5 You can also observe this pattern x _________ x xx __________ x xx xxx __________ x xx xxx xxxx to see why they're called triangular numbers. I think the Pythagoreans (around 700 B.C.E.) were the ones who gave them this name. I do know the...

  • Hi it's python I imported a data which are so many words in txt and I arranged and reshaped with ...

    Hi it's python I imported a data which are so many words in txt and I arranged and reshaped with alphabetically both rows and columns I was successful with these steps but I am stuck with next step below is my code and screenshot import numpy as np import pandas as pd data=pd.read_csv("/Users/superman/Downloads/words_file2.txt",header=None) df_input=pd.DataFrame(data) df_output=pd.DataFrame(np.arange(676).reshape((26,26)), index = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'], columns = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']) df_output.index.name="Start" df_output.columns.name="End" df_output This below screen shot is what I have to find I have to find each word...

  • You may import the following library functions in your module: from fractions import gcd from math...

    You may import the following library functions in your module: from fractions import gcd from math import log from math import floor You may also use: • the .bit_length() method to efficiently obtain the bit length of an integer, • the abs() function for computing the absolute value of an integer, • and the // operator for integer division (you should avoid using / because it does not work for very large integers). Implement the following Python functions. These functions...

  • For this assignment, your job is to create a simple game called Opoly. The objectives of...

    For this assignment, your job is to create a simple game called Opoly. The objectives of this assignment are to: Break down a problem into smaller, easier problems. Write Java methods that call upon other methods to accomplish tasks. Use a seed value to generate random a sequence of random numbers. Learn the coding practice of writing methods that perform a specific task. Opoly works this way: The board is a circular track of variable length (the user determines the...

  • == Programming Assignment == For this assignment you will write a program that controls a set...

    == Programming Assignment == For this assignment you will write a program that controls a set of rovers and sends them commands to navigate on the Martian surface where they take samples. Each rover performs several missions and each mission follows the same sequence: deploy, perform one or more moves and scans, then return to base and report the results. While on a mission each rover needs to remember the scan results, in the same order as they were taken,...

  • so i have my c++ code and ive been working on this for hours but i...

    so i have my c++ code and ive been working on this for hours but i cant get it to run im not allowed to use arrays. im not sure how to fix it thank you for the help our job is to write a menu driven program that can convert to display Morse Code ere is the menu the program should display Menu Alphabet Initials N-Numbers - Punctuations S = User Sentence Q- Quit Enter command the user chooses...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT