Tuesday, January 31, 2017

Fibonacci Sequence Using Recursion Java

Tags
Fibonacci Sequence:
                                     Basic rule:: next term = Sum of previous two terms

Code::

import java .util.*;
public class Fibonacci 
{    
    public static void main(String[] nt) 
    {
      Scanner in=new Scanner(System.in);
      System.out.print("Enter Number of Terms:");
      int a=in.nextInt();
      for(int i=0;i<a;i++)
      {
          System.out.print(fibonacci(i)+" ");
      }
    }
    public static int fibonacci(int n)
    {  
        if(n<2)
        {
            return n;
        }
        else
        {
            return (fibonacci(n-2)+fibonacci(n-1));
        }
    }
}

Output::


                          

Monday, January 30, 2017

Character Frequency In a String Python

Tags
Question::

Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").

Code::

def char_freq(l):
    d={}
    for i in (range(len(l))):
        if (l[i] in d):
            d[l[i]]=int(d.get(l[i]))+1
        else:
            d[l[i]]=1     
    return d
nt=input("Enter any String:")
n=char_freq(nt)

print(n)

Output::

Call By Value V/S Call By Reference Java

Tags
Call by value: In this approach copy of the current variables are passed to called function.
i.e any change in called function on values is not reflected in main program...

Following code will illustrate this:

Code:
import java.util.*;
public class Value 
{

    public static void main(String[] nt) 
    {
       Scanner in=new Scanner(System.in);
       System.out.print("Enter A:");
       int a=in.nextInt();
       System.out.print("Enter B:");
       int b=in.nextInt();
       swap(a,b);
       System.out.println("After Swapping Outside Swap Function :");
       System.out.println("A:"+a);
       System.out.println("B:"+b);
    }
    public static void swap(int c,int d)
    {
        int temp=d;
        d=c;
        c=temp;
       System.out.println("After Swapping Inside Swap Function :"); 
        System.out.println("A:"+c);
        System.out.println("B:"+d);
    }
}

Output:


Call By Reference: As there are no pointers in java so we can not use & to refer to the variables

Following Code Will Illustrate this:

Code::

import java.util.*;
class Swap
{
    int a,b;
    public void swap(Swap s)
    {
        int temp=s.a;
        s.a=s.b;
        s.b=temp;
    }
}
public class Reference 
{

    public static void main(String[] nt) 
    {   Swap ob=new Swap();
        Scanner in=new Scanner(System.in);
       
        System.out.print("Enter A: ");
       ob.a=in.nextInt();
       System.out.print("Enter B: ");
       ob.b=in.nextInt();
       
       System.out.println("Before Swapping :");
       System.out.println("A:"+ob.a);
       System.out.println("B:"+ob.b);
       
       ob.swap(ob);
       
       System.out.println("After Swapping :");
       System.out.println("A:"+ob.a);
       System.out.println("B:"+ob.b);
        
    }   
}

Output::


Recursion Program Java

Tags
Tower of Hanoi: Puzzle in which there are three towers say A,B,C. and some finite number of disks in increasing order of size downwards.

Objective : Move disks from A to C by following below rules:
   1. Only one disk can be moved at a time,and only the top disk.
   2. At no time it is allowed to place a larger disk on small disk.

Following Code Uses Recursion(Function Calling Itself): 

Code::
import java.util.*;
public class Tower 
{  static int c=0;

    public static void main(String[] nt) 
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter Number of Disks: ");
        int n=in.nextInt();
        System.out.println("Moves:");
        hanoi(n,'A','B','C');
        System.out.println("Total Moves: "+c);
    }
    
    public static void hanoi(int n,char A,char B,char C)
    {   if(n<1)
       {
        System.out.println("Please Enter Finite Number of Disks");
        return;
       }
        
        if(n==1)
        {
            System.out.println("From Tower "+A+" to Tower "+C);
            c++;
            return;
        }
        hanoi(n-1,A,C,B);
        System.out.println("From Tower "+A+" to Tower "+C);
        c++;
        hanoi(n-1,B,A,C);   
    }
}

Output::

PygLatin Python :)

Tags
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Computer" becomes "omputercay." 

Following are the Steps involved:
1.Input the word
2. Converting the String to Lowercase
3. Assign first letter of the word to another variable
4. Removing first letter from the word
5. Concatenating the Strings for Output
Following Program Illustrates it:

word=input("Enter the Word: ")   #input word
temp=word.lower()   #lowercase conversion
first=temp[0]       #first letter
temp=temp[1:]
suffix='ay'
if(len(word)==0):
    print("String is Empty!!")
elif word.isalpha()==False:  #else if statement
    print("Enter only Alphabets!")
else:
    print("Pig Latin translation of "+word+" is ")
    print(temp+first+suffix)



Note: isalpha() function is used to check whether String contains alphabets or not. It gives True when all letters in String are alphabets.

"99 Bottles of Beer"

Tags
Question::
"99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:
99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.
The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.
Your task here is write a Python program capable of generating all the verses of the song.


Code::
l=99
for l in (range(99,1,-1)):

    print(l ,"bottles of beer on the wall," ,l," bottles of beer.\nTake one down, pass it around,",l-1 ,"bottles of beer on the wall.\n")


Output::

Pangram Python

Tags
Question::
pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.

Code::

def panagram(nt):
    check="abcdefghijklmnopqrstuvwxyz"
    for l in check:
        if(l in nt):
            continue
        else:
            return False
    return True           
n=input("Enter Any Text:")
if(panagram(n.lower())):
    print("Yes It is a Pangram")
else:

    print("No It is not a Pangram")

Output::


Sunday, January 29, 2017

Filter Long Words

Tags
Question::

Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.

Code:

def filter_long_words(l,a):
    words=[]
    for j in l:
        if(len(j)>=a):
            words.append(j)
    return words

n=input("Enter words:")
nt=n.split(",")
na=input("Enter Min Length:")
long=filter_long_words(nt,int(na))

print("Words with at least min length:",long)

Output::

Longest Word in a List

Tags
Question::

Write a function find_longest_word() that takes a list of words and returns the length of the longest one

Code::
def longest(l):
    long=0
    word=""
    for j in l:
        if(long<len(j)):
            long=len(j)
            word=j
    return [word,long]

n=input("Enter words:")
nt=n.split(",")
long=longest(nt)

print("Longest Word with length:",long)

Output::

Mapping Python

Tags
Question::
Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words.

Code::

def mapping(l):
    mapped=[]
    for j in l:
        mapped.append(len(j))
    return mapped

n=input("Enter words:")
nt=n.split(",")
mapped=mapping(nt)

print("Another List:",mapped)

Output::

Employee's Management in an Organization

Tags
Following program will help in managing employee's in an organization it ask details for each new employee and have functions for printing details of any employee and increment their salary by 5%.

Code::

import java.util.*;
class employee
{  Scanner in=new Scanner(System.in); 
    private String name;
    private double salary;
    private int year,month,day;
    employee()
    {
        System.out.print("Enter Name of Employee: ");
        name=in.nextLine();
        System.out.print("Enter Salary of Employee: ");
        salary=in.nextDouble();
        System.out.println("Enter Date of Joining(in DD/MM/YYYY format): ");
        System.out.print("Date:");
        day=in.nextInt();
        System.out.print("Month:");
        month=in.nextInt();
        System.out.print("Year: ");
        year=in.nextInt();
    }
    public void increment()
    {
        salary=salary+salary*0.05;
    }
    public void show()
    {
        System.out.println("Details of Employee: ");
        System.out.println("Name: "+name);
        System.out.println("Salary: "+salary);
        System.out.printf("Date of Joining: %d/%d/%d\n",day,month,year);
    }
}
public class Organization 
{
    public static void main(String[] nt) 
    {
        employee[] staff=new employee[2];
        staff[0]=new employee();
        staff[0].increment();
        staff[0].show();
    }
}

Output::


here you can declare any number of employees,i have declared only one and increment and show the details of that particular employee....

Lottery Draw Java

Tags
Following program will produce a ticket number with given no of digits randomly and will help in Lottery Draw :

Code::

import java.util.*;
public class LotteryDraw 
{
    public static void main(String[] nt) 
    {
        Scanner in=new Scanner(System.in);
        System.out.print("How many digits a ticket have: ");
        int k=in.nextInt();
        int [] num=new int[10];
        for(int i=0;i<num.length;i++)
        {
            num[i]=i;
        }
        int [] result=new int[k];
        for(int i=0;i<result.length;i++)
        {
            int r=(int)(Math.random()*10); //here 10 bcz the random function will produce positive value less than 1.0 
            result[i]=num[r];
        }
        System.out.print("So the Jackpot Ticket is: ");
        for(int i=0;i<result.length;i++)
        {
            System.out.print(result[i]);
        }
        System.out.println();
    }
}

Output::


Saturday, January 28, 2017

More Operations on datetime :)

Tags
Suppose we want to Display only current Month, Year or Day. Python allows us to do this through some predefined Functions.
Following Program Illustrates it:

from datetime import datetime
current=datetime.now(); #assigning variable
print(current.year);    #Current year
print(current.month);    #Current month
print(current.day);    #Current date




Functions for Time:

print(current.hour);    #Current Hour
print(current.minute);    #Current Minute
print(current.second);    #Current Second



Date and Time in Python :)

Tags
Python contains Library datetime which allows us to keep track of current Time and Date.
Following Program shows the usage of datetime Library:

from datetime import datetime  #importing datetime library
current=datetime.now();  #assigning variable to current date and time
print(current);



datetime.now() Function is used to get the current date and time.

Note: # keyword is used for Comments.

Common Elements In Two Lists

Tags
Question::
Define a function is_common() that takes two lists and returns True if they have at least one member in common, False otherwise.

Code::

def is_common(d,n):
    for i in d:
        for j in n:
             if(j==i):
              return True
    return False 
n=input("Enter list: ")
nt=n.split(",")    
d=input("Enter another list: ")
dm=d.split(",")
if(is_common(dm,nt)):
    print("Yes There are Common Elements")
else:
    print("No There are no Common Elements")
    

Output::




Searching value in a List

Tags
Question::

Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of aFalse otherwise.

Code::
def is_member(d,n):
    for i in n:
        if(d==i):
            return True
    return False 
n=input("Enter list:")
nt=n.split(",")    
d=input("Enter Value to be searched:")
if(is_member(d,nt)):
    print("Yes it is Present")
else:

    print("No it is not Present")


Output::


String Palindrome or Not Python

Tags
Question::

Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".

Code::
def reverse(l):
    return"".join(l[i] for i in range(len(l)-1,-1,-1)) 
name=input("Enter String:")
rev=reverse(name)
print("Reverse is:",rev)
if(rev==name):
    print("String is Palindrome")
else:

    print("Not a Palindrome")

Output::


Addition and Product of a List Python

Tags
Question::
Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.


Code::

def add(l):
    s=0
    for j in l:
        s=s+int(j)
    return s

def multiply(l):
    m=1
    for j in l:
        m=m*int(j)
    return m

d=input("Enter List: ")
n=d.split(",")
print("Entered List=",n)
print("Addition is:",add(n))
print("Product is:",multiply(n))


Output::


Friday, January 27, 2017

"Rövarspråket" (Swedish for "robber's language")

Tags
Question:: Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".


Code::
def translate(str):
    consonants='bcdfghjklmnpqrstvwxyz'
    print("".join(l+'o'+l if l in consonants else l for l in str))

string=input("Enter Any String: ")

translate(string)


Output::


Vowel or Consonant Python

Tags
Following code will identify that entered character is a vowel or consonant.

Code::

def vowel(str):
    if(str=='a' or str=='e' or str=='i' or str=='o' or str=='u' or str=='A' or str=='E' or str=='I' or str=='O' or str=='U'):
        print("Vowel")
    else:
        print("Consonant")
while True:                                                #for only one character 
    
    a=input("Enter a Character: ")
    if(len(a)==1):
        break
    else:
        print("Try Again!!")
        continue
vowel(a)
    

Output:



Length of a String in Python

Tags
Following code is used to calculate length of a string using user defined length function :

Code::

def length(l):
    count=0
    for j in l:
        count=count+1
    return count
    
a=input("Enter String:")
c=length(a)
print("Length is :",c)

Output:


Greater of three Number in Python

Tags

Functions are defined in python using def keyword .Following will illustrate the concept.

Code::

def max(a,b,c):
    if(a>b and a>c):
        print ("Greater is :",a)
    elif(b>c and b>a):
        print("Greater is : ",b)
    else:
        print("Greater is :",c)
        
     
a=input("Enter First No:")
b=input("Enter Second no.:")
c=input("Enter Third no:")

max(a,b,c)


Output:



List and Tuple Datatype in Python

Tags
List and Tuple Both are datatypes in Python .These are similar to each other and used to store data of different types.But the only difference in list and tuple is that we can edit data in list but we can not edit data in tuple


For Example:

List =['76','23','25','85']

Tuple=('75','6','7')


Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')



Code::

var=input("Enter Values Using Comma ',':")
n=var.split(",") # for constructing list from sequence
d=tuple(n)        # for constructing tuple

print ("List is :",n)
print ("Tuple is :",d)



Output:




Thursday, January 26, 2017

Dictionary datatype Python

Tags
Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.

Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}


Code::


dict={}              #dict is of type dictionary
i=input("Enter any Number:")
for j in (range(1,i+1)):
 dict[j]=j*j
print(dict)


Output: