Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Thursday, March 9, 2017

Inheritance Python

Inheritance is the process of reusing the existing code .
Define new classes from the old one i.e including all features of old classes.

Following Program will illustrate the concept:

Code::


class bankaccount:
    def __init__ (self):
        self.bal=int(input("Enter Initial Balance:"))
   
    def withdraw(self,amt):
        if amt<self.bal:
            self.bal=self.bal-amt
        else:
            raise ValueError ("Insufficient Funds")
   
    def deposit(self,amt):
        self.bal=self.bal+amt
   
    def transfer(self,amt,toacc):
        try:
            self.withdraw(amt)
            toacc.deposit(amt)
        except ValueError as e:
            print("Try Again",e)
    def __str__(self):
        return"Balance is: "+str(self.bal)

class cheque(bankaccount):
    def __init__ (self):
        bankaccount.__init__(self)
        self.cheq={}
    def process(self,amt,number,org):
        try:
            self.withdraw(amt)
        except ValueError as e:
            print("Cheque Returned for",e)
        self.cheq[number]=(org,amt)
    def cheqinfo(self,number):
        if self.cheq.get(number):
            print(self.cheq[number])
        else:
            print("No Such Cheque")
    def withdraw(self,amt):
        print('Withdrawing')
        bankaccount.withdraw(self, amt)

nt=bankaccount()        #object of bankaccount type created
nt.deposit(1500)
print(nt)
nt.withdraw(1500)
print(nt)
nti=bankaccount()          #new object created
nt.transfer(1500, nti)
print(nt,nti)

dn=cheque()
dn.process(1500, 1001, 'nearur')

dn.cheqinfo(1001)

Output::

Thursday, February 16, 2017

Telephone Database (Persistent Variables) Python

Following Code will help in maintaining a telephone database including following commands

1.whois phonenumber -tell the details of a particular Number

2. add phonenumber information-add the new number with the information

3.search keyword-return all numbers having keyword in their information

4.delete-deleting any number from database

5.quit-Halt the application

Code::

import string
import shelve

database=shelve.open("information.db")
print("Commands are: whois,add,search,delete or quit")
c=0
line=input("Command: ")
while line!='quit':
    words=line.lower().split()
    if line=="":
        print("Commands are: whois,add,search,delete or quit")
    elif words[0] =='whois':
        if words[1] in database:
            print(words[1],":",string.capwords(database[words[1]]))
        else:
            print("Not Found Try again!!")
    elif words[0]=='add':
        if words[1] in database:
            print("Already Present")
        else:
            database[words[1]]=" ".join(words[2:])
    elif words[0]=='search':
        for e in database:
            if database[e].find(words[1])!=-1:
                c=1
                print(e,":",string.capwords(database[e]))
                
        if c==0:
            print("Keyword Not found Try again!!")
    elif words[0]=="delete":
        if words[1] in database:del database[words[1]]
        else:print("Not Found Try again!!")
    else:
        print("Command Not Found Please Try again!!")
    line=input("Command: ")
database.close()

Output::

 

Wednesday, February 15, 2017

A Concordance Python

A concordance is an alphabetical listing of the words in a text String,along with the line numbers on which each word occurs.

Code::

def count(line,dct,linenumber):
    for word in line.split():
        lst=dct.get(word,[])
        lst.append(linenumber)
        dct[word]=lst

line=input("Enter text,quit to end: ")
linenumber=0
dct={}
while line!='quit':
    linenumber+=1
    count(line,dct,linenumber)
    line=input()
for el in sorted(dct.keys()):
    print(el,":",dct[el])

Output::

Tuesday, February 14, 2017

Tabulating Club Dues Python

Following Code will tabulate the dues of Members of Club :

Code::

def main():
    fre={}
    print("Enter Dues ,enter quit to end")
    while True:
        line=input()
        if(line=='quit'):break
        words=line.split(':')
        fre[words[0]]=fre.get(words[0],0)+int(words[1])
    for name in fre:
        print(name+" has Paid Rs",fre[name],"in dues")

main()

Output::

Word Frequency Python

Following code will give the frequency of occurrence of words in text:

Code::

def main():
    fre={}
    print("Enter Text ,enter quit to end the text")
    while True:
        line=input()
        if(line=='quit'):break
        for el in line.split():
            fre[el]=fre.get(el,0)+1
    print (fre)

main()

    
Output::

Monday, February 13, 2017

Eliza Python

ELIZA is an early natural language processing computer program created from 1964 to 1966[1] at the MIT Artificial Intelligence Laboratory by Joseph Weizenbaum.[2] Created to demonstrate the superficiality of communication between man and machine.

Code::         #a short example u can increase the conditions 

def reply(line,words):
    if len(words)==0: return "You have to talk to me "
    elif "mother"in words:return "Tell me more about your mother "
    elif "father" in words :return "Tell me more about your father "
    elif words[0]=='i' and words[1]=='feel': return "Why do you feel that way? "
    elif words[-1]=='?': return "What do u want to know? "
    elif words[0]=='i' and words[1]=='think': return "Do you really think so? "
    elif "question" in words:return "What's the question? "
    elif "love" in words:return "I must tell you,Love is Very Complicated Agree? "
    elif "agree" in words:return "Do you agree always with this much ease? "
    elif "no" in words: return"Nice!!,Tell me more "
    else: return "Tell me more "

name=input("Hello, Welcome to NT Therapy Center,What's Your name? ")
print("Type quit to exit")
line=input("Hello "+name+" How can we help you? ")
while line!='quit':
    line=line.lower()
    words=line.split()
    replied=reply(line,words)

    line=input(replied)

Output::

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::

Wednesday, February 1, 2017

Lower Function User Defined Python

Following code will define a lower function to convert all letters of a string to lower case:

Code::

def lower(a):
    x=""
    for i in a:
        if(i>='A' and i<'a'):
            x=x+((chr((ord(i)+32))))     #ord to convert character to ascii value
        else:
            x=x+i
    return x

i=input("Enter any String :")
print(lower(i))

Output::


User Defined String Upper Function Python

Following code defines a function upper which changes the entered string to Upper Case:

Code::

def upper(a):
    x=""                                                 #for returning Upper Case
    for i in a:
        if(i>='a'):                                     #for Not Changing Already upper Case Letters
            x=x+((chr((ord(i)-32))))
        else:
            x=x+i
    return x

i=input("Enter any String :")
print(upper(i))

Output::


Number To String Python

Following Code will convert a number entered by user to the Same Number in Words

Code::

def numtostring(n):
    if (n==0):return ""
    elif(n==1):return "one"
    elif(n==2):return "two"
    elif(n==3):return "three"
    elif(n==4):return "four"
    elif(n==5):return "five"
    elif(n==6):return "six"
    elif(n==7):return "seven"
    elif(n==8):return "eight"
    elif(n==9):return "nine"
    elif(n==10):return "ten"
    elif(n==11):return "eleven"
    elif(n==12):return "twelve"
    elif(n==13):return "thirteen"
    elif(n==14):return "fourteen"
    elif(n==15):return "fifteen"
    elif(n==16):return "sixteen"
    elif(n==17):return "seventeen"
    elif(n==18):return "eighteen"
    elif(n==19):return "nineteen"
    elif(n<=29):return "twenty "+numtostring(n%10)
    elif(n<=39):return "thirty "+numtostring(n%10)
    elif(n<=49):return "forty "+numtostring(n%10)
    elif(n<=59):return "fifty "+numtostring(n%10)
    elif(n<=69):return "sixty "+numtostring(n%10)
    elif(n<=79):return "seventy "+numtostring(n%10)
    elif(n<=89):return "eighty "+numtostring(n%10)
    elif(n<=99):return "ninety "+numtostring(n%10)

def convert(n):
    if(n<=99):
        return numtostring(n)
    elif(n<=999):
        return numtostring(n//100)+' hundred '+numtostring(n%100)
    elif(n<=9999):
        return numtostring(n//1000)+' thousand '+numtostring((n//100)%10)+' hundred '+numtostring((n%100))


i=int(input("Enter Any Number Upto 9999: "))
print(convert(i))
     
Output:


Roman Numeral of Given Input Number Python

Following Code will print the Equivalent Roman Numeral of Input Number :

Code::

def romandigit(n,a,b,c):
    if(n==0):return ""
    elif(n==1):return a
    elif(n==2):return a+a
    elif(n==3):return a+a+a
    elif(n==4):return a+b
    elif(n==5):return b
    elif(n==6):return b+a
    elif(n==7):return b+a+a
    elif(n==8):return b+a+a+a
    elif(n==9):return a+c
    
def romannumber(n):
    if(n>999):
        raise RuntimeError('Not Allowed')
    if(n<=99):
        return romandigit((n//10)%10,'X','L','C')+romandigit(n%10,'I','V','X')
    elif(n<=999):
        return romandigit((n//100)%10,'C','D','M')+romandigit((n//10)%10,'X','L','C')+romandigit(n%10,'I','V','X')

def main():
    i=int(input("Enter Any Number Upto 999:"))
    print(romannumber(i))

main()

Output::

Monday, January 30, 2017

Character Frequency In a String Python

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::

PygLatin Python :)

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"

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

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

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::