Home

Learn Programming & Prepare for NPTEL Exams... Swayam Solver is your one-stop destination for NPTEL exam preparation.

NPTEL Programming, Data Structures And Algorithms Using Python July 2023

 

NPTEL » Programming, Data Structures And Algorithms Using Python



  Please scroll down for latest Programs. ðŸ‘‡ 




Week 2 Programming Assignment

Due on 2023-08-10, 23:59 IST
Write three Python functions as specified below. Paste the text for all three functions together into the submission window. Your function will be called automatically with various inputs and should return values as specified. Do not write commands to read any input or print any output.
  • You may define additional auxiliary functions as needed.
  • In all cases you may assume that the value passed to the function is of the expected type, so your function does not have to check for malformed inputs.
  • For each function, there are normally some public test cases and some (hidden) private test cases.
  • "Compile and run" will evaluate your submission against the public test cases.
  • "Submit" will evaluate your submission against the hidden private test cases. There are 12 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
  • Ignore warnings about "Presentation errors".

  1. A positive integer m is a prime product if it can be written as p×q, where p and q are both primes. .

    Write a Python function primeproduct(m) that takes an integer m as input and returns True if m is a prime product and False otherwise. (If m is not positive, your function should return False.)

    Here are some examples of how your function should work.

    >>> primeproduct(6)
    True
    
    >>> primeproduct(188)
    False
    
    >>> primeproduct(202)
    True
    
  2. Write a function delchar(s,c) that takes as input strings s and c, where c has length 1 (i.e., a single character), and returns the string obtained by deleting all occurrences of c in s. If c has length other than 1, the function should return s

    Here are some examples to show how your function should work.

     
    >>> delchar("banana","b")
    'anana'
    
    >>> delchar("banana","a")
    'bnn'
    
    >>> delchar("banana","n")
    'baaa'
    
    >>> delchar("banana","an")
    'banana'
    
  3. Write a function shuffle(l1,l2) that takes as input two lists, 11 and l2, and returns a list consisting of the first element in l1, then the first element in l2, then the second element in l1, then the second element in l2, and so on. If the two lists are not of equal length, the remaining elements of the longer list are appended at the end of the shuffled output.

    Here are some examples to show how your function should work.

    >>> shuffle([0,2,4],[1,3,5])
    [0, 1, 2, 3, 4, 5]
    
    >>> shuffle([0,2,4],[1])
    [0, 1, 2, 4]
    
    >>> shuffle([0],[1,3,5])
    [0, 1, 3, 5]
    
Your last recorded submission was on 2023-08-04, 15:25 IST
Select the Language for this assignment. 
1
def factors(n):
2
    factorlist = []
3
    for i in range(1,n+1):
4
        if n%i == 0:
5
            factorlist.append(i)
6
    return(factorlist)
7
8
def isprime(n):
9
    return(factors(n) == [1,n])
10
11
def primeproduct(n):
12
    for i in range(1,n+1):
13
        if n%i == 0:
14
            if isprime(i) and isprime(n//i):
15
                return(True)
16
    return(False)
17
18
def delchar(s,c):
19
    if len(c) != 1:
20
        return(s)
21
    snew = ""
22
    for char in s:
23
        if char != c:
24
            snew = snew + char
25
    return(snew)
26
27
def shuffle(l1,l2):
28
    if len(l1) < len(l2):
29
        minlength = len(l1)
30
    else:
31
        minlength = len(l2)
32
    shuffled = []
33
    for i in range(minlength):
34
        shuffled.append(l1[i])
35
        shuffled.append(l2[i])
36
    shuffled = shuffled + l1[minlength:] + l2[minlength:]
37
    return(shuffled)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
primeproduct(6)
True
True\n
Passed after ignoring Presentation Error
Test Case 2
primeproduct(188)
False
False\n
Passed after ignoring Presentation Error
Test Case 3
primeproduct(202)
True
True\n
Passed after ignoring Presentation Error
Test Case 4
delchar("banana","b")
anana
anana\n
Passed after ignoring Presentation Error
Test Case 5
delchar("banana","a")
bnn
bnn\n
Passed after ignoring Presentation Error
Test Case 6
delchar("banana","n")
baaa
baaa\n
Passed after ignoring Presentation Error
Test Case 7
delchar("banana","an")
banana
banana\n
Passed after ignoring Presentation Error
Test Case 8
shuffle([0,2,4],[1,3,5])
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]\n
Passed after ignoring Presentation Error
Test Case 9
shuffle([0,2,4],[1])
[0, 1, 2, 4]
[0, 1, 2, 4]\n
Passed after ignoring Presentation Error
Test Case 10
shuffle([0],[1,3,5])
[0, 1, 3, 5]
[0, 1, 3, 5]\n
Passed after ignoring Presentation Error




Private Test cases used for EvaluationStatus
Test Case 1
Passed
Test Case 2
Passed
Test Case 3
Passed
Test Case 4
Passed
Test Case 5
Passed
Test Case 6
Passed
Test Case 7
Passed
Test Case 8
Passed
Test Case 9
Passed
Test Case 10
Passed
Test Case 11
Passed
Test Case 12
Passed


........................................................................................................................................................





Week 3 Programming Assignment

Due on 2023-08-17, 23:59 IST
Write three Python functions as specified below. Paste the text for all three functions together into the submission window. Your function will be called automatically with various inputs and should return values as specified. Do not write commands to read any input or print any output.
  • You may define additional auxiliary functions as needed.
  • In all cases you may assume that the value passed to the function is of the expected type, so your function does not have to check for malformed inputs.
  • For each function, there are normally some public test cases and some (hidden) private test cases.
  • "Compile and run" will evaluate your submission against the public test cases.
  • "Submit" will evaluate your submission against the hidden private test cases. There are 12 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
  • Ignore warnings about "Presentation errors".

    1. Write a function expanding(l) that takes as input a list of integer l and returns True if the absolute difference between each adjacent pair of elements strictly increases.

      Here are some examples of how your function should work.

        >>> expanding([1,3,7,2,9])
        True
      

      Explanation: Differences between adjacent elements are 3-1 = 27-3 = 47-2 = 59-2 = 7.

        >>> expanding([1,3,7,2,-3]) 
        False
      

      Explanation: Differences between adjacent elements are 3-1 = 27-3 = 47-2 = 52-(-3) = 5, so not strictly increasing.

        >>> expanding([1,3,7,10])
        False
      

      Explanation: Differences between adjacent elements are 3-1 = 27-3 = 410-7 = 3, so not increasing.

    2. Write a Python function sumsquare(l) that takes a nonempty list of integers and returns a list [odd,even], where odd is the sum of squares all the odd numbers in l and even is the sum of squares of all the even numbers in l.

      Here are some examples to show how your function should work.

      >>> sumsquare([1,3,5])
      [35, 0]
      
      >>> sumsquare([2,4,6])
      [0, 56]
      
      >>> sumsquare([-1,-2,3,7])
      [59, 4]
      
    3. A two dimensional matrix can be represented in Python row-wise, as a list of lists: each inner list represents one row of the matrix. For instance, the matrix

      1  2  3  4
      5  6  7  8
      

      would be represented as [[1, 2, 3, 4], [5, 6, 7, 8]].

      The transpose of a matrix converts each row into a column. The transpose of the matrix above is:

      1  5
      2  6
      3  7
      4  8
      

      which would be represented as [[1, 5], [2, 6], [3, 7], [4, 8]].

      Write a Python function transpose(m) that takes as input a two dimensional matrix m and returns the transpose of mThe argument m should remain undisturbed by the function.

      Here are some examples to show how your function should work. You may assume that the input to the function is always a non-empty matrix.

      >>> transpose([[1,2,3],[4,5,6]])
      [[1, 4], [2, 5], [3, 6]]
      
      >>> transpose([[1],[2],[3]])
      [[1, 2, 3]]
      
      >>> transpose([[3]])
      [[3]]
      
      
Your last recorded submission was on 2023-08-10, 16:23 IST
Select the Language for this assignment. 
1
def expanding(l):
2
    if len(l) < 3:
3
        return(True)
4
    for i in range(len(l)-2):
5
        diff = abs(l[i+1]-l[i])
6
        if diff >= abs(l[i+2]-l[i+1]):
7
            return(False)
8
    return(True)
9
10
def sumsquare(l):
11
    odd = 0
12
    even = 0
13
    for x in l:
14
        if x%2 :
15
            odd = odd + x**2
16
        else:
17
            even = even + x**2
18
    return([odd,even])
19
20
def transpose(m):
21
  list=[]
22
  c=len(m[0])
23
  r=len(m)
24
  for i in range(0,c):
25
    li=[]
26
    for j in range(0,r):
27
      li=li+[m[j][i]]
28
    list=list+[li] 
29
  return(list)
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed
Test Case 2
Passed
Test Case 3
Passed
Test Case 4
Passed
Test Case 5
Passed
Test Case 6
Passed
Test Case 7
Passed
Test Case 8
Passed
Test Case 9
Passed
Test Case 10
Passed
Test Case 11
Passed
Test Case 12
Passed


........................................................................................................................................................


Week 4 Programming Assignment

Due on 2023-08-24, 23:59 IST

Write two Python functions as specified below. Paste the text for both functions together into the submission window. Your function will be called automatically with various inputs and should return values as specified. Do not write commands to read any input or print any output.

  • You may define additional auxiliary functions as needed.
  • In all cases you may assume that the value passed to the function is of the expected type, so your function does not have to check for malformed inputs.
  • For each function, there are normally some public test cases and some (hidden) private test cases.
  • "Compile and run" will evaluate your submission against the public test cases.
  • "Submit" will evaluate your submission against the hidden private test cases. There are 10 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
  • Ignore warnings about "Presentation errors".

  1. Write a Python function histogram(l) that takes as input a list of integers with repetitions and returns a list of pairs as follows:.

    • for each number n that appears in l, there should be exactly one pair (n,r) in the list returned by the function, where r is the number of repetitions of n in l.

    • the final list should be sorted in ascending order by r, the number of repetitions. For numbers that occur with the same number of repetitions, arrange the pairs in ascending order of the value of the number.

    For instance:

    >>> histogram([13,12,11,13,14,13,7,7,13,14,12])
    [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]
    
    >>> histogram([7,12,11,13,7,11,13,14,12])
    [(14, 1), (7, 2), (11, 2), (12, 2), (13, 2)]
    
    >>> histogram([13,7,12,7,11,13,14,13,7,11,13,14,12,14,14,7])
    [(11, 2), (12, 2), (7, 4), (13, 4), (14, 4)]
    
  2. A college maintains academic information about students in three separate lists

    • Course details: A list of pairs of form (coursecode,coursename), where both entries are strings. For instance,
      [ ("MA101","Calculus"),("PH101","Mechanics"),("HU101","English") ]

    • Student details: A list of pairs of form (rollnumber,name), where both entries are strings. For instance,
      [ ("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar") ]

    • A list of triples of the form (rollnumber,coursecode,grade), where all entries are strings. For instance,
      [ ("UGM2018001", "MA101", "AB"), ("UGP2018132", "PH101", "B"), ("UGM2018001", "PH101", "B") ]. You may assume that each roll number and course code in the grade list appears in the student details and course details, respectively.

    Your task is to write a function transcript (coursedetails,studentdetails,grades) that takes these three lists as input and produces consolidated grades for each student. Each of the input lists may have its entries listed in arbitrary order. Each entry in the returned list should be a tuple of the form

    (rollnumber, name,[(coursecode_1,coursename_1,grade_1),...,(coursecode_k,coursename_k,grade_k)])

    where the student has grades for k ≥ 1 courses reported in the input list grades.

    The output list should be organized as follows.

    • The tuples shold sorted in ascending order by rollnumber

    • Each student's grades should sorted in ascending order by coursecode

    For instance

     
    >>>transcript([("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")],[("UGM2021001","Rohit Grewal"),("UGP2021132","Neha Talwar")],[("UGM2021001","MA101","AB"),("UGP2021132","PH101","B"),("UGM2021001","PH101","B")])
    
    [('UGM2021001', 'Rohit Grewal', [('MA101', 'Calculus', 'AB'), ('PH101', 'Mechanics', 'B')]), ('UGP2021132', 'Neha Talwar', [('PH101', 'Mechanics', 'B')])]
    
    >>>transcript([("T1","Test 1"),("T2","Test 2"),("T3","Test 3")],[("Captain","Rohit Sharma"),("Batsman","Virat Kohli"),("No3","Cheteshwar Pujara")],[("Batsman","T1","14"),("Captain","T1","33"),("No3","T1","30"),("Batsman","T2","55") ,("Captain","T2","158"),("No3","T2","19"), ("Batsman","T3","33"),("Captain","T3","95"),("No3","T3","51")])
    
    [('Batsman', 'Virat Kohli', [('T1', 'Test 1', '14'), ('T2', 'Test 2', '55'), ('T3', 'Test 3', '33')]), ('Captain', 'Rohit Sharma', [('T1', 'Test 1', '33'), ('T2', 'Test 2', '158'), ('T3', 'Test 3', '95')]),('No3', 'Cheteshwar Pujara', [('T1', 'Test 1', '30'), ('T2', 'Test 2', '19'), ('T3', 'Test 3', '51')])]
    
Your last recorded submission was on 2023-08-20, 15:49 IST
Select the Language for this assignment. 
1
def histogram(l):
2
  tuplelist=[]
3
  for i in range(len(l)):
4
    v=l[i]
5
    count=0
6
    
7
    for j in range(len(l)):
8
      if l[j] == v:
9
        count+=1
10
    if i==0:
11
        tuplelist+=[(v,count)]
12
    else :
13
        for k in range(len(tuplelist)):
14
          if tuplelist[k] == (v,count):
15
            break
16
        else:
17
          tuplelist+=[(v,count)]
18
  
19
  SelectionSort(tuplelist)
20
  return(tuplelist)
21
22
23
def SelectionSort(l):
24
  for start in range(len(l)):
25
    minpos = start
26
    for i in range(start,len(l)):
27
      if l[i][1] < l[minpos][1]:
28
        minpos = i
29
      elif l[i][1] == l[minpos][1]:
30
        if l[i][0] < l[minpos][0]:
31
          minpos = i
32
    (l[start],l[minpos]) = (l[minpos],l[start])
33
  
34
def transcript (cd,st,gra):
35
  list=[]
36
  for i in range(len(st)):
37
    rollno = st[i][0]
38
    student_name= st[i][1]
39
    clist=[]
40
    for j in range(len(gra)):
41
      if gra[j][0] == rollno:
42
        coursecode= gra[j][1]
43
        grade= gra[j][2]
44
        for k in range(len(cd)):
45
          if cd[k][0] == coursecode:
46
            coursename = cd[k][1]
47
            break
48
        clist+=[(coursecode,coursename,grade)]
49
        csort(clist)
50
    list+=[(rollno,student_name,clist)]
51
  csort(list)
52
  return(list)
53
54
def csort(l):
55
  for start in range(len(l)): 
56
    minpos = start
57
    for i in range(start,len(l)):
58
      if l[i][0] < l[minpos][0]:
59
        minpos = i
60
    (l[start],l[minpos]) = (l[minpos],l[start])
0
~~~THERE IS SOME INVISIBLE CODE HERE~~~
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed
Test Case 2
Passed
Test Case 3
Passed
Test Case 4
Passed
Test Case 5
Passed
Test Case 6
Passed
Test Case 7
Passed
Test Case 8
Passed
Test Case 9
Passed
Test Case 10
Passed


........................................................................................................................................................



Week 5 Programming Assignment

Due on 2023-08-31, 23:59 IST

For this assignment, you have to write a complete Python program. Paste your code in the window below.

  • You may define additional auxiliary functions as needed.
  • In all cases you may assume that the input to your program has the expected format, so your program does not have to check for malformed inputs.
  • There are some public test cases and some (hidden) private test cases.
  • "Compile and run" will evaluate your submission against the public test cases.
  • "Submit" will evaluate your submission against the hidden private test cases. There are 6 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
  • Ignore warnings about "Presentation errors".


The academic office at the Hogwarts School of Witchcraft and Wizardry has compiled data about students' grades. The data is provided as text from standard input in three parts: information about courses, information about students and information about grades. Each part has a specific line format, described below..

  1. Information about courses
    Line format: Course Code~Course Name~Semester~Year~Instructor
  2. Information about students
    Line format: Roll Number~Full Name
  3. Information about grades
    Line format: Course Code~Semester~Year~Roll Number~Grade

The possible grades are A, AB, B, BC, C, CD, D with corresponding grade points 10, 9, 8, 7, 6, 5 and 4. The grade point average of a student is the sum of his/her grade points divided by the number of courses. For instance, if a student has taken two courses with grades A and C, the grade point average is 8.50 = (10+7)÷2. If a student has not completed any courses, the grade point average is defined to be 0.

You may assume that the data is internally consistent. For every grade, there is a corresponding course code and roll number in the input data.

Each section of the input starts with a line containing a single keyword. The first section begins with a line containing Courses. The second section begins with a line containing Students. The third section begins with a line containing Grades. The end of the input is marked by a line containing EndOfInput.

Write a Python program to read the data as described above and print out a line listing the grade point average for each student in the following format:

Roll Number~Full Name~Grade Point Average

Your output should be sorted by Roll Number. The grade point average should be rounded off to 2 digits after the decimal point. Use the built-in function round().

Here is a sample input and its corresponding output.

Sample Input

Courses
TRAN~Transfiguration~1~2011-2012~Minerva McGonagall
CHAR~Charms~1~2011-2012~Filius Flitwick
Students
SLY2301~Hannah Abbott
SLY2302~Euan Abercrombie
SLY2303~Stewart Ackerley
SLY2304~Bertram Aubrey
SLY2305~Avery
SLY2306~Malcolm Baddock
SLY2307~Marcus Belby
SLY2308~Katie Bell
SLY2309~Sirius Orion Black
Grades
TRAN~1~2011-2012~SLY2301~AB
TRAN~1~2011-2012~SLY2302~B
TRAN~1~2011-2012~SLY2303~B
TRAN~1~2011-2012~SLY2305~A
TRAN~1~2011-2012~SLY2306~BC
TRAN~1~2011-2012~SLY2308~A
TRAN~1~2011-2012~SLY2309~AB
CHAR~1~2011-2012~SLY2301~A
CHAR~1~2011-2012~SLY2302~BC
CHAR~1~2011-2012~SLY2303~B
CHAR~1~2011-2012~SLY2305~BC
CHAR~1~2011-2012~SLY2306~C
CHAR~1~2011-2012~SLY2307~B
CHAR~1~2011-2012~SLY2308~AB
EndOfInput

Sample Output

SLY2301~Hannah Abbott~9.5
SLY2302~Euan Abercrombie~7.5
SLY2303~Stewart Ackerley~8.0
SLY2304~Bertram Aubrey~0
SLY2305~Avery~8.5
SLY2306~Malcolm Baddock~6.5
SLY2307~Marcus Belby~8.0
SLY2308~Katie Bell~9.5
SLY2309~Sirius Orion Black~9.0
Your last recorded submission was on 2023-08-22, 17:14 IST
Select the Language for this assignment. 
1
# Convert letter grade to grade point
2
def gradetonum(grade):
3
    if grade == 'A':
4
        return(10)
5
    elif grade == 'AB':
6
        return(9)
7
    elif grade == 'B':
8
        return(8)
9
    elif grade == 'BC':
10
        return(7)
11
    elif grade == 'C':
12
        return(6)
13
    elif grade == 'CD':
14
        return(5)
15
    elif grade == 'D':
16
        return(4)
17
    else:
18
        return(0)
19
                   
20
# Set up three dictionaries to store data
21
rollname = {}    # Key: roll number, Value: Name
22
gradepoint = {}  # Key: roll number, Value: Cumulative grade points
23
coursecount = {} # Key: roll number, Value: Number of courses taken
24
25
nextline = input().strip()
26
while nextline.find("Courses") < 0:
27
    nextline = input().strip()
28
29
# Read course data
30
while nextline.find("Students") < 0:
31
    nextline = input().strip()
32
    # Course data is irrelevant for this problem!
33
34
# Read students data
35
nextline = input().strip()
36
while nextline.find("Grades") < 0:
37
    fields = nextline.split('~')
38
    roll=fields[0]
39
    name=fields[1]
40
    rollname[roll] = name   # Initialize
41
    gradepoint[roll] = 0    # Initialize
42
    coursecount[roll] = 0   # Initialize
43
    nextline = input().strip()
44
45
# Read grades data
46
nextline = input().strip()
47
while nextline.find("EndOfInput") < 0:
48
    fields = nextline.split('~')
49
    roll=fields[3]
50
    grade=fields[4]
51
    gradepoint[roll] += gradetonum(grade)  # Update
52
    coursecount[roll] += 1                 # Update
53
    nextline = input().strip()
54
55
# Print output
56
for roll in sorted(rollname.keys()):
57
    if coursecount[roll] > 0:
58
        gpa = round(gradepoint[roll]/coursecount[roll],2)
59
    else:
60
        gpa = 0
61
    print(roll,rollname[roll],gpa,sep='~',end='\n' )
62
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   



Private Test cases used for EvaluationStatus
Test Case 1
Passed
Test Case 2
Passed
Test Case 3
Passed
Test Case 4
Passed
Test Case 5
Passed
Test Case 6
Passed



Week 8 Programming Assignment - Dividing Sequences

Due on 2023-09-21, 23:59 IST

For this assignment, you have to write a complete Python program. Paste your code in the window below.

  • You may define additional auxiliary functions as needed.
  • There are some public test cases and some (hidden) private test cases.
  • "Compile and run" will evaluate your submission against the public test cases
  • "Submit" will evaluate your submission against the hidden private test cases. There are 10 private test cases, with equal weightage. You will get feedback about which private test cases pass or fail, though you cannot see the actual test cases.
  • Ignore warnings about "Presentation errors".

Dividing Sequences

(IARCS OPC Archive, K Narayan Kumar, CMI)

This problem is about sequences of positive integers a1,a2,…,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .

fully dividing sequence is a sequence a1,a2,…,aN where ai divides aj whenever i < j. For example, 3,15,60,720 is a fully dividing sequence.

Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.

Consider the sequence 2,3,7,8,14,39,145,76,320

It has a fully dividing sequence of length 3, namely 2,8,320, but none of length 4 or greater.

Consider the sequence 2,11,16,12,36,60,71,17,29,144,288,129,432,993 .

It has two fully dividing subsequences of length 5,

  • 2,11,16,12,36,60,71,17,29,144,288,129,432,993 and
  • 2,11,16,12,36,60,71,17,29,144,288,129,432,993

and none of length 6 or greater.

Solution hint

Let the input be a1, a2, …, aN. Let us define Best(i) to be the length of longest dividing sequence in a1,a2,…ai that includes ai.

Write an expression for Best(i) in terms of Best(j) with j<i, with base case Best(1) = 1. Solve this recurrence using dynamic programming.

Full solution

.

Input format

The first line of input contains a single positive integer N indicating the length of the input sequence. Lines 2,…,N+1 contain one integer each. The integer on line i+1 is ai.

Output format

Your output should consist of a single integer indicating the length of the longest fully dividing subsequence of the input sequence.

Test Data

You may assume that N ≤ 2500.

Example:

Here are the inputs and outputs corresponding to the two examples discussed above.

Sample input 1:

9
2 
3 
7 
8 
14 
39 
145 
76 
320

Sample output 1:

3

Sample input 2:

14
2
11 
16 
12 
36 
60 
71 
17 
29 
144 
288 
129 
432 
993

Sample output 2:

5
Select the Language for this assignment. 
1
n = int(input())
2
L = list()
3
bestvals =list()
4
best_stored = list()
5
for x in range(n):
6
  L.append(int(input()))
7
  best_stored.append(0)
8
9
best_stored[0] = 1
10
11
for i in range(n):
12
  maxval = 1
13
  for j in range(i):
14
    if L[i] % L[j] == 0:
15
      maxval = max(maxval,(best_stored[j])+1)
16
  best_stored[i] = maxval
17
18
print(max(best_stored),end="")
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
9
2 
3 
7 
8 
14 
39 
145 
76 
320
3
3
Passed
Test Case 2
14
2
11 
16 
12 
36 
60 
71 
17 
29 
144 
288 
129 
432 
993
5
5
Passed





Private Test cases used for EvaluationStatus
Test Case 1
Passed
Test Case 2
Passed
Test Case 3
Passed
Test Case 4
Passed
Test Case 5
Passed
Test Case 6
Passed
Test Case 7
Passed
Test Case 8
Passed
Test Case 9
Passed
Test Case 10
Passed




No comments:

Post a Comment

Keep your comments reader friendly. Be civil and respectful. No self-promotion or spam. Stick to the topic. Questions welcome.