Monday, February 13, 2017

Message Encryption and Decryption Python

Suppose you want to send a message to a friend,but you don't want other people to be able to read it
To do this you must disguise the text in some fashion.This Process is called Encryption.The reverse process is called Decryption.

Code::

def encrypt(msg):
    result=''
    for c in msg:
        result=result+" "+str(ord(c))
    return result

def decrypt(msg):
    result=''
    for c in msg.split():
        result=result+chr(int(c))
    return result


msg=input("Enter Secret Message: ")
emsg=encrypt(msg)
print("Encrypted Message: "+emsg)

print("Decrypted Message: "+decrypt(emsg))

Output::


Another method is using rotate 13 i.e convert the entered character to character 13 place ahead that character.


Code::                                                                                                                                       

def char13(c):
    alph="abcdefghijklmnopqrstuvwxyz"
    index=alph.find(c)
    index=(index+13)%26
    return alph[index]

def encrypt(text):
    result=''
    for c in text.lower():
        if 'a'<=c<='z':result=result+char13(c)
        else: result=result+c
    return result

msg=input("Enter Secret Message: ")
emsg=encrypt(msg)
print("Encrypted Message: "+emsg)
print("Decrypted Message: "+encrypt(emsg))


Output::                      
                                                                                                             





Date Conversion from One Format To Another Python

Following Code will convert date entered in one format to another:

Code::

def converter(date):
    day,month,year=date.split('/')
    monthnames=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    return monthnames[int(month)-1]+" "+day+","+year

date=input("Enter Date in DD/MM/YYYY format : ")
print ("Entered Date: "+converter(date))

Output::


Palindrome Testing Recursively Python

Entered string is Palindrome or not can be tested using Recursion as Shown by Following Code::

Code::

def isletter(c):     #function to check that character c is a letter or not
    return ('a'<=c<='z')or ('A'<=c<='Z')

def paltest(line):
    if len(line)<=1:return True
    elif not isletter(line[0]):return paltest(line[1:])      #ignoring first not letter
    elif not isletter(line[-1]):return paltest(line[:-1])    #ignoring last not letter
    elif line[0].lower()!=line[-1].lower():return False      
    else:return paltest(line[1:len(line)-1])                 #palindrome testing recursive call


string=input("Enter any String: ")
if(paltest(string)) : print("Yes,Palindrome")
else: print("Not,Palindrome")

Output::

Saturday, February 11, 2017

Case Conversion Python

Following Code Will Convert The Case of Entered String 
i.e lower to UPPER and UPPER to lower



Code::

def conversion(l):
    li=list(l)
    for i in range(0,len(l)):
        if 'a'<=li[i]<='z': li[i]=chr(ord(li[i])-32)
        elif 'A'<=li[i]<='Z': li[i]=chr(ord(li[i])+32)
    stri=''
    return stri.join(li)

s=input("Enter String: ")
print(conversion(s))


Output::


Standard Deviation Calculator Python

The Standard Deviation is a measure of how spread out numbers are.

Standard Deviation is a quantity expressing by how much the members of a group differ from the mean value for the group.
Its symbol is σ (the greek letter sigma)
Following Code will calculate the Standard Deviation:

Code::
import math
def average(l):             #function to calculate average(mean)
    total=0.0
    for i in l:
        total=total+int(i)
    if(len(l)==0): return 0
    else: return(total/len(l))
    
def standardeviation(l,ave):       #function to calculate standard deviation
    diff=0.0
    for i in l:
        x=int(i)-ave
        diff=diff+x*x
    if(len(l)==0): return 0
    else :return(math.sqrt(diff/len(l)))    


lst=[]
num=input("Enter Values ,enter -1 to end:")
while num!='-1':
    lst.append(num)
    num=input()
ave=average(lst)
print("Average is:",ave)
sd=standardeviation(lst, ave)
print("Standard Deviation :",sd)
        
Output::

Friday, February 10, 2017

Anagram Checking

An Anagram is a word, phrase, or name formed by rearranging the letters of another, such as Hitler woman, formed from mother in law.


Following Code Will Check if the entered Strings are Anagrams or Not ::

Code::

import java.util.*;
public class Anagram 
{
    public static void main(String[] nt) 
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter First String: ");
        String s1=in.nextLine();
        System.out.print("Enter Second String: ");
        String s2=in.nextLine();
        check(s1,s2);              //function to check if the entered strings are anagram
    }
    static void check(String a,String b)
    {   boolean status=true;
        a=a.replaceAll(" ", "");      //removing white spaces from strings
        b=b.replaceAll(" ", ""); 
        char[] s1=a.toLowerCase().toCharArray();    //converting string to character array
        char[] s2=b.toLowerCase().toCharArray();
        if(s1.length!=s2.length)
        {
            status=false;
        }
        else
        {
            Arrays.sort(s1);               //sorting array
            Arrays.sort(s2);
            if(!Arrays.equals(s1, s2))        //checking characters
            {
               status=false;
            }
        }
        if(status)
        {
            System.out.println("Yes these are Anagrams");
        }
        else
        {
            System.out.println("No these are not Anagrams");
        }
    }

}
Output::


More Examples::

  • Debit card = Bad credit
  • Dormitory = Dirty Room
  • The earthquakes = The queer shakes
  • Astronomer = Moon starrer
  • Punishments = Nine Thumps
  • School master = The classroom


Thursday, February 9, 2017

Perfect Number Java

Perfect numbera positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28, 496, and 8,128. 

Code::

import java.util.*;
public class PerfectNumber 
{

    
    public static void main(String[] nt) 
    {
       Scanner in= new Scanner(System.in);
       System.out.print("Enter any Number: ");
       int n=in.nextInt();
       int temp=n;
       int sum=0;
       for(int i=1;i<n;i++)
       {
           if(temp%i==0)
           {
               sum=sum+i;
           }
       }
       if(sum==n)
       {
           System.out.println("Yes it is a Perfect Number");
       }
       else
       {
           System.out.println("No it is not a Perfect Number");
       }
    }
    

}

Output::