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:

Hacker Rank - Day 10 : Binary Numbers

                        Day 10 :Binary Numbers

Solution In Java 8:

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

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Long n_to_b = Long.parseLong(Integer.toBinaryString(n));
        int  max = 0, cnt = 0;
        Long n_to_b1 = n_to_b ;
        while(n_to_b1>0)
            {
            Long rem = n_to_b1 % 10;
            if(rem == 1)
                {
                cnt++;
            }
            else{
                cnt = 0;
            }
            if(cnt > max)
                {
                max = cnt;
            }
            n_to_b1 = n_to_b1 / 10;
        }
      
        System.out.print(max);
    }
}
Solution In Python 3: 


#!/bin/python3
no = int(input())
n_to_b = "{0:b}".format(no)
N_TO_B = str(n_to_b)
cnt = 0
maxi = 0
n = N_TO_B
for i in n:
    if(i == '1'):
        cnt=cnt+1
    else:
        cnt = 0
    if(cnt > maxi):
        maxi = cnt
print(maxi)      
Share:

Hacker Rank - Day 9 : Recursion

                        Day 9 :Recursion

Solution In Java 8:

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

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int ans;
        int n = sc.nextInt();
        ans = factorial(n);
        System.out.println(ans);
    }
       public static int factorial(int n){
            if(n == 1){
                return 1;
            }
            else{
                return (n * factorial(n-1));
            }
        }
    }



Solution In Python 3: 



n = int(input().strip())

def factorial(n):
    if n is 1:
        return 1
    else:
        return (n) * factorial(n-1)

ans = factorial(n)
print(ans)
Share:

Hacker Rank - Day 8 : Dictionaries and Maps

                        Day 8 :Dictionaries and Maps

Solution In Java 8:

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

class Solution{
    public static void main(String []argh){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        HashMap <String,Integer> hm = new HashMap<String,Integer>();
        for(int i = 0; i < n; i++){
            String name = in.next();
            int phone = in.nextInt();
            hm.put(name,phone);
          
        }
        while(in.hasNext()){
            String s = in.next();
            if(hm.containsKey(s))
                {
                System.out.println(s+"="+hm.get(s));
            }
            else{
                System.out.println("Not found");
            }
        }
        in.close();
    }
}

Solution In Python 3: 

n = int(input().strip())
D = {}
for x in range(n):
    l = input()
    k,v = l.split()
    D[k] = v
  
for x in range(len(D)):
    l = input()
    if l in D.keys():
        print("{}={}".format(l ,D[l]))
    else:
        print("Not found")
Share:

Hacker Rank - Day 7 : Arrays

                        Day 4 :Class vs. Instance

Solution In Java 8:

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


public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] arr = new int[n];
        for(int i=0; i < n; i++){
            arr[i] = in.nextInt();
        }
        for(int j = n-1;j >= 0;j--)
            {
            System.out.print(arr[j]+" "); 
        }
  
        in.close();
    }
}

Solution In Python 3: 


import sys

n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
for i in range(n-1, -1, -1):
    print(arr[i],end=" ")
   
   
Share:

Hacker Rank - Day 6 : Let's Review

                        Day 6 :Lets Review

Solution In Java 8:

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

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int T = scan.nextInt();
        scan.nextLine();
        for(int i = 0;i < T ;i++ )
            {
            String s = scan.nextLine();
            for(int j = 0;j < s.length() ; j+=2)
                {
                System.out.print(s.charAt(j));
            }
            System.out.print(" ");
            for(int j = 1;j < s.length() ; j+=2)
                {
                System.out.print(s.charAt(j));
            }
            System.out.println();
        }
    }
}

Solution In Python 3: 

n = int (input())
s1 = input()
s2 = input()

for i in range(0,len(s1),2):
    print(s1[i],end="")

print(" ",end = "")
for i in range(1,len(s1),2):
    print(s1[i],end="")
  
print("")
for i in range(0,len(s2),2):
    print(s2[i],end="")

print(" ",end = "")
for i in range(1,len(s2),2):
    print(s2[i],end="")
  
print("")
Share:

Hacker Rank - Day 5 : Loops

                        Day 5 : Loops

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 n = in.nextInt();
        int i = 1;
        while(i<=10)
            {
             
            System.out.println(n+" x "+i+" = "+n*i);
            i++;
        }
    }
}

Solution In Python 3: 
#!/bin/python3

import sys


n = int(input().strip())
if n>=2 and n<=20:
    for i in range(1,11):
        print("%d x %d = %d"%(n ,i,(n*i)))
Share:

Hacker Rank - Day 4 : Class vs. Instance

                        Day 4 :Class vs. Instance

Solution In Java 8:

import java.io.*;
import java.util.*;
public class Person {
    private int age; 

    public Person(int initialAge) {
          this.age = initialAge;
        if(age<0)
        {
            age = 0;
            System.out.println("Age is not valid, setting age to 0.");
        }
    }

    public void amIOld() {
        String str = "";
        if(age < 13)
        {
            str = "You are young."; 
        }
        else if(age >= 13 && age < 18)
        {
            str = "You are a teenager."; 
        }
        else
        {
            str = "You are old."; 
        }
        System.out.println(str);
    }

    public void yearPasses() {
          age ++;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for (int i = 0; i < T; i++) {
            int age = sc.nextInt();
            Person p = new Person(age);
            p.amIOld();
            for (int j = 0; j < 3; j++) {
                p.yearPasses();
            }
            p.amIOld();
            System.out.println();
        }
        sc.close();
    }
}

Solution In Python 3: 

class Person:
    def __init__(self, initialAge):
        if initialAge > 0:
            self.age = initialAge
        else:
            print("Age is not valid, setting age to 0.")
            self.age = 0
    def amIOld(self):
        if self.age < 13:
            print("You are young.")
        elif self.age < 18:
            print("You are a teenager.")
        else:
        print("You are old.")
    def yearPasses(self):
            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("")           
Share:

Hacker Rank - Day 3 : Intro to Conditional Statements

                        Day 3 :Intro to Conditional Statements.

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 scan = new Scanner(System.in);
      int n = scan.nextInt();
      scan.close();
      String ans="";
        
      if(n%2==1){
         ans = "Weird";
      }
      else if (n>=2 && n<=5){
             ans = "Not Weird";
      }
      else if (n>=6 && n<=20){
          ans = "Weird";
      }
       else{
           ans = "Not Weird";
       }
      System.out.println(ans);
   }
}

Solution In Python 3: 

import sys
N = int(input().strip())
if N%2!=0:
    print("Weird")
elif N>=2 and N<=5:
    print("Not Weird")
elif N>=6 and N<=20:
    print("Weird")
else:
    print("Not Weird")
Share:

Hacker Rank - Day 2 : Operators

                        Day 2 :Operators.

Solution In Java 8:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Arithmetic {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double mealCost = scan.nextDouble();
        int tipPercent = scan.nextInt();
        int taxPercent = scan.nextInt();
        scan.close();
        double tip = mealCost*((double)tipPercent/100);
        double tax = mealCost*((double)taxPercent/100);
        Double cost = (Double) mealCost + tip + tax ;
        int totalCost = (int) Math.round(cost);
        System.out.println("The total meal cost is "+totalCost+ " dollars.");
    
    
    }
}

Solution In Python 3:

mealCost = float(input())
tipPercent = float(input())
taxPercent = float(input())

Cost = mealCost + (tipPercent/100)*mealCost + (taxPercent/100)*mealCost
round(Cost)
print("The total meal cost is %d dollers."%Cost)


The Solution is Corrent But the Compiler at Hacker Rank Shows Wrong Answer '

Wll be back at this SOON :)

Share:

Hacker Rank - Day 1 : Data Types

                        Day 1 :Data Types.

Solution In Java 8:

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

public class Solution
{
    public static void main(String[] args)
    {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);
       
        int i2 = scan.nextInt();
        double d2 = scan.nextDouble();
        scan.nextLine();
        String s2 = scan.nextLine();

        System.out.println(i+i2);
        System.out.println(d+d2);
        System.out.println(s+s2);
       
        scan.close();
    
    }
}

Solution In Python 3:


no = int(input())
dno = float(input())
stri = (input())

print(i + no)
print(d + dno)
print(s + stri)

Share:

Hacker Rank - Day 0 : Hello World.

                        Day 0 :Hello World.

Solution In Java 8: 

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

public class Solution 

{
    public static void main(String[] args) 

    {

        Scanner scan = new Scanner(System.in);
        String inputString = scan.nextLine();
        System.out.println("Hello, World.");
        System.out.println(inputString);
     
    }
}

 

Solution In Python 3:


input_string = input()
print('Hello, World.')

Share: