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 Jan-2024

 

NPTEL » Programming, Data Structures And Algorithms Using Python


  Please scroll down for latest Programs ðŸ‘‡ 




Week 2 Programming Assignment

Due on 2024-02-08, 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 can be expresseed as the sum of three squares if it is of the form p + q + r where p, q, r ≥ 0, and p, q, r are all perfect squares. For instance, 2 can be written as 0+1+1 but 7 cannot be expressed as the sum of three squares. The first numbers that cannot be expressed as the sum of three squares are 7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71, … (see Legendre's three-square theorem).

    Write a Python function threesquares(m) that takes an integer m as input and returns True if m can be expressed as the sum of three squares and False otherwise. (If m is not positive, your function should return False.)

    Here are some examples of how your function should work.

    >>> threesquares(6)
    True
    
    >>> threesquares(188)
    False
    
    >>> threesquares(1000)
    True
    
  2. Write a function repfree(s) that takes as input a string s and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise.

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

     
    >>> repfree("zb%78")
    True
    
    >>> repfree("(7)(a")
    False
    
    >>> repfree("a)*(?")
    True
    
    >>> repfree("abracadabra")
    False
    
  3. A list of numbers is said to be a hill if it consists of an ascending sequence followed by a descending sequence, where each of the sequences is of length at least two. Similarly, a list of numbers is said to be a valley if it consists of an descending sequence followed by an ascending sequence. You can assume that consecutive numbers in the input sequence are always different from each other.

    Write a Python function hillvalley(l) that takes a list l of integers and returns True if it is a hill or a valley, and False otherwise.

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

    >>> hillvalley([1,2,3,5,4])
    True
    
    >>> hillvalley([1,2,3,4,5])
    False
    
    >>> hillvalley([5,4,1,2,3])
    True
    
    >>> hillvalley([5,4,3,2,1])
    False
    
Your last recorded submission was on 2024-02-08, 17:45 IST
Select the Language for this assignment. 
1
##############################
2
def factors(n):
3
    if n == 0:
4
        return([0])
5
    factorlist = []
6
    for i in range(1,n+1):
7
        if n%i == 0:
8
            factorlist.append(i)
9
    return(factorlist)
10
def square(n):
11
    return(len(factors(n))%2 == 1)
12
def threesquares(n):
13
    for i in range(0,n+1):
14
        for j in range(i,n+1):
15
            if square(i) and square(j) and square(n-(i+j)):
16
                return(
17
                    True)
18
    return(False)
19
##################################################
20
def repfree(s):
21
    for i in range(len(s)):
22
        for j in range(i+1,len(s)):
23
            if s[i] == s[j]:
24
                return(False)
25
    return(True)
26
##################################################
27
def ascending(l):
28
    if len(l) <= 1:
29
        return(True)
30
    else:
31
        return(l[0] < l[1] and ascending(l[1:]))
32
def descending(l):
33
    if len(l) <= 1:
34
        return(True)
35
    else:
36
        return(l[0] > l[1] and descending(l[1:]))
37
def hill(l):
38
    for i in range(1,len(l)-1):
39
        if ascending(l[:i+1]) and descending(l[i:]):
40
            return(True)
41
    return(False)
42
def valley(l):
43
    for i in range(1,len(l)-1):
44
        if descending(l[:i+1]) and ascending(l[i:]):
45
            return(True)
46
    return(False)
47
def hillvalley(l):
48
    return(hill(l) or valley(l))
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
threesquares(6)
True
True\n
Passed after ignoring Presentation Error
Test Case 2
threesquares(143)
False
False\n
Passed after ignoring Presentation Error
Test Case 3
threesquares(1024)
True
True\n
Passed after ignoring Presentation Error
Test Case 4
repfree("qwerty!@#2")
True
True\n
Passed after ignoring Presentation Error
Test Case 5
repfree("(x+6)(y-5)")
False
False\n
Passed after ignoring Presentation Error
Test Case 6
repfree("94templars")
True
True\n
Passed after ignoring Presentation Error
Test Case 7
repfree("siruseri")
False
False\n
Passed after ignoring Presentation Error
Test Case 8
hillvalley([1,2,3,5,4,3,2,1])
True
True\n
Passed after ignoring Presentation Error
Test Case 9
hillvalley([1,2,3,4,5,3,2,4,5,3,2,1])
False
False\n
Passed after ignoring Presentation Error
Test Case 10
hillvalley([9,5,4,-1,-2,3,7])
True
True\n
Passed after ignoring Presentation Error
Test Case 11
hillvalley([5,4,3,2,1,0,-1,-2,-3])
False
False\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 2024-02-15, 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 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. Define a Python function remdup(l) that takes a nonempty list of integers l and removes all duplicates in l, keeping only the first occurrence of each number. For instance:

    >>> remdup([3,1,3,5])
    [3, 1, 5]
    
    >>> remdup([7,3,-1,-5])
    [7, 3, -1, -5]
    
    >>> remdup([3,5,7,5,3,7,10])
    [3, 5, 7, 10]
    
  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 2024-02-06, 15:15 IST
Select the Language for this assignment. 
1
def remdup(l):
2
  p=[]
3
  for x in l:
4
    if(x not in p):
5
      p=p+[x]
6
  return(p)
7
###############################
8
def sumsquare(l):
9
  list=[0,0]
10
  for i in range(len(l)):
11
    if l[i]%2==0:
12
      list[1]+=l[i]**2
13
    else:
14
      list[0]+=l[i]**2
15
  return (list)
16
###############################
17
def transpose(m):
18
  list=[]
19
  c=len(m[0])
20
  r=len(m)
21
  for i in range(0,c):
22
    li=[]
23
    for j in range(0,r):
24
      li=li+[m[j][i]]
25
    list=list+[li] 
26
  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.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
remdup([3,1,3,5])
[3, 1, 5]
[3, 1, 5]\n
Passed after ignoring Presentation Error
Test Case 2
remdup([7,3,-1,-5])
[7, 3, -1, -5]
[7, 3, -1, -5]\n
Passed after ignoring Presentation Error
Test Case 3
remdup([3,5,7,5,3,7,10])
[3, 5, 7, 10]
[3, 5, 7, 10]\n
Passed after ignoring Presentation Error
Test Case 4
sumsquare([1,3,5])
[35, 0]
[35, 0]\n
Passed after ignoring Presentation Error
Test Case 5
sumsquare([2,4,6])
[0, 56]
[0, 56]\n
Passed after ignoring Presentation Error
Test Case 6
sumsquare([-1,-2,3,7])
[59, 4]
[59, 4]\n
Passed after ignoring Presentation Error
Test Case 7
transpose([[1,2,3],[4,5,6]])
[[1, 4], [2, 5], [3, 6]]
[[1, 4], [2, 5], [3, 6]]\n
Passed after ignoring Presentation Error
Test Case 8
transpose([[1],[2],[3]])
[[1, 2, 3]]
[[1, 2, 3]]\n
Passed after ignoring Presentation Error
Test Case 9
transpose([[3]])
[[3]]
[[3]]\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






Week 4 Programming Assignment

Due on 2024-02-22, 23:59 IST

Write Python functions as specified below. Paste the text for all functions together into the submission window.

  • 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 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 and report a score on 100. There are 10 private testcases in all, each 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. We represent scores of batsmen across a sequence of matches in a two level dictionary as follows:

    {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}
    

    Each match is identified by a string, as is each player. The scores are all integers. The names associated with the matches are not fixed (here they are 'match1''match2''match3'), nor are the names of the players. A player need not have a score recorded in all matches.

    Define a Python function orangecap(d) that reads a dictionary d of this form and identifies the player with the highest total score. Your function should return a pair (playername,topscore) where playername is a string, the name of the player with the highest score, and topscore is an integer, the total score of playername.

    The input will be such that there are never any ties for highest total score.

    For instance:

    >>> orangecap({'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}})
    ('player3', 100)
    
    >>> orangecap({'test1':{'Pant':84, 'Kohli':120}, 'test2':{'Pant':59, 'Gill':42}})
    ('Pant', 143)
    
  2. Let us consider polynomials in a single variable x with integer coefficients. For instance:

    3x4 - 17x2 - 3x + 5
    

    Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs.

    We have the following constraints to guarantee that each polynomial has a unique representation:

    • Terms are sorted in descending order of exponent
    • No term has a zero cofficient
    • No two terms have the same exponent
    • Exponents are always nonnegative

    For example, the polynomial introduced earlier is represented as:

    [(3,4),(-17,2),(-3,1),(5,0)]
    

    The zero polynomial, 0, is represented as the empty list [], since it has no terms with nonzero coefficients.

    Write Python functions for the following operations:

    addpoly(p1,p2)
    multpoly(p1,p2)
    

    that add and multiply two polynomials, respectively.

    You may assume that the inputs to these functions follow the representation given above. Correspondingly, the outputs from these functions should also obey the same constraints.

    You can write auxiliary functions to "clean up" polynomials – e.g., remove zero coefficient terms, combine like terms, sort by exponent etc. Build a library of functions that can be combined to achieve the desired format.

    You may also want to convert the list representation to a dictionary representation and manipulate the dictionary representation, and then convert back.

    Some examples:

      
       >>> addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
       [(2, 1),(3, 0)]
    
       Explanation: (4x^3 + 3) + (-4x^3 + 2x) = 2x + 3
    
       >>> addpoly([(2,1)],[(-2,1)])
       []
    
       Explanation: 2x + (-2x) = 0
    
       >>> multpoly([(1,1),(-1,0)],[(1,2),(1,1),(1,0)])
       [(1, 3),(-1, 0)]
    
       Explanation: (x - 1) * (x^2 + x + 1) = x^3 - 1
    


Link of text file


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
orangecap({'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}})
('player3', 100)
('player3', 100)\n
Passed after ignoring Presentation Error
Test Case 2
orangecap({'test1':{'Pant':84, 'Kohli':120}, 'test2':{'Pant':59, 'Gill':42}})
('Pant', 143)
('Pant', 143)\n
Passed after ignoring Presentation Error
Test Case 3
addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
[(2, 1), (3, 0)]
[(2, 1), (3, 0)]\n
Passed after ignoring Presentation Error
Test Case 4
addpoly([(2,1)],[(-2,1)])
[]
[]\n
Passed after ignoring Presentation Error
Test Case 5
multpoly([(1,1),(-1,0)],[(1,2),(1,1),(1,0)])
[(1, 3), (-1, 0)]
[(1, 3), (-1, 0)]\n
Passed after ignoring Presentation Error




Week 5 Programming Assignment

Due on 2024-02-29, 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 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".

Here are some basic facts about tennis scoring: A tennis match is made up of sets. A set is made up of games.

To win a set, a player has to win 6 games with a difference of 2 games. At 6-6, there is often a special tie-breaker. In some cases, players go on playing till one of them wins the set with a difference of two games.

Tennis matches can be either 3 sets or 5 sets. The player who wins a majority of sets wins the match (i.e., 2 out 3 sets or 3 out of 5 sets) The score of a match lists out the games in each set, with the overall winner's score reported first for each set. Thus, if the score is 6-3, 5-7, 7-6 it means that the first player won the first set by 6 games to 3, lost the second one 5 games to 7 and won the third one 7 games to 6 (and hence won the overall match as well by 2 sets to 1).

You will read input from the keyboard (standard input) containing the results of several tennis matches. Each match's score is recorded on a separate line with the following format:

Winner:Loser:Set-1-score,...,Set-k-score, where 2 ≤ k ≤ 5

For example, an input line of the form

Jabeur:Swiatek:3-6,6-3,6-3

indicates that Jabeur beat Swiatek 3-6, 6-3, 6-3 in a best of 3 set match.

The input is terminated by a line consisting of the string "EOF".

You have to write a Python program that reads information about all the matches and compile the following statistics for each player:

  1. Number of best-of-5 set matches won
  2. Number of best-of-3 set matches won
  3. Number of sets won
  4. Number of games won
  5. Number of sets lost
  6. Number of games lost

You should print out to the screen (standard output) a summary in decreasing order of ranking, where the ranking is according to the criteria 1-6 in that order (compare item 1, if equal compare item 2, if equal compare item 3 etc, noting that for items 5 and 6 the comparison is reversed).

For instance, given the following data

Zverev:Alcaraz:2-6,6-7,7-6,6-3,6-1
Swiatek:Jabeur:6-4,6-4
Alcaraz:Zverev:6-3,6-3
Jabeur:Swiatek:1-6,7-5,6-2
Zverev:Alcaraz:6-0,7-6,6-3
Jabeur:Swiatek:2-6,6-2,6-0
Alcaraz:Zverev:6-3,4-6,6-3,6-4
Swiatek:Jabeur:6-1,3-6,7-5
Zverev:Alcaraz:7-6,4-6,7-6,2-6,6-2
Jabeur:Swiatek:6-4,1-6,6-3
Alcaraz:Zverev:7-5,7-5
Jabeur:Swiatek:3-6,6-3,6-3
EOF

your program should print out the following

Zverev 3 0 10 104 11 106
Alcaraz 1 2 11 106 10 104
Jabeur 0 4 9 76 8 74
Swiatek 0 2 8 74 9 76

You can assume that there are no spaces around the punctuation marks ":", "-" and ",". Each player's name will be spelled consistently and no two players have the same name.


Link of Text file

 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
Zverev:Alcaraz:2-6,6-7,7-6,6-3,6-1
Swiatek:Jabeur:6-4,6-4
Alcaraz:Zverev:6-3,6-3
Jabeur:Swiatek:1-6,7-5,6-2
Zverev:Alcaraz:6-0,7-6,6-3
Jabeur:Swiatek:2-6,6-2,6-0
Alcaraz:Zverev:6-3,4-6,6-3,6-4
Swiatek:Jabeur:6-1,3-6,7-5
Zverev:Alcaraz:7-6,4-6,7-6,2-6,6-2
Jabeur:Swiatek:6-4,1-6,6-3
Alcaraz:Zverev:7-5,7-5
Jabeur:Swiatek:3-6,6-3,6-3
EOF
Zverev 3 0 10 104 11 106\n
Alcaraz 1 2 11 106 10 104\n
Jabeur 0 4 9 76 8 74\n
Swiatek 0 2 8 74 9 76
Zverev 3 0 10 104 11 106\n
Alcaraz 1 2 11 106 10 104\n
Jabeur 0 4 9 76 8 74\n
Swiatek 0 2 8 74 9 76\n
Passed after ignoring Presentation Error
Test Case 2
Gauff:Zverev:2-6,6-7,7-6,6-3,6-1
Tsitsipas:Zverev:6-3,4-6,6-4,6-3
Zverev:Thiem:6-0,7-6,6-7,6-3
Thiem:Zverev:6-4,6-4
Gauff:Zverev:2-6,6-2,6-0
Thiem:Zverev:6-3,4-6,6-3,6-4
Zverev:Thiem:7-6,4-6,7-6,2-6,6-2
Thiem:Tsitsipas:7-5,7-5
Gauff:Tsitsipas:3-6,6-3,6-3
Gauff:Thiem:0-6,0-6,6-0,6-0,7-5
Tsitsipas:Thiem:6-3,4-6,7-6,0-6,7-5
EOF
Gauff 2 2 10 75 6 60\n
Zverev 2 0 11 122 16 139\n
Tsitsipas 2 0 7 68 7 71\n
Thiem 1 2 14 133 13 128
Gauff 2 2 10 75 6 60\n
Zverev 2 0 11 122 16 139\n
Tsitsipas 2 0 7 68 7 71\n
Thiem 1 2 14 133 13 128\n
Passed after ignoring Presentation Error
Test Case 3
Djokovic:Nadal:2-6,6-7,7-6,6-3,6-1
Nadal:Djokovic:6-3,4-6,6-4,6-3
Djokovic:Nadal:6-0,7-6,6-7,6-3
Nadal:Djokovic:6-4,6-4
Djokovic:Nadal:2-6,6-2,6-0
Nadal:Djokovic:6-3,4-6,6-3,6-4
Djokovic:Nadal:7-6,4-6,7-6,2-6,6-2
Nadal:Djokovic:7-5,7-5
Williams:Muguruza:3-6,6-3,6-3
Muguruza:Williams:6-4,6-4
Williams:Muguruza:2-6,6-2,6-0
Muguruza:Williams:6-3,4-6,6-4,6-3
Williams:Muguruza:6-0,7-6,6-7,6-3
Muguruza:Williams:6-3,4-6,6-4,6-3
Williams:Muguruza:6-0,7-6,6-7,6-3
Muguruza:Williams:6-3,4-6,6-4,6-3
Williams:Muguruza:6-0,7-6,6-7,6-3
EOF
Williams 3 2 16 160 16 146\n
Muguruza 3 1 16 146 16 160\n
Djokovic 3 1 13 142 16 143\n
Nadal 2 2 16 143 13 142
Williams 3 2 16 160 16 146\n
Muguruza 3 1 16 146 16 160\n
Djokovic 3 1 13 142 16 143\n
Nadal 2 2 16 143 13 142\n
Passed after ignoring Presentation Error






Week 8 Programming Assignment - Longest Palindrome

Due on 2024-03-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".


Find the longest palindrome

(IARCS OPC Archive, K Narayan Kumar, CMI)

As we all know, a palindrome is a word that equals its reverse. Here are some examples of palindromes: malayalam, gag, appa, amma.

We consider any sequence consisting of the letters of the English alphabet to be a word. So axxb,abbba and bbbccddx are words for our purpose. And aaabbaaa, abbba and bbb are examples of palindromes.

By a subword of a word, we mean a contiguous subsequence of the word. For example the subwords of the word abbba are ababbbbaabbbbbbbaabbbbbba and abbba.

In this task you will given a word and you must find the longest subword of this word that is also a palindrome.

For example if the given word is abbba then the answer is abbba. If the given word is abcbcabbacba then the answer is bcabbacb.

Solution hint

Any subword of w that is a palindrome is also a subword when w is reversed.

Input format

The first line of the input contains a single integer N indicating the length of the word. The following line contains a single word of length N, made up of the letters a,b,…, z.

Output format

The first line of the output must contain a single integer indicating the length of the longest subword of the given word that is a palindrome. The second line must contain a subword that is a palindrome and which of maximum length. If there is more than one subword palindrome of maximum length, print the one that is lexicographically smallest (i.e., smallest in dictionary order).

Test Data:

You may assume that 1 ≤ N ≤ 5000. You may further assume that in 30% of the inputs 1 ≤ N ≤ 300.

Example:

We illustrate the input and output format using the above examples:

Sample Input 1:

5
abbba

Sample Output 1:

5
abbba

Sample Input 2:

12
abcbcabbacba

Sample Output 2:

8
bcabbacb
Your last recorded submission was on 2024-03-11, 12:18 IST
Select the Language for this assignment. 
1
# Compute longest common subword using dynamic programming
2
3
# lcw[i][j] is length of longest common subword starting at w1[i], w2[j]
4
#
5
# lcw[m][j] = 0 for all j
6
# lcw[i][n] = 0 for all i
7
# lcw[i][j] = 1 + lcw[i+1][j+1], if w1[i] == w2[j]
8
#             0, otherwise
9
#
10
11
def lcw(w1,w2):
12
    m = len(w1)
13
    n = len(w2)
14
15
    maxlen = 0       # Current maximum length
16
    maxpos = (m,n)   # Position of lexicographically smallest word of max length
17
18
    # For DP, initialize (m+1) x (n+1) matrix lcw[][] with 0's
19
    # This also initializes the base case
20
21
    lcw = [ [0 for j in range(n+1)] for i in range(m+1) ]
22
23
    # Fill in lcw[][] columnwise and rowwise from bottom right corner
24
    for i in range(m-1,-1,-1):
25
        for j in range(n-1,-1,-1):
26
            if w1[i] == w2[j]:
27
                lcw[i][j] = 1 + lcw[i+1][j+1]
28
29
                # Update maxlen and maxpos if maxlen increases
30
                if lcw[i][j] > maxlen:
31
                    maxlen = lcw[i][j]
32
                    maxpos = (i,j)
33
34
                # Update maxpos if we find a lexicographically smaller word
35
                # with length = maxlen
36
                if lcw[i][j] == maxlen:
37
                    if w1[maxpos[0]:maxpos[0]+maxlen] > w1[i:i+maxlen]:
38
                        maxpos = (i,j)
39
            else:
40
                lcw[i][j] = 0
41
42
    return(maxlen,w1[maxpos[0]:maxpos[0]+maxlen])
43
            
44
# main()
45
46
# Read input
47
num = input()  # Discard first line, not needed
48
49
word = input().strip()
50
rword = ''.join(reversed(word))  # Reverse word
51
52
# Compute lcw of word and rword
53
(palinlen,palinpat) = lcw(word,rword)
54
55
# Print answer
56
print(palinlen)
57
print(palinpat)
58
59
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
5
abbba
5\n
abbba
5\n
abbba\n
Passed after ignoring Presentation Error
Test Case 2
12
abcbcabbacba
8\n
bcabbacb
8\n
bcabbacb\n
Passed after ignoring Presentation Error



























































































































































































































































































































































































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.