Wednesday, March 3, 2021

Java Code Solution | TCS NQT Previous Year Coding Question and Solution

1. A Sober Walk

Our hoary culture had several great persons since time immemorial and king vikramaditya’s nava ratnas (nine gems) belongs to this ilk.They are named in the following shloka:


Among these, Varahamihira was an astrologer of eminence and his book Brihat Jataak is recokened as the ultimate authority in astrology. He was once talking with Amarasimha,another gem among the nava ratnas and the author of Sanskrit thesaurus, Amarakosha. Amarasimha wanted to know the final position of a person, who starts from the origin 0 0 and travels per following scheme.


  • He first turns and travels 10 units of distance
  • His second turn is upward for 20 units
  • Third turn is to the left for 30 units
  • Fourth turn is the downward for 40 units
  • Fifth turn is to the right(again) for 50 units

… And thus he travels, every time increasing the travel distance by 10 units.


Constraints:

2<=n<=1000


Input:

3


Solution

import java.util.Scanner;
class Main{
    
    
    public static void main(String[] args){
        
        
        System.out.println("Enter the number of steps taken by Mr. Vikrant");
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=0;
        int y=0;
        for(int i=1;i<=n;i++){
            
            
            
            if(i%2==0){
                if(i%2==0 && i%4!=0){
                    
                    y=y+(i*10);
    
                }
                else{
                
                    y=y-(i*10);
                
                }
                
            }
            else{
               
                
                if(i%4==1){
                    
                    x=x+i*10;
                    
                }
                else{
                    
                    x=x-(i*10);
                }
            }
            }
           System.out.println(x+","+y);
       
    }
}


2. Rock, Paper and Secissor Game

In this game, user gets the first chance to pick the option among Rock, paper and scissor. After that computer select from remaining two choices(randomly), then winner is decided as per the rules.

Winning Rules as follows :

Rock vs paper-> paper wins
Rock vs scissor-> Rock wins
paper vs scissor-> scissor wins

Solution

import java.util.Scanner;
import java.util.Random;

public class Main{
    
    public static void main(String args[]){
        
        int rock=0;
        int scissor=1;
        int paper=2;
        
        Scanner sc=new Scanner(System.in);
        Random ran=new Random();
        int winning=0;
        int losing=0;
        
        
        for(int i=0;i<=5;i++){
            
            System.out.print("Choose-> 0 for rock, 1 for scissor, 2 for paper: ");
            int user = sc.nextInt();
            int comp= ran.nextInt(3);
            if(user==0 && comp==1 || user==1 && comp==2 || user==2 && comp==0){
                winning=winning+1;
                System.out.println("Congrates! you won the game");
                
            }
            
            else{
                System.out.println("Sorry, You lost");
                losing=losing+1;
            }
            
            System.out.println("Play Again");
            
            
        }
        System.out.println("Total winning= "+winning);
        System.out.println("Total losing= "+losing);
    }
}

Sunday, February 23, 2020

Python Code Solution

As we know that for getting incentive we must clear the proctored Assessment test. But many of the students are  confused which type of coding question will come and from where  we find solution if we did mistakes in previous assessment test.  I'm creating this blog for the help of those students.


15th January


Question 1:


-> Create a function count_words() which takes a string as input and creates a dictionary with a word   in the string as key and its value as number of times the word is repeating in the string. It should return the dictionary.

eg: "hello hi hello world hello" 
          
         dict={'hello':3,'hi':1,'word':1}

-> Create another function max_accurance_word() which takes a string as input and returns the word which is occuring maximum number of times in the string. Use the count_words function inside this function.

Sample input:
"hello hi hello world hello"

Sample output:
'hello'


Program:

def count_words(string):
    l=string.split()
    s=set(l)
    d={}
    for i in s:
        x=l.count(i)
        d[i]=x
    return d
def max_occurance(string):
    d=count_words(string)
    l1=[]
    for i in d.values():
        l1.append(i)
    max1=max(l1)
    
    
    for i in d.keys():
        if d[i]==max1:
            return i
string=input() 
     
print(max_occurance(string))

Input: 
hello hi hello world hello

Output:
hello


Question 2:

->Create a class Book()
    Include '__init__' constructor
    Attributes: 
                    book_id
                    book_name

->Create another class Library()
    Attributes:
                    library_id
                    address
                    book_list

   Create a method books_count() inside this class. This method takes a character as input and returns the count of those books whose name starts with the given character.

    Create another method delete_books() which takes a list of books as input and deletes  those books from the book list of library.

Input:

In first line Number of books must be entered.
book id and book name of first book must be entered in next two lines.
After entering all books enter single character for searching books.
In the next line enter count of books to be deleted and books must be entered in next fewlines.

Output:

1.count of books matching with character
2.books left in the list after deleting


Program:

class Book:
    def __init__(self,book_id,book_name):
        self.book_id=book_id
        self.book_name=book_name


class Library:
    def __init__(self,library_id,address,book_list):
        self.library_id=library_id
        self.address=address
        self.book_list=book_list
    def books_count(self,ch):
        count=0
        for i in self.book_list:
            if i.book_name[0]==ch:
                count+=1
        return count
    def delete_books(self,list1):
        for i in list1:
            for b in self.book_list:
                if b.book_name==i:
                    self.book_list.remove(b)
        
if __name__=="__main__":
            
    n=int(input())
    book_list=[]
    for i in range(n):
        book_id=int(input())
        book_name=input()
        book_list.append(Book(book_id,book_name))
    ch=input()
    l=Library(123,"Mumbai",book_list)  
    d_n=int(input())
    list1=[]
    for i in range(d_n):
        name=input()
        list1.append(name)
    
    print(l.books_count(ch))
    l.delete_books(list1)
    for i in l.book_list:
        print(i.book_name)

Input:
3
1
c lang
2
c++
3
java
c
2
c lang
java

Output:
2
c++


25th January

Question 1:

-> Create a function check_prime() which takes a number as input and returns 1 if the number is prime, 0 if the number is composite, -1 if the number is neither prime nor composite.

-> create a function prime_composite_list() which takes a list which contains numbers, seperates prime and composite numbers and returns a list containing list of prime and list of composite numbers as its elements, that is list of lists.


Program:

def is_prime(n):
    temp=False
    for i in range(2,n):
        if n%i==0:
            temp=True
    if temp==False:
        return 1
    else:
        return 0
def prime_composite_list(l):
    l1=[]
    l2=[]
    l3=[]
    for j in l:
        if is_prime(j)==1:
            l1.append(j)
        else:
            l2.append(j)
    l3.append(l1)
    l3.append(l2)
    return l3
if __name__=="__main__":
    l=[]
    count=int(input(""))
    for i in range(count):
        l.append(int(input("")))
    print(is_prime(l[1]))
    result=prime_composite_list(l)
    print(result)


Input:
5
1
2
3
4
5

Output:
1
[[2, 3, 5], [4]]


Question 2:

->Create a class Item() with
     Attributes:
                     item_id
                     item_name
                     item_price
                     quantity_available
     Include __init__ method
     Create a method calculate-price() which takes a quantity of items as input. If given quantity is             greater than or equal to available quantity then calculate price[price=quantity*item_price] else             return 0.

->Create another class Store() with
    Attribute : item_list.
     Create a method generate_bill() which takes input as dictionary which contains item names as             keys and values are quantity of item.
     Use calculate_price() method inside generate_bill().
     generate_bill method returns total bill of item in the dictionary.

Input:
1. Enter number of items in the first line
2. Enter the details of all items in following lines
3.Enter number of items in dictionary
4.Enter item name and quantity in next two lines. Enter all items of dictionary

Program:

class Item:

    def __init__(self,item_id,item_name,item_price,quantity_available):
        self.item_id=item_id
        self.item_name=item_name
        self.item_price=item_price
        self.quantity_available=quantity_available
     
    def calculate_price(self,quantity):
        if self.quantity_available>=quantity:
            price=quantity*self.item_price
            return price
        else:
            return 0

class Store:
    def __init__(self,item_list):
        self.item_list=item_list
     
    def generate_bill(self,d):
        total_price=0
        for itemName , qnty in d.items():
            for item_obj in self.item_list:
                if item_obj.item_name==itemName:
                    total_price+=item_obj.calculate_price(qnty)
     
        return total_price
 
if __name__=="__main__":
    item_list=[]
    count=int(input())
    for i in range(count):
        item_id=int(input())
        item_name=input()
        item_price=int(input())
        item_quantity=int(input())
        item_list.append(Item(item_id,item_name,item_price,item_quantity))
    s=Store(item_list)
    d={}
    d_count=int(input())
    for i in range(d_count):
        name=input()
        qnty=int(input())
        d[name]=qnty
    print(item_list[0].calculate_price(2))
    print(s.generate_bill(d))

Input:
3
1
bread
30
5
2
butter
20
3
3
milk
50
10
2
bread
2
butter
2

Output:
60
100


10th February  

Question 1:

->Create a function check_palindrome() which takes a list of string and returns a list of  palindrome strings.

Program:
def check_palindrome(strng):
l=[]
for i in strng:
if i.lower()==i[-1::-1].lower():
l.append(i)
return l
if __name__=="__main__":
strng=[]
n=int(input())
for i in range(n):
s=input()
strng.append(s)
result=check_palindrome(strng)
if len(result)>0:
for k in result:
print(k)
else:
print("No Palindrome found")

Input:
3
Hello
Radar
Malayalam

Output:
Radar
Malayalam


Question 2:

->Create a class Employee() with 
    Attributes: 
                     emp_id
                     emp_name
                     emp_role
                     emp_salary
Include __init__ method
Create a method increase_salary() which takes percentage that is to be increased and returns updated salary.

->Create another Organization() with
                Attributes:
                                 org_name
                                  emp_list (list of employees those salary have to be  increased)

create a method calculate_increament() which takes role of employee and percentage that is to be increased. This method will return  a list with increased salary of employee. Use increase_salary() method in this class to update increasing salary.

Program:


class Employee:
    def __init__ (self,emp_id,emp_name,emp_role,emp_salary):
        self.emp_id=emp_id
        self.emp_name=emp_name
        self.emp_role=emp_role
        self.emp_salary=emp_salary
    
    def increase_salary(self,p):
        salary=self.emp_salary+p*self.emp_salary/100
        return salary
    
class Organisation:
    def __init__ (self,org_name,emp_list):
        self.org_name=org_name
        self.emp_list=emp_list
    
    
    def calculate_increment(self,role,p):
        l=[]
        for i in self.emp_list:
            if i.emp_role==role:
                i.emp_salary=i.increase_salary(p)
                l.append(i)
        return l
if __name__=="__main__": 
    emp_list=[]
    n=int(input())
    for i in range(n):
        emp_id=input()
        emp_name=input()
        emp_role=input()
        emp_salary=float(input())
        emp_list.append(Employee(emp_id,emp_name,emp_role,emp_salary))
    role=input()
    p=int(input())
    o=Organisation("TCS",emp_list)
    result=o.calculate_increment(role, p)
    for j in result:
        print(j.emp_name)
        print(j.emp_salary)

Input:
3
1
ram
developer
50000
2
shyam
debugger
40000
3
krisna
developer
80000
developer
10

Output:
ram
55000
krishna
88000

13th february


Question 1:

->Create a class Account() with
            Attributes:
                            acc_no
                            name
                            balance
create a method deposit_money() which takes a parameter dep_amount as  a number and updates the deposit money to the balance and returns the updated amount.

Create another method withdraw_money which takes a number as withdraw_money. There should be minimum amount present in the account which is 1000, so if the amount present in the account after withdrawing money is less than 1000 then return 0 otherwise return updated amount.

Program:

class Account:
    def __init__(self,acc_no,name,balance):
        self.acc_no=acc_no
        self.name=name
        self.balance=balance
        
    def deposit_money(self,dep_amount):
        self.balance+=dep_amount
        return self.balance
        
    def withdraw_amount(self,withdraw_amount):
        if self.balance-withdraw_amount>=1000:
            self.balance-=withdraw_amount
            return self.balance
        else:
            return 0
        
if __name__=="__main__":
    acc_no=int(input())
    name=input()
    balance=int(input())
    account=Account(acc_no,name,balance)
    dep_or_withdrawl=input()
    if(dep_or_withdrawl=='d'):
        dep_amount=int(input())
        print(account.deposit_money(dep_amount))
    
    else:
        withdrawl_amount=int(input())
        withdrawl=account.withdraw_amount(withdrawl_amount)
        if withdrawl==0:
            print("Insufficient Amount")
        else:
            print(withdrawl)

Input:
12345
vikrant
1500
w
2000

Output:
Insufficient Amount


Question 2:


->Create a class Employee() with 
           Attributes:
                       emp_no
                       emp_name
                       leaves
     Leaves is a dictionary with the three keys "EL',  "CL", "SL" which are the type of leaves. Define __init__() to initialize the values.

Create another class Company() which has two fields cname and emps. cname is the company name and emps is the list of employees. Create a function leave_available() to which takes two parameterrs emp_no and type of leave and used to print the number of leaves remaining.

Create another function leave_permission() which takes empno, type of leave and num of leave. if availabel leave of empoyee is greater than equal to the umber of leaves amployee want then print "Granted" else print "Rejected".

Program:

class Employee:
    def __init__(self,emp_no,emp_name,leaves):
        self.emp_no=emp_no
        self.emp_name=emp_name
        self.leaves=leaves
        

class Company:
    def __init__(self,cname,emps):
        self.cname=cname
        self.emps=emps
        
    def leave_available(self,emp_no,t_leave):
        for i in self.emps:
            if i.emp_no==emp_no:
                return i.leaves[t_leave]
        
        
    def leave_permission(self,emp_no,t_leave,n_leave):
        for i in self.emps:
            if i.emp_no==emp_no:
                if i.leaves[t_leave]>=n_leave:
                    return "Granted"
                else:
                    return "Rejected"
                
if __name__=="__main__":
    c=int(input())
    emps=[]
    z=Company("TCS",emps)
    for i in range(c):
        leaves={}
        emp_no=int(input())
        emp_name=input()
        leaves['EL']=int(input())
        leaves['CL']=int(input())
        leaves['SL']=int(input())
        employee=Employee(emp_no,emp_name,leaves)
        z.emps.append(employee)
    emp_id=int(input())
    t_leave=input()
    n_leave=int(input())
    print(z.leave_available(emp_no,t_leave))
    print(z.leave_permission(emp_no,t_leave,n_leave))

Input:
2
1
vikrant
5
10
15
2
kishan
10
10
10
1
SL
20

Output:
10
Rejected


    
    
    
    
                


                








    


Java Code Solution | TCS NQT Previous Year Coding Question and Solution

1. A Sober Walk Our hoary culture had several great persons since time immemorial and king vikramaditya’s nava ratnas (nine gems) belongs t...