Java and Python Programming Exercises
Java and Python Programming Exercises
B) Write a ‘java’ program to copy only non-numeric data from one file to another file. [25 M]
Sol: import [Link].*;
class Slip1B{
public static void main(String args[]) throws IOException{
char ch;
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int c;
while ((c=[Link]())!=-1){
ch=(char)c;
if([Link](ch)==false){
[Link](c);
}
}
[Link]();
[Link]();
}
}
Q.2 Python:
A) Write a Python program to accept n numbers in list and remove duplicates from a list. [15 M]
Sol: def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
# Driver Code
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))
B) Write Python GUI program to take accept your birthdate and output your age when a button
is pressed. [25 M]
Sol: from datetime import date
today = [Link]()
def exit():
[Link]()
def get_age():
d = int([Link]())
m = int([Link]())
y = int([Link]())
age = [Link] - y - (([Link], [Link]) < (m, d))
[Link](state='normal')
[Link]('1.0', [Link])
[Link]([Link], age)
[Link](state='disabled')
import tkinter as tk
window = [Link]()
[Link]("400x300")
[Link](bg="#F7DC6F")
[Link](width=False, height=False)
[Link]('Age Calculator!')
l3 = [Link](window, text="The Calculated Age is: ", font=('Arial', 12, "bold"), fg="darkgreen",
bg="#F7DC6F")
t1 = [Link](window, width=5, height=0, state="disabled")
[Link](x=70, y=5)
[Link](x=10, y=40)
l_d.place(x=100, y=70)
l_m.place(x=100, y=95)
l_y.place(x=100, y=120)
[Link](x=180, y=70)
[Link](x=180, y=95)
[Link](x=180, y=120)
[Link](x=100, y=150)
[Link](x=50, y=200)
[Link](x=240, y=203)
[Link]()
SLIP 2
Q.1. Core Java:
1. A) Write a java program to display all the vowels from a given string. [15 M]
Sol: import [Link];
class Slip2A {
public static void main(String args[]){
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
String str = [Link]().toLowerCase();
for(int i=0; i<[Link](); i++){
if([Link](i)=='a' || [Link](i)=='e' || [Link](i)=='i' || [Link](i)=='o' ||
[Link](i)=='u' ){
[Link]([Link](i));
}
}
} catch (Exception e) {}
}
}
B) Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and
MOUSE_CLICK and display the position of the Mouse_Click in a TextField. [25 M]
Sol: import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextField t,t1;
Label l,l1;
int x,y;
Panel p;
MyFrame(String title)
{
super(title);
setLayout(new FlowLayout());
p=new Panel();
[Link](new GridLayout(2,2,5,5));
t=new TextField(20);
l= new Label("Mouse clicking");
l1= new Label("Mouse Movement");
t1=new TextField(20);
[Link](l);
[Link](t);
[Link](l1);
[Link](t1);
add(p);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
x=[Link]();
y=[Link]();
[Link]("X="+x+" Y="+y);
}
}
class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=[Link]();
y=[Link]();
[Link]("X="+ x +" Y="+y);
}
}
}
class Slip2B
{
Q.2 Python:
A) Write a Python function that accepts a string and calculate the number of upper case letters
and lower case letters. Sample String: 'The quick Brown Fox' Expected Output: No. of Upper
case characters: 3 No. of Lower case characters: 13 [15 M]
Sol: def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if [Link]():
d["UPPER_CASE"]+=1
elif [Link]():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
B) Write Python GUI program to create a digital clock with Tkinter to display the time. [25 M]
Sol: import time
from tkinter import *
canvas = Tk()
[Link]("Digital Clock")
[Link]("350x200")
[Link](1,1)
label = Label(canvas, font=("Courier", 30, 'bold'), bg="blue", fg="white", bd =30)
[Link](row =0, column=1)
def digitalclock():
text_input = [Link]("%H:%M:%S")
[Link](text=text_input)
[Link](200, digitalclock)
digitalclock()
[Link]()
SLIP3
Q.1. Core Java:
A) Write a ‘java’ program to check whether given number is Armstrong or not. (Use static
keyword) [15 M]
Sol:import [Link];
class Slip3A {
static int temp;
public static void main(String args[]){
int n,r,sum=0;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Number");
n = [Link]([Link]());
temp=n;
while(n>0){
r = n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum){
[Link](temp + " Is Armstrong Number : ");
}else{
[Link](temp + " Is Not Armstrong Number : ");
}
} catch (Exception e) {}
}
}
B) Define an abstract class Shape with abstract methods area () and volume (). Derive abstract
class Shape into two classes Cone and Cylinder. Write a java Program to calculate area and
volume of Cone and Cylinder.(Use Super Keyword.) [25 M]
Sol:
import [Link].*;
double area(){
return (2*3.14*a*b*3.14*a*b);
}
double volume(){
return (3.14*a*a*b);
}
}
class Slip3B{
public static void main(String args[]) throws Exception{
int r,h,s;
DataInputStream dr = new DataInputStream([Link]);
[Link]("Enter Radius, Height and Side Values : ");
r = [Link]([Link]());
h = [Link]([Link]());
s = [Link]([Link]());
Shape s1;
Q.2 Python:
A) Write a Python program to check if a given key already exists in a dictionary. If key exists
replace with another key/value pair. [15 M]
Sol:
dict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9}
print("The given dictionary : ",dict)
check_key = input("Enter Key to check: ")
check_value = input("Enter Value: ")
if check_key in dict:
print(check_key,"is Present.")
[Link](check_key)
dict[check_key]=check_value
else:
print(check_key, " is not Present.")
dict[check_key]=check_value
print("Updated dictionary : ",dict)
B) Write a python script to define a class student having members roll no, name, age, gender.
Create a subclass called Test with member marks of 3 subjects. Create three objects of the Test
class and display all the details of the student with total marks. [25 M]
Sol: class Student:
def GetStudent(self):
[Link]=int(input("\nEnter Student Roll No:"))
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Student Age:"))
[Link]=input("Enter Student Gender:")
def PutStudent(self):
print("Student Roll No:",[Link])
print("Student Name:",[Link])
print("Student Age:",[Link])
print("Student Gender:",[Link])
class Test(Student):
def GetMarks(self):
[Link]=int(input("Enter Marks of Marathi Subject"))
[Link]=int(input("Enter Marks of Hindi Subject"))
[Link]=int(input("Enter Marks of Eglish Subject"))
def PutMarks(self):
print("Marathi Marks:", [Link])
print("Hindi Marks:", [Link])
print("English Marks:", [Link])
print("Total Marks:",[Link]+[Link]+[Link])
for i in range(0,n):
obj=input("Enter Object Name:")
[Link](obj)
print(lst)
for j in range(0,n):
lst[j]=Test()
lst[j].GetStudent()
lst[j].GetMarks()
print("\nDisplay Details of Student",j+1)
lst[j].PutStudent()
lst[j].PutMarks()
SLIP4
Q.1. Core Java:
A) Write a java program to display alternate character from a given string.[15 M]
Sol: import [Link];
class Slip4A {
public static void main(String args[]){
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
String str = [Link]();
for(int i=0;i<[Link]();i+=2) {
[Link](" " + [Link](i));
}
} catch (Exception e) {}
}
}
B) Write a java program using Applet to implement a simple arithmetic calculator. [25 M]
Sol: import [Link].*;
import [Link].*;
import [Link].*;
A) Write Python GUI program to create background with changing colors [15 M]
Sol: from tkinter import *
app = Tk()
[Link]("Vinayak App")
l1 = Label(app, text="Choose the the week day here")
[Link]()
text1 = StringVar()
[Link]("Choose here")
w = OptionMenu(app, text1, "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
[Link](bg="GREEN", fg="WHITE")
w["menu"].config(bg="RED")
[Link](pady=20)
[Link]()
B) Define a class Employee having members id, name, department, salary. Create a subclass
called manager with member bonus. Define methods accept and display in both the classes.
Create n objects of the manager class and display the details of the manager having the
maximum total salary (salary+bonus). [25 M]
Sol: class Employee:
def AcceptEmp(self):
[Link]=int(input("Enter emp id:"))
[Link]=input("Enter emp name:")
[Link]=input("Enter emp Dept:")
[Link]=int(input("Enter emp Salary:"))
def DisplayEmp(self):
print("Emp id:",[Link])
print("Emp Name:",[Link])
print("Emp Dept:",[Link])
print("Emp Salary:",[Link])
class Manager(Employee):
def AcceptMgr(self):
[Link]=int(input("Enter Manager Bonus"))
def DisplayMgr(self):
print("Manger Bonus is:",[Link])
[Link]=[Link]+[Link]
print("Total Salary: ", [Link])
n=int(input("Enter How may Managers:"))
lst=[]
for i in range(0,n):
obj=input("Enter Object Name:")
[Link](obj)
print(lst)
for j in range(0,n):
lst[j]=Manager()
lst[j].AcceptEmp()
lst[j].AcceptMgr()
print("\nDisplay Details of Manager",j+1)
lst[j].DisplayEmp()
lst[j].DisplayMgr()
#maximum logic
maxTotalSal= lst[0].TotalSal
maxIndex=0
for j in range(1,n):
if lst[j].TotalSal > maxTotalSal:
maxTotalSal= lst[j].TotalSal
maxIndex=j
print("\nDisplay Details of Manager Having Maximum Salary(Salary+Bonus)")
lst[maxIndex].DisplayEmp()
lst[maxIndex].DisplayMgr()
SLIP5
B) Write a java program to accept list of file names through command line. Delete the files
having extension .txt. Display name, location and size of remaining files. [25 M]
Sol: import [Link].*;
class Slip5B{
public static void main(String args[]) throws Exception{
for(int i=0;i<[Link];i++){
File file=new File(args[i]);
if([Link]()){
String name = [Link]();
if([Link](".txt")){
[Link]();
[Link]("file is deleted " + file);
}else{
[Link]("File Name : " + name + "\nFile Location : "
+[Link]()+"\nFile Size : "+[Link]()+" bytes");
}
}
else{
[Link](args[i]+ "is not a file");
}
}
}
}
Q.2 Python:
A) Write a Python script using class, which has two methods get_String and print_String.
get_String accept a string from the user and print_String print the string in upper case. [15 M]
Sol:
class MyClass:
def Get_String(self):
[Link]=input("Enter any String: ")
def Print_String(self):
s=[Link]
print("String in Upper Case: " , [Link]())
# main body
Obj=MyClass()
Obj.Get_String()
Obj.Print_String()
B) Write a python script to generate Fibonacci terms using generator function. [25 M]
Sol: def Fibo(terms2):
f1=0
yield f1
f2=1
yield f2
for i in range(0,terms2-2):
f3=f1+f2
yield f3
f1=f2
f2=f3
#mainbody
terms1=int(input("How many terms:"))
gen=Fibo(terms1)
while True:
try:
print(next(gen))
except StopIteration:
break
SLIP6
Q.1. Core Java:
A) Write a java program to accept a number from user, if it zero then throw user defined
Exception “Number Is Zero”, otherwise calculate the sum of first and last digit of that number.
(Use static keyword). [15 M]
Sol: import [Link].*;
class NumZero extends Exception{}
public class Slip6A {
static int n;
public static void main(String args[]){
int first,last=0;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Number : ");
n = [Link]([Link]());
if(n!=0){
last = n % 10;
first = n;
while(n>=10){
n = n / 10;
}
first=n;
[Link]("Sum of First and Last Number is : " + (first + last));
}else{
throw new NumZero();
}
Q.2 Python:
A) Write python script using package to calculate area and volume of cube and sphere [15 M]
Sol: pi=22/7
radian = float(input('Radius of sphere: '))
sur_area = 4 * pi * radian **2
volume = (4/3) * (pi * radian ** 3)
print("Surface Area is: ", sur_area)
print("Volume is: ", volume)
B) Write a Python GUI program to create a label and change the label font style (font name,
bold, size). Specify separate check button for each style. [25 M]
Sol: import tkinter as tk
parent = [Link]()
[Link]("-Welcome to Python tkinter Basic exercises-")
my_label = [Link](parent, text="Hello", font=("Arial Bold", 70))
my_label.grid(column=0, row=0)
[Link]()
SLIP7
Q.1. Core Java:
A) Write a java program to display Label with text “Dr. D Y Patil College”, background color Red
and font size 20 on the frame. [15 M]
Sol: import [Link].*;
import [Link].*;
void accept(){
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
try{
[Link]("Enter Name of Player : ");
Name = [Link]();
[Link]("Enter Total Runs of Player : ");
Total_runs = [Link]([Link]());
[Link]("Enter Name of Tixes Not out : ");
Notout = [Link]([Link]());
[Link]("Enter Innings played by players : ");
Inning = [Link]([Link]());
}catch (Exception e) {}
}
void average(){
avg = Total_runs/Inning;
[Link]("Name : "+Name+"\nTotal runs : "+Total_runs+"\nAvergae :
"+avg+"\nInning : "+ Inning);
}
}
public class Slip7B {
public static void main(String args[]){
float max =0;
int n;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
try {
[Link]("How many Players : ");
n = [Link]([Link]());
Cricket ob1[]= new Cricket[n];
for(int i=0; i<n; i++){
ob1[i] = new Cricket();
ob1[i].accept();
}
for(int i=0; i<n; i++){
ob1[i].average();
}
for(int i=0; i<n; i++){
if(max<ob1[i].avg){
max = ob1[i].avg;
}
}
[Link](" --------------------------- \nMax avg : "+max);
} catch (Exception e) {
[Link]("Error ........ "+e);
}
}
}
Q.2 Python:
A) Write Python class to perform addition of two complex numbers using binary + operator
overloading. [15 M]
Sol: print("Format for writing complex number: a+bj.\n")
c1 = complex(input("Enter First Complex Number: "))
c2 = complex(input("Enter second Complex Number: "))
B) Write python GUI program to generate a random password with upper and lower case letters.
[25 M]
Sol: from tkinter import *
import random
import string
top = Tk()
[Link]("300x150")
def disp():
letters = string.ascii_lowercase
ulet=string.ascii_uppercase
rand_letters = [Link](letters+ulet,k=7)
[Link](text = rand_letters)
label = Label(top)
[Link]()
[Link]()
OR
import random
import string
print('Password generator')
length=int(input('\n Enter the length of password'))
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = [Link]
symbols=[Link]
all=lower+upper+num+symbols
temp=[Link](all,length)
password="".join(temp)
print(password)
OR
Write python GUI program to generate a random password with upper and lower case letters.
Ans - import random
password_len = int(input("Enter the length of the password: "))
UPPERCASE = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z']
LOWERCASE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z']
DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
SPECIAL = ['@', '#', '$', '=', ':', '?', '.', '/', '|', '~', '>', '*', '<']
COMBINED_LIST = DIGITS + UPPERCASE + LOWERCASE + SPECIAL
password = "".join([Link](COMBINED_LIST, password_len))
print(password)
SLIP8
Q.1. Core Java:
A) Define an Interface Shape with abstract method area(). Write a java program to calculate an
area of Circle and Sphere.(use final keyword) [15 M]
Sol: import [Link].*;
interface Shape{
final float pi= 3.14F;
double area();
}
class Circle implements Shape{
int rad;
Circle(int r){
rad=r;
}
public double area(){
return pi*rad*rad;
}
}
class Sphere implements Shape{
int rad;
Sphere(int r){
rad =r;
}
public double area(){
return 4*pi*rad*rad;
}
}
class Slip8A {
public static void main(String args[]) throws Exception{
int r;
Scanner sc = new Scanner([Link]);
[Link]("Enter the Radius : ");
r=[Link]();
Shape sh;
Circle cl=new Circle(r);
sh=cl;
[Link]("Area of Circle : " + [Link]());
B) Write a java program to display the files having extension .txt from a given directory. [25 M]
Sol: import [Link];
class Slip8B {
public static void main(String[] args) {
File file = new File("C:\\Users\\Saurabh_Sapkal\\Desktop\\ln\\java\\Slips");
String[] fileList = [Link]();
for(String str : fileList) {
if([Link](".txt")){
[Link](str);
}
}
}
}
Q.2 Python:
t = (1, 2, 3, 4, 2, 7, 8, 8, 3, 2)
print(t)
lst=[]
if [Link](t[i])>1 :
print(t[i])
B) Write a Python class which has two methods get_String and print_String. get_String accept
a string from the user and print_String print the string in upper case. Further modify the program
to reverse a string word by word and print it in lower case. [25 M]
Sol: class MyClass:
def Get_String(self):
[Link]=input("Enter any String: ")
def Print_String(self):
s=[Link]
print("String in Upper Case: " , [Link]())
#String Reverse logic
cnt=len(s)
i=cnt-1
RevStr=""
while(i >= 0):
RevStr=RevStr + s[i]
i=i-1
print("String in Reverse & Lower case:" , [Link]())
# main body
Obj=MyClass()
Obj.Get_String()
Obj.Print_String()
SLIP 9
Q.1. Core Java:
B) Write a java program to validate PAN number and Mobile Number. If it is invalid then throw
user defined Exception “Invalid Data”, otherwise display it. [25 M]
Sol: import [Link].*;
class invaliddetails extends Exception{}
class Slip9B{
static int n;
public static void main( String args[]){
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("********* Do you Want to Validate ********* \n1. Mobile Number Press :
1 \n2. PAN Card Press : 2 \nEnter Number : ");
n = [Link]([Link]());
switch(n){
case 1 :
[Link]("Enter Mobile Number : ");
Long num = [Link]([Link]());
if([Link]().matches("(0/91)?[7-9][0-9]{9}")){
[Link]("Enter Valid Mobile Number..!");
}else{
throw new invaliddetails();
}
break;
case 2 :
[Link]("Enter PAN Number : ");
String str= [Link]();
if([Link]("[A-Z]{5}[0-9]{4}[A-Z]{1}")){
[Link]("Enter Valid PAN CARD Number..!");
}else{
throw new invaliddetails();
}
break;
default :
throw new invaliddetails();
}
} catch (invaliddetails nz) {
[Link]("You Enter Invalid Details...!");
}
catch (NumberFormatException e){
[Link]("You Enter Invalid Details...!");
}
catch(Exception e){}
}
}
Q.2 Python:
A) Write a Python script using class to reverse a string word by word [15 M]
Sol: class MyClass:
def Get_String(self):
[Link]=input("Enter any String: ")
def Reverse_String(self):
s=[Link]
cnt=len(s)
i=cnt-1
revStr=""
while(i >= 0):
revStr=revStr + s[i]
i=i-1
print("String in Reverse:" , revStr)
# main body
Obj=MyClass()
Obj.Get_String()
Obj.Reverse_String()
B) Write Python GUI program to accept a number n and check whether it is Prime, Perfect or
Armstrong number or not. Specify three radio buttons. [25 M]
Sol: num = int(input("Enter a number: ")
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
SLIP 10
Q.1. Core Java:
A) Write a java program to count the frequency of each character in a given string. [15 M]
Sol: import [Link];
class Slip10A {
public static void main(String args[]){
int i, j;
String ch;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
ch = [Link]();
int[] str = new int[[Link]()];
char string[] = [Link]();
for(i = 0; i <[Link](); i++) {
str[i] = 1;
for(j = i+1; j <[Link](); j++) {
if(string[i] == string[j]) {
str[i]++;
string[j] = '0';
}
}
}
for(i = 0; i <[Link]; i++) {
if(string[i] != ' ' && string[i] != '0'){
[Link](string[i] + "-" + str[i]);
}
}
} catch (Exception e) {}
}
}
B) Write a java program for the following: [25 M]
Sol: import [Link].*;
import [Link].*;
import [Link].*;
class Slip10B extends JFrame implements ActionListener{
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5;
JButton b1,b2,b3;
Panel p1,p2,p3,p4,p5;
GridLayout g1,g2,g3,g4,g5,g6;
JFrame jf;
public Slip10B(){
jf = new JFrame();
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
t4 = new JTextField(20);
t5 = new JTextField(20);
b1 = new JButton("Calculate");
b2 = new JButton("Clear");
b3 = new JButton("Close");
p1 = new Panel();
g1= new GridLayout(1,1);
[Link](g1);
[Link](l1);
p2 = new Panel();
g2 = new GridLayout(1,2);
[Link](g2);
[Link](l2);
[Link](t1);
p3 = new Panel();
g3 = new GridLayout(1,4);
[Link](g3);
[Link](l3);
[Link](t2);
[Link](l4);
[Link](t3);
p4 = new Panel();
g4 = new GridLayout(2,2);
[Link](g4);
[Link](l5);
[Link](t4);
[Link](l6);
[Link](t5);
p5 = new Panel();
g5 = new GridLayout(1,3);
[Link](g5);
[Link](b1);
[Link](b2);
[Link](b3);
g6 = new GridLayout(5,1);
[Link](g6);
[Link](p1);
[Link](p2);
[Link](p3);
[Link](p4);
[Link](p5);
[Link](500,250);
[Link](true);
[Link](this);
[Link](this);
[Link](this);
}
if([Link]()==b1){
double iamt = (p*tm*rt)/100;
[Link]([Link](iamt));
double tamt = iamt+p;
[Link]([Link](tamt));
}
if([Link]()==b2){
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]("");
}
if([Link]()==b3){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String args[]){
Slip10B s1 = new Slip10B();
}
}
Q.2 Python:
A) Write Python GUI program to display an alert message when a button is pressed. [15 M]
B) Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' ']’. These
brackets must be close in the correct order. for example "()" and "()[]{}" are valid but "[)", "({[)]"
and "{{{" are invalid. [25 M]
Sol: s="{()[}("
lst=[]
if len(s) % 2 != 0:
print("Invalid Sequence")
else:
for b in s:
if b=="(" or b=="{" or b=="[":
[Link](b)
elif b==")" or b=="}" or b=="]":
cnt=len(lst)-1
if b==")":
if lst[cnt]=="(":
[Link]()
else:
print("Invalid Sequence")
break
if b=="}":
if lst[cnt]=="{":
[Link]()
else:
print("Invalid Sequence")
break
if b=="]":
if lst[cnt]=="[":
[Link]()
else:
print("Invalid Sequence")
break
if len(lst)==0:
print("valid Sequence")
SLIP 11
Q.1. Core Java:
A) Write a menu driven java program using command line arguments for the following: [15 M]
1. Addition 2. Subtraction 3. Multiplication 4. Division.
Sol:
import [Link];
public class Slip11A {
public static void main(String args[]){
int a,b,n;
[Link]("Enter 1 : Additon" + '\n' + "Enter 2 : Substraction" + '\n' + "Enter 3 :
Multiplication" + '\n' + "Enter 4 : Division");
DataInputStream dr = new DataInputStream([Link]);
try {
a = [Link](args[0]);
b = [Link](args[1]);
[Link]("Enter Number : ");
n = [Link]([Link]());
switch(n){
case 1:
[Link](a + " + " + b + " = " + (a+b));
break;
case 2:
[Link](a + " - " + b + " = " + (a-b));
break;
case 3:
[Link](a + " * " + b + " = " + (a*b));
break;
case 4:
[Link](a + " / " + b + " = " + (a/b));
break;
}
} catch (Exception e) {}
}
}
B) Write an applet application to display Table lamp. The color of lamp should get change
randomly. [25 M]
Sol: import [Link].*;
import [Link].*;
[Link](0,250,290,290);
[Link](125,250,125,160);
[Link](175,250,175,160);
[Link](85,157,130,50,-65,312);
[Link](85,87,130,50,62,58);
[Link](85,177,119,89);
[Link](215,177,181,89);
[Link](cl);
[Link](78,120,40,40,63,-174);
[Link](120,96,40,40);
[Link](173,100,40,40,110,180);
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
Q.2 Python:
A) Write a Python program to compute element-wise sum of given tuples. Original lists: (1, 2, 3,
4) (3, 5, 2, 1) (2, 2, 3, 1) Element-wise sum of the said tuples: (6, 9, 8, 6) [15 M]
Sol: from numpy import array
lst1=[1,5,7]
lst2=[3,2,1]
a = array(lst1)
b = array(lst2)
print(a + b)
B) Write Python GUI program to add menu bar with name of colors as options to change the
background color as per selection from menu option. [25 M]
Sol:
SLIP 12
Q.1. Core Java:
A) Write a java program to display each String in reverse order from a String array. [15 M]
Sol: class Slip12A{
public static void main(String args[]){
String arr[] = {"swarup", "Sayali", "Mahesh"};
for(int i=[Link]-1; i>=0; i--){
[Link](arr[i] + ' ');
}
}
}
B) Write a java program to display multiplication table of a given number into the List box by
clicking on button. [25 M]
Sol: import [Link].*;
import [Link].*;
import [Link].*;
public class Slip12B extends Applet implements ActionListener{
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
Q.2 Python:
A) Write a Python GUI program to create a label and change the label font style (font name,
bold, size) using tkinter module. [15 M]
Sol:
B) Write a python program to count repeated characters in a string. Sample string:
'thequickbrownfoxjumpsoverthelazydog' Expected output: o-4, e-3, u-2, h-2, r-2, t-2 [25 M]
Sol: check_string="MalegaonBaramatiPune"
dict = {}
for ch in check_string:
if ch in dict:
dict[ch] += 1
else:
dict[ch] = 1
SLIP13
Q.1. Core Java:
A) Write a java program to accept ‘n’ integers from the user & store them in an ArrayList
collection. Display the elements of ArrayList collection in reverse order. [15 M]
Sol: import [Link].*;
class Slip13A{
public static void main(String args[]){
String temp=null;
int i,j,n;
DataInputStream dr = new DataInputStream([Link]);
try{
[Link]("Enter How May Element You Want = ");
n = [Link]([Link]());
String name[]= new String[n];
for(i=0; i<n; i++){
[Link]("Enter " + (i+1) + " String = ");
name[i] = [Link]();
}
[Link]("After Sorting = ");
for(i=n-1; i>=0; i--){
[Link](name[i] + " ");
}
}catch(Exception e){}
}
}
B) Write a java program that asks the user name, and then greets the user by name. Before
outputting the user's name, convert it to upper case letters. For example, if the user's name is
Raj, then the program should respond "Hello, RAJ, nice to meet you!". [25 M]
Sol: import [Link];
class Slip13B {
public static void main(String args[]){
String str;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Username : ");
str = [Link]();
[Link]("\"Hello, " + [Link]() + ", nice to meet you!\"");
} catch (Exception e) {}
}
}
Q.2 Python:
A) Write a Python program to input a positive integer. Display correct message for correct and
incorrect input. (Use Exception Handling) [15 M]
Sol: num = int (input("Enter Any Positive number:"))
try:
if num >= 0:
raise ValueError("Positive Number-Input Number is Correct")
else:
raise ValueError("Negative Number-Input Number is InCorrect")
except ValueError as e:
print(e)
SLIP 14
Q.1. Core Java:
B) Write a java program to accept the details of employee (Eno, EName, Sal) and display it on
next frame using appropriate event . [25 M]
Sol: import [Link].*;
import [Link].*;
Emp_details() {
f = new Frame("\t Employee Details:");
empno = new Label("\t Employee Id:");
empname = new Label("\t Employee Name:");
sal = new Label("\t Employee Sal:");
tempno = new TextField(25);
tempname = new TextField(25);
tsal = new TextField(25);
next = new Button("Next");
[Link](empno);
[Link](tempno);
[Link](empname);
[Link](tempname);
[Link](sal);
[Link](tsal);
[Link](next);
[Link](this);
[Link](new FlowLayout());
[Link](400, 400);
[Link](true);
}
class Slip14B {
public static void main(String args[]) {
new Emp_details();
}
}
Q.2 Python:
A) Write a Python GUI program to accept dimensions of a cylinder and display the surface area
and volume of cylinder. [15 M]
B) Write a Python program to display plain text and cipher text using a Caesar encryption. [25
M]
SLIP 15
Q.1. Core Java:
A) Write a java program to search given name into the array, if it is found then display its index
otherwise display appropriate message. [15 M]
Sol: import [Link];
class Slip15A{
public static void main(String args[]){
String arr[] = {"saurabh", "Sapkal", "Mahesh","priya"};
int i,n=0;
boolean a=false;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
String s= [Link]();
for(i = 0; i < [Link]; i++)
{
if(arr[i].equals(s))
{
n = i;
a = true;
break;
}
}
if(a){
[Link]("arr" + "["+ i + "]");
}else{
[Link]("not Found");
}
} catch (Exception e) {}
}
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
Q.2 Python:
A) Write a Python class named Student with two attributes student_name, marks. Modify the
attribute values of the said class and print the original and modified values of the said attributes.
[15 M]
Sol: class Student:
def Accept(self):
[Link]=input("Enter Student Name:")
[Link]=int(input("Enter Student Total Marks:"))
def Modify(self):
[Link]=[Link]
[Link]=int(input("Enter Student New Total Marks:"))
print("Student Name:",[Link])
print("Old Total Mark:",[Link])
print("New Total Mark:",[Link])
#main body
Stud1=Student()
[Link]()
[Link]()
B) Write a python program to accept string and remove the characters which have odd index
values of given string using user defined function. [25 M]
Sol: def MyStr():
Str=input("Enter any String: ")
cnt=len(Str)
newStr=""
for i in range(0,cnt):
if i%2 ==0:
newStr=newStr + Str[i]
print("New String with removed odd Index Character: ",newStr)
# Mainbody
MyStr()
SLIP 16
Q.1. Core Java:
A) Write a java program to calculate sum of digits of a given number using recursion. [15 M]
Sol: import [Link].*;
public class Slip16A {
int sum =0;
public static void main(String args[]) throws Exception{
int n;
Scanner s = new Scanner([Link]);
[Link]("Enter the Number : ");
n =[Link]();
Slip16A obj = new Slip16A();
int a = obj.sum_digit(n);
[Link]("Sum of Digit is : "+a);
}
B) Write a java program to accept n employee names from user. Sort them in ascending order
and Display them.(Use array of object and Static keyword) [25 M]
Sol:
Q.2 Python:
A) Write a python script to create a class Rectangle with data member’s length, width and
methods area, perimeter which can compute the area and perimeter of rectangle. [15 M]
Sol: class Rect:
def init (self,l2,w2):
self.l=l2
self.w=w2
def RectArea(self):
self.a=self.l * self.w
print("Area of Rectangle:", self.a)
def RectPer(self):
self.p=2*(self.l + self.w)
print("Perimeter of Rectangle:", self.p)
#main body
l1=int(input("Enter Length:"))
w1=int(input("Enter Width:"))
Obj=Rect(l1,w1)
[Link]()
[Link]()
B) Write Python GUI program to add items in listbox widget and to print and delete the selected
items from listbox on button click. Provide three separate buttons to add, print and delete. [25 M]
SLIP 17
Q.1. Core Java:
A) Write a java Program to accept ‘n’ no’s through command line and store only armstrong no’s
into the array and display that array. [15 M]
Sol:
class Slip17A{
public static void main(String args[]){
int num,i,r,sum=0,temp,count=0;;
num = [Link];
int a[]= new int[num];
int b[]= new int[10];
for(i=0; i<num; i++){
a[i] = [Link](args[i]);
sum =0;
temp =a[i];
while(a[i]!=0){
r = a[i]%10;
sum = sum+r*r*r;
a[i] = a[i]/10;
}
if(temp==sum){
b[count] = temp;
count++;
}
}
for(i=0; i<count; i++){
[Link](b[i] + " ");
}
}
}
B) Define a class Product (pid, pname, price, qty). Write a function to accept the product details,
display it and calculate total amount. (use array of Objects) [25 M]
Sol:
import [Link].*;
class Product{
String pname;
int pid, qty;
float price, total;
void accept(){
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
try {
[Link]("Enter the producat Name : ");
pname=[Link]();
[Link]("Enter pid, qty and price : ");
pid = [Link]([Link]());
qty = [Link]([Link]());
price = [Link]([Link]());
} catch (Exception e) { }
}
void display(){
total = qty*price;
[Link]("pid : " + pid + "\nProduct Nmae : "+pname+"\nQuantity : "+qty +
"\nPrice : "+price+"\n Total Amount : "+total);
}
}
class Slip17B {
public static void main(String args[]) throws IOException{
int n;
float to=0;
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("How many Product you want to enter : ");
n = [Link]([Link]());
Product p1[]=new Product[n];
for(int i=0; i<n; i++){
p1[i]=new Product();
p1[i].accept();
}
for(int i=0; i<n; i++){
p1[i].display();
}
for(int i=0; i<n; i++){
to=to+p1[i].total;
[Link]("Total Cost : "+to);
}
}
}
Q.2 Python:
A) Write Python GUI program that takes input string and change letter to upper case when a
button is pressed. [15 M]
Sol:
B) Define a class Date (Day, Month, Year) with functions to accept and display it. Accept date
from user. Throw user defined exception “invalid Date Exception” if the date is invalid. [25 M]
Sol: class MyDate:
def accept(self):
self.d=int(input("Enter Day:"))
self.m=int(input("Enter Month:"))
self.y=int(input("Enter Year:"))
def display(self):
try:
if self.d>31:
raise ValueError("Day value is greater than 31")
if self.m>12:
raise ValueError("Month Value is Greater than 12")
print("Date is: ", self.d, "-" ,self.m , "-",self.y )
except ValueError as e:
print(e)
#main body
Obj= MyDate()
[Link]()
[Link]()
SLIP 18
Q.1. Core Java:
A) Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method
Overloading) [15 M]
Sol: import [Link].*;
class AreaCalculate{
void area(int r){
[Link]("Area of Cirlce = " + (3.14*r*r));
}
float area(int b, float h){
return b*h/2;
}
double area(Float l, Float db){
return l+db;
}
}
class Slip18A {
public static void main(String args[]){
int r, b, l, db;
float h;
Scanner br = new Scanner([Link]);
[Link]("Enter the radius, base, height, length and breadth : ");
r = [Link]();
b = [Link]();
h = [Link]();
l = [Link]();
db = [Link]();
AreaCalculate ac = new AreaCalculate();
[Link](r);
[Link]("Area of Triangle = " +[Link](b,h));
[Link]("Area of Rectange = " +[Link](l,db));
}
}
B) Write a java program to copy the data from one file into another file, while copying change
the case of characters in target file and replaces all digits by ‘*’ symbol. [25 M]
Sol: import [Link].*;
class Slip18B{
public static void main(String args[]) throws IOException{
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int c;
while ((c=[Link]())!=-1){
if([Link](c)==false){
if([Link](c)){
[Link]([Link](c));
}else if([Link](c)){
[Link]([Link](c));
}
}else{
[Link]('*');
}
}
[Link]();
[Link]();
}
}
Q.2 Python:
A) Create a list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a python program that prints out
all the elements of the list that are less than 5 [15 M]
Sol: lst=[1,1,2,3,5,8,13,21,34,55]
cnt=len(lst)
print("Total number of Element in list is:",cnt)
for i in range(0,cnt):
if lst[i]<5:
print(lst[i])
B) Write a python script to define the class person having members name, address. Create a
subclass called Employee with members staffed salary. Create 'n' objects of the Employee class
and display all the details of the employee. 25 M]
Sol:
SLIP 19
Q.1. Core Java:
B) Create an Applet that displays the x and y position of the cursor movement using Mouse and
Keyboard. (Use appropriate listener) [25 M]
Sol:
Q.2 Python:
A) Write a Python GUI program to accept a number form user and display its multiplication table
on button click. [15 M]
Sol:
B) Define a class named Shape and its subclass(Square/ Circle). The subclass has an init
function which takes an argument (Lenght/redious). Both classes should have methods to
calculate area and volume of a given shape. [25 M
Sol: class Shape:
pass
class Square(Shape):
self.l=l2
def SArea(self):
a=self.l * self.l
print("Area of Square:", a)
def SPerimeter(self):
p=4 * self.l
print("Perimeter of Square:",p)
class Circle(Shape):
self.r=r2
def CArea(self):
print("Area of Circle:", a)
def SCircumference(self):
print("Circumference of Circle:",c)
#main body
obj=Square(l1)
[Link]()
[Link]()
obj=Circle(r1)
[Link]()
[Link]()
SLIP 20
Q.1. Core Java:
A) Write a java program using AWT to create a Frame with title “TYBBACA”, background color
RED. If user clicks on close button then frame should close. [15 M]
Sol: import [Link].*;
import [Link].*;
class Slip20A {
public static void main(String args[]) {
JFrame frame = new JFrame("TYBBACA");
[Link](400, 400);
[Link](JFrame.EXIT_ON_CLOSE);
[Link]().setBackground([Link]);
[Link](true);
}
}
B) Construct a Linked List containing name: CPP, Java, Python and PHP. Then extend your java
program to do the following:
i. Display the contents of the List using an Iterator
ii. Display the contents of the List in reverse order using a List Iterator. [25 M]
Sol: import [Link].*;
public class Slip20B{
public static void main (String args[]){
LinkedList al = new LinkedList<>();
[Link]("CPP");
[Link]("JAVA");
[Link]("Python");
[Link]("PHP");
[Link]("Display content using Iterator...");
Iterator il=[Link]();
while([Link]()){
[Link]([Link]());
}
[Link]("Display Content Revverse Using ListIterator");
ListIterator li1=[Link]();
while([Link]()){
[Link]();
}
while([Link]()){
[Link]("" + [Link]());
}
}
Q.2 Python:
A) Write a python program to create a class Circle and Compute the Area and the
circumferences of the circle.(use parameterized constructor) [15 M]
Sol:
B) Write a Python script to generate and print a dictionary which contains a number (between 1
and n) in the form(x,x*x). Sample Dictionary (n=5) Expected Output: {1:1, 2:4, 3:9, 4:16, 5:25}
[25 M]
Sol: dict={}
n=int(input("How many numbers do you want to add in Dictionar:"))
for x in range(1,n+1):
dict[x]=x*x
print(dict)
SLIP 21
Q.1. Core Java:
A) Write a java program to display each word from a file in reverse order. [15 M]
Sol: import [Link].*;
import [Link];
class Slip21A{
public static void main(String args[]) throws IOException{
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
try (Scanner dr = new Scanner(fr)) {
while([Link]()){
String s=[Link]();
StringBuffer buffer = new StringBuffer(s);
buffer=[Link]();
String ans = [Link]();
[Link](ans);
}
}catch(Exception e){
[Link]("Error...!");
}
[Link]();
[Link]();
}
}
B) Create a hashtable containing city name & STD code. Display the details of the hashtable.
Also search for a specific city and display STD code of that city. [25 M]
Sol: import [Link].*;
import [Link].*;
Q.2 Python:
A) Define a class named Rectangle which can be constructed by a length and width. The
Rectangle class has a method which can compute the area and Perimeter. [15 M]
Sol:
B) Write a Python program to convert a tuple of string values to a tuple of integer values.
Original tuple values: (('333', '33'), ('1416', '55')) New tuple values: ((333, 33), (1416, 55)) [25 M]
Sol: def Convert_Fun(tuple_str):
result = tuple((int(x[0]), int(x[1])) for x in tuple_str)
return result
tuple_str = (('333', '33'), ('1416', '55'))
print("Original tuple values:")
print(tuple_str)
print("\nNew tuple values:")
print(Convert_Fun(tuple_str))
SLIP 22
Q.1. Core Java:
switch(num){
case 1 :
if ([Link]()) {
[Link]("File created : " + [Link]());
} else {
[Link]("File already exists.");
}
case 2 :
[Link]("Enter New File Name : ");
String newone = [Link]();
File newfile =new File(newone);
if([Link](newfile)){
[Link]("File renamed");a
}else{
[Link]("Sorry! the file can't be renamed");
}
break;
case 3 :
if ([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
break;
case 4 :
[Link]("File Location : " +[Link]());
break;
default :
[Link]("Wrong Number ..!");
break;
}
}
}
Q.2 Python:
A) Write a python class to accept a string and number n from user and display n repetition of
strings by overloading * operator. [15 M]
Sol:
public Slip23B(){
[Link](600,500);
[Link](200,200);
[Link](OpenItem);
[Link](SaveItem);
[Link](QuitItem);
[Link](UndoItem);
[Link](RedoItem);
[Link](CutItem);
[Link](CopyItem);
[Link](PasteItem);
[Link](OpenIcon);
[Link](SaveIcon);
[Link](QuitIcon);
[Link](UndoIcon);
[Link](RedoIcon);
[Link](CutIcon);
[Link](CopyIcon);
[Link](PasteIcon);
[Link](filMenu);
[Link](filEdit);
[Link](filSearch);
[Link](menuBar);
[Link](true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Q.2 Python:
A) Write a Python GUI program to create a label and change the label font style (font name,
bold, size) using tkinter module. [15 M]
Sol:
B) Create a class circles having members radius. Use operator overloading to add the radius of
two circle objects. Also display the area of circle. [25 M]
Sol:
SLIP 24
Q.1. Core Java:
A) Write a java program to count number of digits, spaces and characters from a file. [15 M]
Sol: import [Link].*;
class Slip24A{
public static void main(String args[]) throws IOException{
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int c;
int letter=0;
int space=0;
int num=0;
int other=0;
while ((c=[Link]())!=-1){
if([Link](c)){
num ++;
}else if([Link](c)){
letter++;
}else if([Link](c)){
space++;
}else{
other ++;
}
}
[Link]("Numbers : " + num + "\nLetters : "+letter+"\nSpace : "+space+"\nSpecial
Characters : "+other);
[Link]();
[Link]();
}
}
B) Create a package TYBBACA with two classes as class Student (Rno, SName, Per) with a
method disp() to display details of N Students and class Teacher (TID, TName, Subject) with a
method disp() to display the details of teacher who is teaching Java subject. (Make use of
finalize() method and array of Object) [25 M]
Sol: import TYBBACA.*;
import [Link].*;
Q.2 Python:
A) Write a Python Program to Check if given number is prime or not. Also find factorial of the
given no using user defined function. [15 M]
Sol: def Prime(num):
flag=0
for i in range(2,num):
if num%i==0 :
flag=1
break
if flag==0:
print("Number is Prime")
else:
print("Number is Not Prime")
def Fact(num):
f=1
for i in range(1,num+1):
f=f*i
print("Factorial of Given number is:",f)
#main body
SLIP 25
Q.1. Core Java:
A) Write a java program to check whether given string is palindrome or not. [15 M]
Sol: import [Link];
public class Slip25A {
public static void main(String args[]){
int i=0,h=0;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
String str = [Link]();
int j= [Link]()-1;
while(i<j){
if([Link](i++) != [Link](j--)){
h=h+i;
}
}
if(h>0){
[Link]("String is not palindrome");
}else{
[Link]("String is palindrome");
}
} catch (Exception e) {}
}
}
B) Create a package named Series having three different classes to print series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers Write a java program to generate ‘n’ terms of the above series. [25 M]
Sol: import [Link];
public class Slip25A {
public static void main(String args[]){
int i=0,h=0;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter String : ");
String str = [Link]();
int j= [Link]()-1;
while(i<j){
if([Link](i++) != [Link](j--)){
h=h+i;
}
}
if(h>0){
[Link]("String is not palindrome");
}else{
[Link]("String is palindrome");
}
} catch (Exception e) {
}
}
Q.2 Python:
A) Write a Python function that accepts a string and calculate the number of upper case letters
and lower case letters. Sample String : 'The quick Brow Fox' Expected Output : No. of Upper
case characters : 3 No. of Lower case Characters : 12 [15 M]
Sol:
B) Write a Python script to Create a Class which Performs Basic Calculator Operations. [25 M]
Sol: class MathOp:
def AddOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a + self.b
print("Addition is:",self.c)
def SubOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a - self.b
print("Sub is:",self.c)
def MulOp(self):
self.a=int(input("Enter first no:"))
self.b=int(input("Enter Second no:"))
self.c= self.a * self.b
print("Addition is:",self.c)
print("Multiplication is:",self.c)
#main body
obj=MathOp()
while True:
print("\n1. Addtion")
print("2. Substraction")
print("3. Multiplication")
print("4. Exit")
A) Write a java program to display ASCII values of the characters from a file. [15 M]
Sol: import [Link].*;
class Slip26A{
public static void main(String args[]) throws IOException{
char ch;
FileReader fr = new FileReader("[Link]");
int c;
while ((c=[Link]())!=-1){
ch=(char)c;
if([Link](ch)==false && ([Link](c)==false)){
[Link]("ASCII "+ch+" : "+ c);
}
}
[Link]();
}
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
Q.2 Python:
B) Write Python GUI program which accepts a sentence from the user and alters it when a
button is pressed. Every space should be replaced by *, case of all alphabets should be
reversed, digits are replaced by?. [25 M]
Sol:
SLIP 27
Q.1. Core Java:
A) Write a java program to accept a number from user, If it is greater than 1000 then throw user
defined exception “Number is out of Range” otherwise display the factors of that number. (Use
static keyword) [15 M]
Sol:
import [Link].*;
class NumOutRange extends Exception{}
class Slip27A{
static int n;
public static void main( String args[]){
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Number : ");
n = [Link]([Link]());
if(n>1000){
throw new NumOutRange();
}else{
for(int i=1; i<n; i++){
if(n%i==0){
[Link](i + " ");
}
}
}
} catch (NumOutRange nz) {
[Link]("Num is out of range..!");
}
catch (Exception e){
[Link](""+[Link]());
}
}
}
B) Write a java program to accept directory name in TextField and display list of files and
subdirectories in List Control from that directory by clicking on Button. [25 M]
Sol: import [Link].*;
import [Link].*;
import [Link].*;
public Slip27B(){
[Link](new FlowLayout());
[Link](400,400);
[Link](true);
l1 = new Label("Enter Directory ");
t1 = new TextField(20);
l = new List(10);
b1 = new Button("Display");
[Link](50,100,80,80);
[Link](50,150,80,80);
[Link](50,200,80,80);
[Link](50,300,100,100);
add(l1);
add(t1);
add(b1);
add(l);
[Link](this);
}
A) Write a Python program to unzip a list of tuples into individual lists. [15 M]
Sol: l = [(1,2), (3,4), (8,9)]
print(list(zip(*l)))
B) Write Python GUI program to accept a decimal number and convert and display it to binary,
octal and hexadecimal number. [25 M]
Sol:
SLIP 28
Q.1. Core Java:
A) Write a java program to count the number of integers from a given list. (Use Command line
arguments). [15 M]
Sol:
B) Write a java Program to accept the details of 5 employees (Eno, Ename, Salary) and display
it onto the JTable. [25 M]
Sol: import [Link].*;
public class Slip28B {
JFrame f;
JTable j;
Slip28B(){
f = new JFrame();
[Link]("Employee Details");
String data[][] = {
{"1","Radhika Sapkal","50,000"},
{"2","Ramesh Devakar","20,000"},
{"3","Hardik Shrinivas","25,000"},
{"4","Bhihari Kumar","20,000"},
{"5","Swaraghini Pawar","15,000"},
};
String[] columnNames = {"Eno", "Ename", "Salary" };
j = new JTable(data, columnNames);
[Link](30,40,200,300);
JScrollPane sp = new JScrollPane(j);
[Link](sp);
[Link](500,200);
[Link](true);
}
Q.2 Python:
A) Write a Python GUI program to create a list of Computer Science Courses using Tkinter
module (use Listbox). [15 M]
Sol:
B) Write a Python program to accept two lists and merge the two lists into list of tuple. [25 M]
Sol: lst1=[1,2,3,5]
lst2=["SVPM","Baramati"]
t1=tuple(lst1)
t2=tuple(lst2)
t3=t1 + t2
print(t3)
SLIP 29
Q.1. Core Java:
A) Write a java program to check whether given candidate is eligible for voting or not. Handle
user defined as well as system defined Exception. [15 M]
Sol: import [Link].*;
class NumOutRange extends Exception{}
class Slip29A{
static int n;
public static void main( String args[]){
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Age : ");
n = [Link]([Link]());
if(n<18){
throw new NumOutRange();
}else{
[Link]("You Are eligible For Voting :) ");
}
} catch (NumOutRange nz) {
[Link]("You Are Not eligible For Voting ..... !");
}
catch (Exception e){}
}
}
B) Write a java program using Applet for bouncing ball. Ball should change its color for each
bounce. [25 M]
Sol: import [Link].*;
import [Link].*;
import [Link].*;
public class Slip29B extends Applet implements MouseListener, Runnable {
Thread t = null;
int x1 = 10, x2 = 10, x3 = 10, x4 = 10;
int y1 = 300, y2 = 300, y3 = 300, y4 = 300;
int flagx1, flagy1, flagx2, flagy2;
int flagx3, flagy3, flagx4, flagy4;
[Link]([Link]);
[Link](x1, y1, 20, 20);
if (flagx1 == 1)
y1 -= 2;
else if (flagx1 == 0)
y1 += 2;
if (flagy1 == 0)
x1 += 4;
else if (flagy1 == 1)
x1 -= 4;
[Link]([Link]);
[Link](x2, y2, 20, 20);
if (flagx2 == 1)
y2 -= 4;
else if (flagx2 == 0)
y2 += 4;
if (flagy2 == 0)
x2 += 3;
else if (flagy2 == 1)
x2 -= 3;
[Link]([Link]);
[Link](x3, y3, 20, 20);
if (flagx3 == 1)
y3 -= 6;
else if (flagx3 == 0)
y3 += 6;
if (flagy3 == 0)
x3 += 2;
else if (flagy3 == 1)
x3 -= 2;
[Link]([Link]);
[Link](x4, y4, 20, 20);
if (flagx4 == 1)
y4 -= 5;
else if (flagx4 == 0)
y4 += 5;
if (flagy4 == 0)
x4 += 1;
else if (flagy4 == 1)
x4 -= 1;
}
}
/*
* <applet code="[Link]" width="300" height="300">
* </applet>
*/
Q.2 Python:
A) Write a Python GUI program to calculate volume of Sphere by accepting radius as input.
[15 M]
Sol: from tkinter import*
top=Tk()
[Link]('400x400+400+300')
def calvolume():
n=int([Link]())
v=(4/3)*3.14*n*n*n
print("vol",v)
numberv=StringVar()
e1 = Entry(top,textvariable=numberv).pack()
[Link]()
B) Write a Python script to sort (ascending and descending) a dictionary by key and value.
[25 M]
Sol: names = {1:'Sun' ,2:'Mon' ,4:'Wed' ,3:'Tue' ,6:'Fri' ,5:'Thur' }
#print a sorted list of the keys
print(sorted([Link]()))
#print the sorted list with items.
print(sorted([Link]()))
SLIP 30
Q.1. Core Java:
A) Write a java program to accept a number from a user, if it is zero then throw user defined
Exception “Number is Zero”. If it is non-numeric then generate an error “Number is Invalid”
otherwise check whether it is palindrome or not. [15 M]
Sol: import [Link].*;
class Numberiszero extends Exception{}
class Slip30A{
public static void main( String args[]){
int r,sum=0,temp;
int n;
DataInputStream dr = new DataInputStream([Link]);
try {
[Link]("Enter Number : ");
n = [Link]([Link]());
if(n==0){
throw new Numberiszero();
}else{
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum){
[Link]("Palindrome Number ");
}else{
[Link]("Not Palindrome");
}
}
} catch (Numberiszero nz) {
[Link]("Number is Zero");
}
catch (NumberFormatException e){
[Link]("Number is Invalid");
}
catch (Exception e){}
}
}
Q.2 Python:
A) Write a Python GUI program to accept a string and a character from user and count the
occurrences of a character in a string. [15 M]
Sol:
B) Python Program to Create a Class in which One Method Accepts a String from the User and
Another method Prints it. Define a class named Country which has a method called print
Nationality. Define subclass named state from Country which has a mehtod called printState.
Write a method to print state, country and nationality. [25 M]
Sol: class Country:
def AcceptCountry(self):
[Link]=input("Enter Country Name: ")
def DisplayCountry(self):
print("Country Name is:", [Link])
class State(Country):
def AcceptState(self):
[Link]=input("Enter State Name: ")
def DisplayState(self):
print("State Name is:", [Link])
#main body
Obj=State()
[Link]()
[Link]()
[Link]()
[Link]()