Hacker Rank - Day 17 : More Exceptions

                   Day 17 : More Exceptions

Solution In Java 8:


import java.util.*;
import java.io.*;

class Calculator{
    int power(int n , int p) throws Exception
    {
            if(n < 0 || p < 0)
            {
                    throw new Exception("n and p should be non-negative");
            }
        return (int)Math.pow(n,p);
    }
}

class Solution{

    public static void main(String []argh)
    {
        Scanner in = new Scanner(System.in);
        int T=in.nextInt();
        while(T-->0)
        {
            int n = in.nextInt();
            int p = in.nextInt();
            Calculator myCalculator = new Calculator();
            try
            {
                int ans=myCalculator.power(n,p);
                System.out.println(ans);
               
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }

    }
}
 


Solution In Python 3: 
class Calculator(Exception):
    def power(self,n,p):
        self.n = n
        self.p = p
        if self.n < 0 or self.p < 0:
            raise Exception("n and p should be non-negative")

        return self.n**self.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)  
Share:

Hacker Rank - Day 16 : Exceptions

                       Day 16 : Exceptions

Solution In Java 8:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.next();
      
        try{
            Integer i = Integer.parseInt(S);
            System.out.println(i);
          
        }catch(NumberFormatException nfe){
            System.out.println("Bad String");
        }
    }
}

Solution In Python 3: 

#!/bin/python3

import sys

try:
    print(int(input()))
except ValueError:
    print("Bad String")
Share:

Hacker Rank - Day 15 : Linked List

                       Day 15 : Linked List

Solution In Java 8:


import java.io.*;
import java.util.*;

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

class Solution {

public static  Node insert(Node head,int data) {
        if(head == null){
            head = new Node(data);
        }
        else{
            Node curr = head;
            while(curr.next!=null){
                curr = curr.next ;
            }
            curr.next = new Node(data);
        }
        return head;
    }
public static void display(Node head) {
        Node start = head;
        while(start != null) {
            System.out.print(start.data + " ");
            start = start.next;
        }
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Node head = null;
        int N = sc.nextInt();

        while(N-- > 0) {
            int ele = sc.nextInt();
            head = insert(head,ele);
        }
        display(head);
        sc.close();
    }
}


Solution In Python 3: 



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):
        if(head == None):
            head = Node(data)
        else:
            curr = head
       
            while curr.next:
                curr = curr.next
            curr.next = Node(data)
        return head    
 
  mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)   
mylist.display(head);
     
Share:

Hacker Rank - Day 12 : Inheritance

                    Hacker Rank - Day 14 : Scope

Solution In Java 8:

import java.util.*;

class Person {
    protected String firstName;
    protected String lastName;
    protected int idNumber;
   
    // Constructor
    Person(String firstName, String lastName, int identification){
        this.firstName = firstName;
        this.lastName = lastName;
        this.idNumber = identification;
    }
   
    // Print person data
    public void printPerson(){
         System.out.println(
                "Name: " + lastName + ", " + firstName
            +     "\nID: " + idNumber);
    }
   
}

class Student extends Person{
    private int[] testScores;
    Student(String firstName , String lastName , int id , int [] testScores){
        super(firstName , lastName , id);
        this.testScores = testScores;
    }
    public String calculate(){
        int sum = 0;
        for(int i = 0; i < testScores.length ; i++){
            sum = sum + testScores[i];
        }
        int avg = sum / testScores.length;
       
        if(avg >= 90 && avg <= 100)
            return "O";
        else if(avg >= 80 && avg < 90)
            return "A";
        else if(avg >= 70 && avg < 80)
            return "E";
        else if(avg >= 55 && avg < 70)
            return "P";
        else if(avg >= 40 && avg < 55)
            return "D";
        else
            return "T";
       
    }
  
}

class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String firstName = scan.next();
        String lastName = scan.next();
        int id = scan.nextInt();
        int numScores = scan.nextInt();
        int[] testScores = new int[numScores];
        for(int i = 0; i < numScores; i++){
            testScores[i] = scan.nextInt();
        }
        scan.close();
       
        Student s = new Student(firstName, lastName, id, testScores);
        s.printPerson();
        System.out.println("Grade: " + s.calculate() );
    }
}
 
Solution In Python 3: 

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):
    def __init__(self,firstName,lastName,ids,testScores):
        super().__init__(firstName,lastName,ids)
        self.testScores = testScores
       
    def calculate(self):
        total = 0
        for testScore in self.testScores:
            total += testScore
        avg = total / len(self.testScores)
        if 90 <= avg <= 100:
            return 'O'
        if 80 <= avg < 90:
            return 'E'
        if 70 <= avg < 80:
            return 'A'
        if 55 <= avg < 70:
            return 'P'
        if 40 <= avg < 55:
            return 'D'
        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())
Share:

Hacker Rank - Day 14 : Scope

                    Hacker Rank - Day 14 : Scope

Solution In Java 8:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;


class Difference {
      private int[] elements;
      public int maximumDifference;
    Difference(int [] elements){
        this.elements = elements ;
    }
    public void computeDifference(){
        int diff = 0 ,maximumDifference1  = 0;
           for(int i = 0 ; i < elements.length ; i++){
               for(int j = i+1 ; j < elements.length ; j++){
                   diff = Math.abs(elements[i] - elements[j]);
                   if(maximumDifference1 < diff){
                       maximumDifference1 = diff ;
                   }
               }
           }
            maximumDifference = maximumDifference1;
    }
} // End of Difference class

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();

        Difference difference = new Difference(a);

        difference.computeDifference();

        System.out.print(difference.maximumDifference);
    }
}
Solution In Python 3: 


Solution will be added later B'coz question has some issues .......

Thank You   :)
Share:

Hacker Rank - Day 13 : Abstract Classes

                    Hacker Rank - Day 13 : Abstract Classes

Solution In Java 8:


import java.util.*;
abstract class Book
{
    String title;
    String author;
    Book(String t,String a){
        title=t;
        author=a;
    }
    abstract void display();


}
class MyBook extends Book{
    int price;
    MyBook(String title , String author , int price){
        super(title,author); 
        this.price = price;
    }
    void display(){
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
    
}
public class Solution
{
   
   public static void main(String []args)
   {
      Scanner sc=new Scanner(System.in);
      String title=sc.nextLine();
      String author=sc.nextLine();
      int price=sc.nextInt();
      Book new_novel=new MyBook(title,author,price);
      new_novel.display();
      
   }
}

Solution In Python 3: 

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

class MyBook(Book):
    def __init__(self,title,author,price):
        self.price = price ;
        super(MyBook,self).__init__(title,author);
        
        
    def display(self):
        print("Title:",self.title)
        print("Author:",self.author)
        print("Price:",self.price)
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
Share:

Hacker Rank - Day 11 : 2D Arrays

                        Day 11 : 2D Arrays

Solution In Java 8:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a[][] = new int[6][6];
        int sum = 0;
        for(int i=0; i < 6; i++){
            for(int j=0; j < 6; j++){
                a[i][j] = in.nextInt();
            }
        }
        int max = -99999;
        
        for(int i = 0 ; i < 4 ; i++){
            for(int j= 0 ; j < 4 ; j++){
                sum = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
                if(sum > 0) 
                {
                    if(sum > max){
                        max =sum;
                    }
                }
                else{
                    if(max < sum ){
                        max = sum;
                    }
                }
            }
            
            
        }
       
      System.out.println(max);  
    }
}

Solution In Python 3: 

import sys


arr = []
maxi = -9999
for arr_i in xrange(6):
   arr_temp = map(int,raw_input().strip().split(' '))
   arr.append(arr_temp)

for i in range(4):
    for j in range(4):
        addition = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
        if(addition > 0):
            if(addition > maxi):
                maxi = addition 
        else:
            if(maxi < addition):
                maxi = addition
print(maxi)            
Share: