HackerRank: 30 Days of Code

August 17, 2022

Day 0: Hello World

  • Instructions:
    • Write a line of code here that prints the contents of input_string to stdout.
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    #!/bin/python3
    
    # Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
    input_string = input()
    
    # Print a string literal saying "Hello, World." to stdout.
    print('Hello, World.')
    
    # TODO: Write a line of code here that prints the contents of input_string to stdout.
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #!/bin/python3
    
    # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. 
    input_string = input()
    
    # Print a string literal saying "Hello, World." to stdout. 
    print('Hello, World.')
    
    # TODO: Write a line of code here that prints the contents of input_string to stdout. 
    print(input_string)
    

Day 1: Data Types

  • Instructions:
    • Given the variables i, d, and s
    • Initialize 3 separate variables from STDIN: one of type int, one of type double, and one of type string
    • Print the sum of i plus your int variable on a new line
    • Print the sum of d plus your double variable to a scale of one decimal place on a new line
    • Concatenate s with the string you read as input and print the result on a new line.
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    i = 4
    d = 4.0
    s = 'HackerRank '
    # Declare second integer, double, and String variables.
    
    # Read and save an integer, double, and String to your variables.
    
    # Print the sum of both integer variables on a new line.
    
    # Print the sum of the double variables on a new line.
    
    # Concatenate and print the String variables on a new line
    # The 's' variable above should be printed first.
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    #!/bin/python3
    
    i = 4
    d = 4.0
    s = 'HackerRank '
    
    # Declare second integer, double, and String variables.
    # Read and save an integer, double, and String to your variables.
    int_eger = input()
    dou_ble = input()
    str_ing = input()
    
    # Print the sum of both integer variables on a new line.
    print(i + int(int_eger))
    
    # Print the sum of the double variables on a new line.
    print(round(d + float(dou_ble),1))
    
    # Concatenate and print the String variables on a new line
    # The 's' variable above should be printed first.
    print(s + str_ing)
    

Day 2: Operators

  • Instructions:
    • Complete the solve function
      • calculate tip, given tip percentage
      • calculate tax, given tax percentage
      • sum the meal cost, tip, and tax and round to the nearest integer
      • print the total
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the 'solve' function below.
    
    # The function accepts following parameters:
    #  1. DOUBLE meal_cost
    #  2. INTEGER tip_percent
    #  3. INTEGER tax_percent
    
    def solve(meal_cost, tip_percent, tax_percent):
        # Write your code here
    
    if __name__ == '__main__':
        meal_cost = float(input().strip())
    
        tip_percent = int(input().strip())
    
        tax_percent = int(input().strip())
    
        solve(meal_cost, tip_percent, tax_percent)
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the 'solve' function below.
    
    # The function accepts following parameters:
    #  1. DOUBLE meal_cost
    #  2. INTEGER tip_percent
    #  3. INTEGER tax_percent
    
    def solve(meal_cost, tip_percent, tax_percent):
        tip = meal_cost/100*tip_percent
        tax = tax_percent/100*meal_cost
        total = round(meal_cost + tip + tax)
        print(total)
    
    if __name__ == '__main__':
        meal_cost = float(input().strip())
    
        tip_percent = int(input().strip())
    
        tax_percent = int(input().strip())
    
        solve(meal_cost, tip_percent, tax_percent)
    

Day 3: Intro to Conditional Statements

  • Instructions:
    • Given an integer n perform the following conditional actions:
      • If n is odd, print Weird
      • If n is even and in the inclusive range of 2 to 5 print Not Weird
      • If n is even and in the inclusive range of 6 to 20 print Weird
      • If n is even and greater than 20 print ‘Not Weird’
    • Constraint:
      • 1 <= n <= 100
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        N = int(input().strip())
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # function that checks to see if a number is even and returns True, False otherwise
    def is_even(num):
        if (num % 2) == 0:
            return True
        else:
            return False
        
    if __name__ == '__main__':
        N = int(input().strip())
        if 1 <= N <= 100:
            if (is_even(N)==False) or ((is_even(N)==True) and (6<=N<=20)):
                print("Weird")
            if (is_even(N)==True) and ((2<=N<=5) or (N>20)):
                print("Not Weird")
    

Day 4: Class vs. Instance

  • Instructions:
    • Use the constructor to verify the parameter initialAge
      • If initialAge is negative, print Age is not valid, setting age to 0. and set the instance variable age to 0
    • Complete the amIOld method
      • if age < 13 print You are young.
      • if 13 <= age < 18 print You are a teenager.
      • otherwise print You are old.
    • Complete the yearPasses method by incrementing the age instance variable by 1
    • Contraints:
      • 1 <= t <= 4
      • 5 <= age <= 30
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    class Person:
        def __init__(self,initialAge):
            # Add some more code to run some checks on initialAge
    
        def amIOld(self):
            # Do some computations in here and print out the correct statement to the console
    
        def yearPasses(self):
            # Increment the age of the person in here
    
    t = int(input())
    
    for i in range(0, t):
        age = int(input())         
        p = Person(age)  
        p.amIOld()
        for j in range(0, 3):
            p.yearPasses()       
        p.amIOld()
        print("")
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    
    #!/bin/python3
    
    class Person:
        def __init__(self,initialAge):
            # Add some more code to run some checks on initialAge
            if initialAge < 0:
                print("Age is not valid, setting age to 0.")
                self.age = 0
            else:
                self.age = initialAge
    
        def amIOld(self):
            # Do some computations in here and print out the correct statement to the console
            if self.age < 13:
                print("You are young.")
            elif 13 <= self.age < 18:
                print("You are a teenager.")
            else:
                print("You are old.")
    
        def yearPasses(self):
            # Increment the age of the person in here
            self.age+=1
            
    t = int(input())
    
    for i in range(0, t):
        age = int(input())         
        p = Person(age)  
        p.amIOld()
        for j in range(0, 3):
            p.yearPasses()       
        p.amIOld()
        print("")
    

Day 5: Loops

  • Instructions:
    • print the first 10 multiples of n x i using the format n x i = result
    • Constraints:
      • 1 <= i <= 10
      • 2 <= n <= 20
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
        for i in range(1,11):
            print("{} x {} = {}".format(n,i,n * i))
    

Day 6: Let’s Review

  • Instructions:
    • Given a string s of length N that is indexed from 0 to N - 1, print it’s even-indexed and odd-indexed characters as space-separated strings on a single line
    • Example: s = adbecf prints out: abc def
    • Constraints
      • 1 <= t <= 10 : (t is number of test cases)
      • 2 < length of s <= 10000
    Excercise
    1
    
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    #!/bin/python3
    
    if __name__ == '__main__':
        # number of strings user will provide
        numStrings = int(input())
        count = 0
        strings = []
    
        # get strings from user and append to strings array 
        while count != numStrings:
            s = str(input())
            strings.append(s)
            count+=1
        
        x = 0
        evens = ""
        odds = ""
    
        # loop through elements in strings array
        while x < len(strings):
            y = 0
            # loop through characters in element
            while y < len(strings[x]):
                if y%2==0:
                    evens+=strings[x][y]
                else:
                    odds+=strings[x][y]     
                y+=1
            print("{} {}".format(evens,odds))
            evens = ""
            odds = ""
            x+=1
    

Day 7: Arrays

  • Instructions:
    • Given an array of N integers, print the integers in reverse order on a single line with a space between each character
    • Constraints:
      • 1 <= N <= 1000
      • 1 <= A[i] <= 1000, where A[i] is the i'th integer of the array
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
        arr = list(map(int, input().rstrip().split()))
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
        arr = list(map(int, input().rstrip().split()))
    
        x = len(arr)-1
        s = ""
    
        while x >= 0:
            s+= "{} ".format(arr[x])
            x-=1
    
        print(s)
    

Day 8: Dictionaries and Maps

  • Instructions:
    • Given n names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers.
    • Given an unknown number of names to query, print the associated entry from the phone book on a new line in the form name=phoneNumber
    • If an entry for name is not found, print Not found
    • Phone book should be a Dictionary/Map/HashMap data structure
    • Constraints:
      • 1 <= n <= 10^5
      • 1 <= queries <= 10^5
    Excercise
    1
    
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    #!/bin/python3
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    
    if __name__ == '__main__':
        n = int(input())
        
        phoneBook=dict(input().split(' ',2) for _ in range(n))
        
        while True:
            try:
                name = str(input())
                if name in phoneBook.keys():
                    print("{}={}".format(name,phoneBook[name]))
                else:
                    print("Not found")
            except:
                break
    

Day 9: Recursion

  • Instructions:
    • Complete function method called factorial that recursively calculates factorial of given integer n
    • Constraint:
      • 2 <= n <= 12
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the 'factorial' function below.
    
    # The function is expected to return an INTEGER.
    # The function accepts INTEGER n as parameter.
    
    def factorial(n):
        # Write your code here
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        result = factorial(n)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the 'factorial' function below.
    
    # The function is expected to return an INTEGER.
    # The function accepts INTEGER n as parameter.
    
    
    def factorial(n):
        if n > 1:
            n = n * factorial(n-1) 
        return n
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input().strip())
    
        result = factorial(n)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()
    

Day 10: Binary Numbers

  • Instructions:
    • Given a base-10 integer n convert it to base-2 (binary)
    • Find and print the base-10 integer denoting the maximum number of consecutive 1s in n’s binary representation
    • Constraint:
      • 1 <= n <= 10^6
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    def binary(decimal,string):
        while decimal != 0:
            string+=str(decimal % 2)
            decimal = decimal//2
            binary(decimal,string)
        return string
    
    def count_ones(binary):
        count = 0
        max_count = 0
        for x in range(0,len(binary)):
            if binary[x] == '1':
                count+=1
                if count > max_count:
                    max_count = count
            elif binary[x] == '0':
                count = 0
        return max_count
            
    if __name__ == '__main__':
        n = int(input().strip())
        s = ''
        b = binary(n,s)
        number_of_ones = count_ones(b)    
        print(number_of_ones)
    

Day 11: 2D Arrays

  • Instructions:
    • Given a 6 x 6 2D Array, A:
      • 1 1 1 0 0 0
      • 0 1 0 0 0 0
      • 1 1 1 0 0 0
      • 0 0 2 4 4 0
      • 0 0 0 2 0 0
      • 0 0 1 2 4 0
    • Calculate the hourglass sum for every hourglass in A
    • Then print the maximum hourglass sum
    • An hourglass is defined as a subset of values with indices falling in the following graphical representation:
      • 1 1 1
      •    1
      • 1 1 1
    • There are 16 hourglasses in A and an hourglass sum is the sum of an hourglass’ values
    • In the array above, the maximum hourglass sum is 19 for the hourglass
      • 2 4 4
      •    2
      • 1 2 4
    • Constraints:
      • 9 <= A[i][j] <= 9
      • 0 <= i,j <= 5
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
    
        arr = []
    
        for _ in range(6):
            arr.append(list(map(int, input().rstrip().split())))
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    def findMax(array):
        d ={}
        for n in range(1,17):
            d['hourglass{}'.format(n)] = 0
            
        x = 0
        y = 0
        while y < 6:
            while x < 6:
                n = array[y][x]
                if 0 <= x <= 2 and 0 <= y <= 2:
                    if y == 1 and x != 1:
                        pass
                    else:
                        d['hourglass1'] += n
                if 1 <= x <= 3 and 0 <= y <= 2:
                    if y == 1 and x != 2:
                        pass
                    else:
                        d['hourglass2'] += n
                if 2 <= x <= 4 and 0 <= y <= 2:
                    if y == 1 and x != 3:
                        pass
                    else:
                        d['hourglass3'] += n
                if 3 <= x <= 5 and 0 <= y <= 2:
                    if y == 1 and x != 4:
                        pass
                    else:
                        d['hourglass4'] += n
                if 0 <= x <= 2 and 1 <= y <= 3:
                    if y == 2 and x != 1:
                        pass
                    else:
                        d['hourglass5'] += n
                if 1 <= x <= 3 and 1 <= y <= 3:
                    if y == 2 and x != 2:
                        pass
                    else:
                        d['hourglass6'] += n
                if 2 <= x <= 4 and 1 <= y <= 3:
                    if y == 2 and x != 3:
                        pass
                    else:
                        d['hourglass7'] += n
                if 3 <= x <= 5 and 1 <= y <= 3:
                    if y == 2 and x != 4:
                        pass
                    else:
                        d['hourglass8'] += n
                if 0 <= x <= 2 and 2 <= y <= 4:
                    if y == 3 and x != 1:
                        pass
                    else:
                        d['hourglass9'] += n
                if 1 <= x <= 3 and 2 <= y <= 4:
                    if y == 3 and x != 2:
                        pass
                    else:
                        d['hourglass10'] += n
                if 2 <= x <= 4 and 2 <= y <= 4:
                    if y == 3 and x != 3:
                        pass
                    else:
                        d['hourglass11'] += n
                if 3 <= x <= 5 and 2 <= y <= 4:
                    if y == 3 and x != 4:
                        pass
                    else:
                        d['hourglass12'] += n
                if 0 <= x <= 2 and 3 <= y <= 5:
                    if y == 4 and x != 1:
                        pass
                    else:
                        d['hourglass13'] += n
                if 1 <= x <= 3 and 3 <= y <= 5:
                    if y == 4 and x != 2:
                        pass
                    else:
                        d['hourglass14'] += n
                if 2 <= x <= 4 and 3 <= y <= 5:
                    if y == 4 and x != 3:
                        pass
                    else:
                        d['hourglass15'] += n
                if 3 <= x <= 5 and 3 <= y <= 5:
                    if y == 4 and x != 4:
                        pass
                    else:
                        d['hourglass16'] += n                        
                x+=1
            y+=1
            x=0
            
        allValues = d.values()
        return(max(allValues))
                
    if __name__ == '__main__':
    
        arr = []
     
        for _ in range(6):
            arr.append(list(map(int, input().rstrip().split())))
    
        print(findMax(arr))  
    

Day 12: Inheritance

  • Instructions:
    • Given 2 classes, Person and Student where:
      • Person is the base class and Student is the derived class
    • Complete the Student class by writing the following:
      • A Student constructor with 4 parameters:
      • 2 strings firstName & lastName
      • an integer idNumber
      • an integer array (or vector) of test scores, scores
    • A calculate() method that calculates a Student object’s average and returns the grade character representative of their calculated average
    • Constraints:
      • 1 <= length of firstName
      • length of lastName <= 10
      • length of idNumber <= 7
      • 0 <= score <= 100
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    
    class Person:
        def __init__(self, firstName, lastName, idNumber):
            self.firstName = firstName
            self.lastName = lastName
            self.idNumber = idNumber
        def printPerson(self):
            print("Name:", self.lastName + ",", self.firstName)
            print("ID:", self.idNumber)
    
    class Student(Person):
        #   Class Constructor
    
        #   Parameters:
        #   firstName - A string denoting the Person's first name.
        #   lastName - A string denoting the Person's last name.
        #   id - An integer denoting the Person's ID number.
        #   scores - An array of integers denoting the Person's test scores.
    
        # Write your constructor here
        
    
        #   Function Name: calculate
        #   Return: A character denoting the grade.
        #
        # Write your function here
    
    line = input().split()
    firstName = line[0]
    lastName = line[1]
    idNum = line[2]
    numScores = int(input()) # not needed for Python
    scores = list( map(int, input().split()) )
    s = Student(firstName, lastName, idNum, scores)
    s.printPerson()
    print("Grade:", s.calculate())
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    
    class Person:
        def __init__(self, firstName, lastName, idNumber):
            self.firstName = firstName
            self.lastName = lastName
            self.idNumber = idNumber
        def printPerson(self):
            print("Name:", self.lastName + ",", self.firstName)
            print("ID:", self.idNumber)
    
    class Student(Person):
        #   Class Constructor
        #   
        #   Parameters:
        #   firstName - A string denoting the Person's first name.
        #   lastName - A string denoting the Person's last name.
        #   id - An integer denoting the Person's ID number.
        #   scores - An array of integers denoting the Person's test scores.
        #
        # Write your constructor here
        def __init__(self,firstName,lastName,idNumber, scores):
            super().__init__(firstName, lastName, idNumber)
            self.scores = scores
        #   Function Name: calculate
        #   Return: A character denoting the grade.
        #
        # Write your function here
        def calculate(self):
            average = sum(self.scores)/len(self.scores)
            if 90 <= average <=100:
                return('O')
            elif 80 <= average < 90:
                return('E')
            elif 70 <= average < 80:
                return('A')
            elif 55 <= average < 70:
                return('P')
            elif 40 <= average < 55:
                return('D')
            elif average < 40:
                return('T')
    
    line = input().split()
    firstName = line[0]
    lastName = line[1]
    idNum = line[2]
    numScores = int(input()) # not needed for Python
    scores = list( map(int, input().split()) )
    s = Student(firstName, lastName, idNum, scores)
    s.printPerson()
    print("Grade:", s.calculate())
    

Day 13: Abstract Classes

  • Instructions:
    • Given a Book class and a Solution class, write a MyBook class that does the following:
      • Inherits from Book
      • Has a parameterized constructor taking 3 parameters:
        • 2 strings title & author
        • int price
      • Implements the Book class’ abstract display() method so it prints 3 lines:
        • Title: instance title
        • Author: instance author
        • Price: instance price
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    from abc import ABCMeta, abstractmethod
    class Book(object, metaclass=ABCMeta):
        def __init__(self,title,author):
            self.title=title
            self.author=author   
        @abstractmethod
        def display(): pass
    
    #Write MyBook class
    
    title=input()
    author=input()
    price=int(input())
    new_novel=MyBook(title,author,price)
    new_novel.display()
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    from abc import ABCMeta, abstractmethod
    class Book(object, metaclass=ABCMeta):
        def __init__(self,title,author):
            self.title=title
            self.author=author   
        @abstractmethod
        def display(): pass
    
    #Write MyBook class
    class MyBook(Book):
        def __init__(self,title,author,price):
            super().__init__(title,author)
            self.price = price
            
        def display(self):
            print("Title: {}".format(self.title))
            print("Author: {}".format(self.author))
            print("Price: {}".format(self.price))
    
    title=input()
    author=input()
    price=int(input())
    new_novel=MyBook(title,author,price)
    new_novel.display()
    

Day 14: Scope

  • Instructions:
    • Complete the difference class by writig the following:
      • A classconstructor that takes an array of integers as a parameter and saves it to the __elements instance variable
      • A computeDifference method that finds the maximum absolute difference between any 2 numbers in __elements and stores it in the maximumDifference instance variable
      • The difference class has a private integer array elements for storing N non-negative integers, and a public integer maximumDifference for storing the maximum absolute difference
        • The maximum absolute difference between two integers in a set of positive integers, elements, is the largest absolute difference |a - b| between any two integers, a and b, in __elements.
    • Constraints:
      • 1 <= N <= 10
      • 1 <= __elements[i] <= 100 where 0 <= i <= N-1
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    class Difference:
        def __init__(self, a):
            self._elements = a
    
        # Add your code here
    
    # End of Difference class
    
    _ = input()
    a = [int(e) for e in input().split(' ')]
    
    d = Difference(a)
    d.computeDifference()
    
    print(d.maximumDifference)
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    class Difference:
        def __init__(self, a):
            self.__elements = a
    
        # Add your code here
        def computeDifference(self):
            smallest = self.__elements[0]
            largest = self.__elements[0]
            for x in range(0,len(self.__elements)):
                if self.__elements[x] < smallest:
                    smallest = self.__elements[x]
                if self.__elements[x] > largest:
                    largest = self.__elements[x]
            self.maximumDifference = abs(smallest - largest)
    # End of Difference class
    
    _ = input()
    a = [int(e) for e in input().split(' ')]
    
    d = Difference(a)
    d.computeDifference()
    
    print(d.maximumDifference)
    

Day 15: Linked List

  • Instructions:
    • Complete the insert function such that it creates a new Node (data is passed as Node constructor argument) and inserts it at the tail end of the linked list referenced by the head parameter.
    • Once the new node is added, return the reference to the head node
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    class Node:
        def __init__(self,data):
            self.data = data
            self.next = None 
    class Solution: 
        def display(self,head):
            current = head
            while current:
                print(current.data,end=' ')
                current = current.next
    
        def insert(self,head,data): 
        #Complete this method
    
    mylist= Solution()
    T=int(input())
    head=None
    for i in range(T):
        data=int(input())
        head=mylist.insert(head,data)    
    mylist.display(head);  
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    #!/bin/python3
    
    class Node:
        def __init__(self,data):
            self.data = data
            self.next = None 
    class Solution: 
        def display(self,head):
            current = head
            while current:
                print(current.data,end=' ')
                current = current.next
    
        def insert(self,head,data): 
        #Complete this method
            print(data, end= ' ')
    
    mylist= Solution()
    T=int(input())
    head=None
    for i in range(T):
        data=int(input())
        head=mylist.insert(head,data)    
    mylist.display(head);
    

Day 16: Exceptions - String to Integer

  • Instructions:
    • Read a string S and print it’s integer value
    • if S cannot be converted to an integer, print Bad String
    • use String-to-Integer exception handling instead of loops/conditional statements
    • Constraints:
      • 1 <= |S| <= 6 : |S| is length of string S
      • S is composed of either lowercase letters (a-z) or decimal digits (0-9)
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        S = input()
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    S = input().strip()
    try:
        print(int(S))
    except ValueError:
        print("Bad String")
    

Day 17: More Exceptions

  • Instructions:
    • Write a Calculator class with a single method: int power(int,int)
    • The power method takes two integers n & p as parameters and returns the integer result of n^p
    • If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    #Write your code here
    
    myCalculator=Calculator()
    T=int(input())
    for i in range(T):
        n,p = map(int, input().split())
        try:
            ans=myCalculator.power(n,p)
            print(ans)
        except Exception as e:
            print(e) 
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    #!/bin/python3
    
    #Write your code here
    
    class Calculator:
        def power(self,n,p):
            Error = ValueError('n and p should be non-negative')
            self.n = n
            self.p = p
            if self.n < 0 or self.p < 0:
                raise Error
            else:
                return n ** p
    
    myCalculator=Calculator()
    T=int(input())
    for i in range(T):
        n,p = map(int, input().split())
        try:
            ans=myCalculator.power(n,p)
            print(ans)
        except Exception as e:
            print(e) 
    

Day 18: Queues and Stacks

  • Instructions:
    • Determine if a given string s is a palindrome (word, phrase, number, or other sequence of characters which reads the same backwards and forwards)
    • First take each character in s, enqueue it in a queue, and also push that same character onto a stack.
    • Then dequeue the first character from the queue and pop the top character off the stack, then compare the two characters to see if they are the same; as long as the characters match, we continue dequeueing, popping, and comparing each character until our containers are empty (a non-match means isn’t a palindrome).
    • Constraint:
      • s is composed of lowercase English letters.
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    import sys
    
    class Solution:
        # Write your code here
    
    # read the string s
    s=input()
    #Create the Solution class object
    obj=Solution()   
    
    l=len(s)
    # push/enqueue all the characters of string s to stack
    for i in range(l):
        obj.pushCharacter(s[i])
        obj.enqueueCharacter(s[i])
        
    isPalindrome=True
    '''
    pop the top character from stack
    dequeue the first character from queue
    compare both the characters
    ''' 
    for i in range(l // 2):
        if obj.popCharacter()!=obj.dequeueCharacter():
            isPalindrome=False
            break
    #finally print whether string s is palindrome or not.
    if isPalindrome:
        print("The word, "+s+", is a palindrome.")
    else:
        print("The word, "+s+", is not a palindrome.")   
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    import sys
    
    class Solution:
        # Write your code here
        def __init__(self):
            self.stack = []
            self.queue = []
        
        def pushCharacter(self, char):
            self.stack.insert(0,char)
        
        def popCharacter(self):
            return self.stack.pop(0)
            
        def enqueueCharacter(self,char):
            self.queue.append(char)
            
        def dequeueCharacter(self):
            return self.queue.pop(0)
          
    # read the string s
    s=input()
    #Create the Solution class object
    obj=Solution()   
    
    l=len(s)
    # push/enqueue all the characters of string s to stack
    for i in range(l):
        obj.pushCharacter(s[i])
        obj.enqueueCharacter(s[i])
        
    isPalindrome=True
    '''
    pop the top character from stack
    dequeue the first character from queue
    compare both the characters
    ''' 
    for i in range(l // 2):
        if obj.popCharacter()!=obj.dequeueCharacter():
            isPalindrome=False
            break
    #finally print whether string s is palindrome or not.
    if isPalindrome:
        print("The word, "+s+", is a palindrome.")
    else:
        print("The word, "+s+", is not a palindrome.")
    

Day 19: Interfaces

  • Instructions:
    • Complete the implementation of Calculator class, which implements the AdvancedArithmetic interface.
    • The implementation for the divisorSum(n) method must return the sum of all divisors of n
    • Example:
      • n = 20, The divisors of 20 are 1,2,4,5,10,20
    • Constraint:
      • 1 <= n <= 1000
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    class AdvancedArithmetic(object):
        def divisorSum(n):
            raise NotImplementedError
    
    class Calculator(AdvancedArithmetic):
        def divisorSum(self, n):
            pass
    
    
    n = int(input())
    my_calculator = Calculator()
    s = my_calculator.divisorSum(n)
    print("I implemented: " + type(my_calculator).__bases__[0].__name__)
    print(s)
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    class AdvancedArithmetic(object):
        def divisorSum(n):
            raise NotImplementedError
    
    class Calculator(AdvancedArithmetic):
        def divisorSum(self, n):
            if n == 0 or n==1:
                return n
            else:
                list_of_divisors = []
                list_of_divisors.extend([1,n])
                max_divisor = n//2
                for i in range(2,max_divisor+1):
                    if n%i == 0:
                        list_of_divisors.append(i)
            return sum(list_of_divisors)
    
    
    n = int(input())
    my_calculator = Calculator()
    s = my_calculator.divisorSum(n)
    print("I implemented: " + type(my_calculator).__bases__[0].__name__)
    print(s)
    

Day 20: Sorting

  • Instructions:
    • Given an array a of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm
    • Once sorted, print the following lines:
      • Array is sorted in numSwaps swaps, where numSwaps is the number of swaps that took place.
      • First Element: firstElement, where firstElement is the first element in the sorted array.
      • Last Element: lastElement, where lastElement is the last element in the sorted array.
    • The first line of input contains an integer, n, the number of elements in array a
    • The second line of input contains n space-separated integers that describe a[0],a[1],...,a[n-1]
    • Constraints:
      • 2 <= n <= 600
      • 1 <= a[i] <= 2 x 10^6, where 0 <= i < n
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
    
        # Write your code here
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    if __name__ == '__main__':
        n = int(input().strip())
    
        a = list(map(int, input().rstrip().split()))
    
        # Write your code here
        iteration_count = 0
        for i in range(n):
            for idx in range(n - i - 1):
                if a[idx] > a[idx+1]:
                    a[idx], a[idx+1] = a[idx+1], a[idx]
                    iteration_count += 1
                    
        print("Array is sorted in {0} swaps.".format(iteration_count))
        print("First Element:",a[0])
        print("Last Element:",a[-1])
    

Day 22: Binary Search Trees

  • Instructions:
    • The height of a binary search tree is the number of edges between the tree’s root and its furthest leaf.
    • You are given a pointer, root, pointing to the root of a binary search tree.
    • Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
    • The first line of input contains an integer, n, denoting the number of nodes in the tree.
    • Each of the n subsequent lines of input contain an integer, data, denoting the value of an element that must be added to the BST.
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    class Node:
        def __init__(self,data):
            self.right=self.left=None
            self.data = data
    class Solution:
        def insert(self,root,data):
            if root==None:
                return Node(data)
            else:
                if data<=root.data:
                    cur=self.insert(root.left,data)
                    root.left=cur
                else:
                    cur=self.insert(root.right,data)
                    root.right=cur
            return root
    
        def getHeight(self,root):
            #Write your code here
    
    T=int(input())
    myTree=Solution()
    root=None
    for i in range(T):
        data=int(input())
        root=myTree.insert(root,data)
    height=myTree.getHeight(root)
    print(height) 
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    class Node:
        def __init__(self,data):
            self.right=self.left=None
            self.data = data
    class Solution:
        def insert(self,root,data):
            if root==None:
                return Node(data)
            else:
                if data<=root.data:
                    cur=self.insert(root.left,data)
                    root.left=cur
                else:
                    cur=self.insert(root.right,data)
                    root.right=cur
            return root
    
        def getHeight(self,root,height=0, a_set=None):
            if root is None:
                return "None"
            root.height = height
            if a_set == None:
                a_set = set()
                a_set.add(height)
                
            if root.left is not None:
                root.left.height = height + 1
                a_set.add(root.left.height)
                self.getHeight(root.left, root.left.height,a_set)
                
            if root.right is not None:
                root.right.height = height + 1
                a_set.add(root.right.height)
                self.getHeight(root.right, root.right.height,a_set)
        
            if root.height == 0:
                return max(a_set)
                
    T=int(input())
    myTree=Solution()
    root=None
    for i in range(T):
        data=int(input())
        root=myTree.insert(root,data)
    height=myTree.getHeight(root)
    print(height)
    

Day 23: BST Level-Order Traversal

  • Instructions:
    • A level-order traversal, also known as a breadth-first search, visits each level of a tree’s nodes from left to right, top to bottom.
    • You are given a pointer, root, pointing to the root of a binary search tree.
    • Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.
    • The first line of input contains an integer, T (the number of test cases).
    • The T subsequent lines each contain an integer, data, denoting the value of an element that must be added to the BST.
    • Constraints:
      • 1 <= N <= 20
      • 1 <= node.data[i] <= 100
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    import sys
    
    class Node:
        def __init__(self,data):
            self.right=self.left=None
            self.data = data
    class Solution:
        def insert(self,root,data):
            if root==None:
                return Node(data)
            else:
                if data<=root.data:
                    cur=self.insert(root.left,data)
                    root.left=cur
                else:
                    cur=self.insert(root.right,data)
                    root.right=cur
            return root
    
        def levelOrder(self,root):
            #Write your code here
    
    T=int(input())
    myTree=Solution()
    root=None
    for i in range(T):
        data=int(input())
        root=myTree.insert(root,data)
    myTree.levelOrder(root)
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    
    import sys
    
    class Node:
        def __init__(self,data):
            self.right=self.left=None
            self.data = data
    class Solution:
        def insert(self,root,data):
            if root==None:
                return Node(data)
            else:
                if data<=root.data:
                    cur=self.insert(root.left,data)
                    root.left=cur
                else:
                    cur=self.insert(root.right,data)
                    root.right=cur
            return root
    
        def levelOrder(self,root,lst=None):
            print(root.data)
            if lst == None:
                lst = []
                lst.append(root.data)
                
            if root.left is not None:
                lst.append(root.left.data)
                  
            if root.right is not None:
                lst.append(root.right.data)
                
            if root.left is not None: 
                self.levelOrder(root.left, lst)
                
            if root.right is not None: 
                self.levelOrder(root.right, lst)
            
            print(lst)  
    
    T=int(input())
    myTree=Solution()
    root=None
    for i in range(T):
        data=int(input())
        root=myTree.insert(root,data)
    myTree.levelOrder(root)
    

Day 24: More Linked Lists

  • Instructions:
    • A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).
    • A removeDuplicates function is declared in your editor, which takes a pointer to the node of a linked list as a parameter.
    • Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list.
    • The first line of input contains an integer, N, the number of nodes to be inserted.
    • The N subsequent lines each contain an integer describing the data value of a node being inserted at the list’s tail.
    • Contraint:
      • The data elements of the linked list argument will always be in non-decreasing order.
    Excercise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    
    class Node:
        def __init__(self,data):
            self.data = data
            self.next = None 
    class Solution: 
        def insert(self,head,data):
                p = Node(data)           
                if head==None:
                    head=p
                elif head.next==None:
                    head.next=p
                else:
                    start=head
                    while(start.next!=None):
                        start=start.next
                    start.next=p
                return head  
        def display(self,head):
            current = head
            while current:
                print(current.data,end=' ')
                current = current.next
    
        def removeDuplicates(self,head):
            #Write your code here
    
    mylist= Solution()
    T=int(input())
    head=None
    for i in range(T):
        data=int(input())
        head=mylist.insert(head,data)    
    head=mylist.removeDuplicates(head)
    mylist.display(head); 
    
    Solution
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    
    class Node:
        def __init__(self,data):
            self.data = data
            self.next = None 
    class Solution: 
        def insert(self,head,data):
                p = Node(data)           
                if head==None:
                    head=p
                elif head.next==None:
                    head.next=p
                else:
                    start=head
                    while(start.next!=None):
                        start=start.next
                    start.next=p
                return head  
        def display(self,head):
            current = head
            while current:
                print(current.data,end=' ')
                current = current.next
    
        def removeDuplicates(self,head):
            current = head
            while current:
                if current.next != None:
                    if current.next.data != current.data:
                        current = current.next
                    else:
                        next_node = current.next.next
                        current.next = None
                        current.next = next_node
                else:
                    return head
                
    mylist= Solution()
    T=int(input())
    head=None
    for i in range(T):
        data=int(input())
        head=mylist.insert(head,data)    
    head=mylist.removeDuplicates(head)
    mylist.display(head);