Python RESOURCES
EXCERCISES
Q1. Get a string from user. Reverse the order of words in it.
Input:
"hello world !"
Output:
"! world hello"
A1:Code in Python
mesg=raw_input("Input:\n")
mlist=str(mesg)
invstr=""
for i in range (1 , len(mlist)+1):
invstr=invstr+mlist[-i]
print invstr
+++++++++++++++++++++++++++++++++++++++++++++++++++
Q2 Take upto a three digit number as input, print the equivalent of the number in words.
Input:
123
Output:
"one hundred and twenty three".
A2: Code in Python
num=raw_input("Input the number:\n")
list=str(num)
o=list[-1]
t=list[-2]
h=list[-3]
sp=t+o
one={'0':'','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
tens={'0':'and','1':'ten','2':'twenty','3':'thirty','4':'forty','5':'fifty','6':'sixty','7':'seventy','8':'eighty','9':'ninety'}
hun={'1':'one hundred','2':'two hundred','3':'three hundred','4':'four hundred','5':'five hundred','6':'six hundred','7':'seven hundred','8':'eight hundred','9':'nine hundred'}
spl={'11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'fifteen','16':'sixteen','17':'seventeen','18':'eighteen','19':'nineteen'}
if (t=='1'):
print hun[h],spl[sp]
print hun[h],tens[t],one[o]
+++++++++++++++++++++++++++++++++++++++++++++++++
Q3:
Write a python program to get abbreviation of name.
Input:
Aakash Kumar Gupta
Output:
A. K. Gupta
A3:
name=raw_input("Enter the name\n")
list=name.split()
abr=''
for i in range(0,len(list)-1):
x=str(list[i])
y=str(x)
abr+=y[0]
print abr+" "+list[len(list)-1]
+++++++++++++++++++++++++++++++++++++++++++++++
Q4:
Write a function to create a list containing first n prime numbers. The user should enter n as
a command line argument.
A4:
def isprime(startnumber):
startnumber*=1.0
for divisor in range(2,int(startnumber**0.5)+1):
if startnumber/divisor==int(startnumber/divisor):
return False
return True
ran=raw_input("Input the range number\n")
for a in range(2,int(ran)):
if isprime(a):
print a
++++++++++++++++++++++++++++++++++++++++++++
Q5:
Write a recursive function to calculate the sum of first n numbers. Note that you are not
supposed to use the formula directly.
Input:
9
Output:
45
A5:
def sum(n):
if (n==0):
return 0
s=n+sum(n-1)
return s
ran=input("Enter the range \n")
total=sum(ran)
print "The sum = " ,total
+++++++++++++++++++++++++++++++++++++++++++++
Q6
Develop a game which allows user to guess 5 times a number randomly generated between 1 and 20 (This you can vary)
A6:
import random
name=raw_input( "Enter you name\n")
print "Hello ! " , name , "Lets play a game of guessing "
hit=random.ranrange(1,20)
guess=input("Input a number between 1 and 20 \n")
for i in range (1,5):
if (guess<hit):
print "Your guess is too low ! "
if (guess >hit):
print "Your guess is too high ! "
if (guess==hit)
print "B i n g o ! you guessed the correct number in " , i , "chances"
break
+++++++++++++++++++++++++++++++++++++++++++++++++
Q7
To reverse the order of digits while taking input from command line
A7
#!/usr/bin/env python
# This can also be used to print the sum of digits of a given integer from a command line
import sys
num=int(sys.argv[1]) # convert to int
while num:
rem=num % 10 # holds remainder
quot=num / 10 # holds the quotient
num=quot
sys.stdout.write(str(rem))
print '\n'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q8 Code for printing the below given pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
A8
for row in range(1,11):
for col in range(1,row+1):
print col, # The comma important for changing the line.try without comma
print # \n
+++++++++++++++++++++++++++++++++++++++++++++++++++++
Q9
To check if the input string is a palindrome or not .using Recursion .
A9
#!/usr/bin/python
# tests if a string is palindrome of not recursively
import sys
s=str(sys.argv[1] )
def pal(s):
try:
if len(s) == 0 or len(s)==1:
return 'Palindrome'
if s[0] != s[-1]:
return "Not Palindrome"
else:
return pal(s[1:-1])
# stripping off the first and last chars
except: IndexError
print pal(s)
+++++++++++++++++++++++++++++++++++++++++++++++++++++
Q10
Reverses a string recursively
A:10
import sys
def RecRev(s):
if len(s)==1:
# base case
return s
else:
# recursive case
return RecRev(s[1:]) + s[0]
# strip off the first char and append to the end
s=sys.argv[1]
# hold the input
print RecRev(s)
# call the function
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q11
Find Commom items in 2 given lists
A11:
import sys
def common(s1, s2):
List=[]
# start with empty list
for i in s1:
# traverse s1
if i in s2:
L.append(i)
# found, so add to L
return List
print common([1,2,3,4,5], [2,4,6,8,10]) # both lists
#print common(('Guanine', 'Cytocin', 'Adenine'), ['Adenine', 'Thyamine'])
# tuple and list
#print common("This is string 1", "hide and seek")
# version 2 - Using List comprhension
#[i for i in s1 if i in s2]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q12 Program to simulate COPY command .
A12:
#!/usr/bin/python
import sys
source=sys.argv[1] #source file
dest=sys.argv[2] #destination file
def copy(source,dest):
f1=open(source,'r')
# open file for reading
f2=open(dest,'w')
# open dest file for writing
for line in f1:
f2.write(line)
f1.close()
f2.close()
# call the function
copy(source,dest)
++++++++++++++++++++++++++++++++++++++++++++
Q13.
Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with "From" in a sample log file
Sample Line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Build a histogram using a dictionary to count how many messages have come from each email address, and print the dictionary. Add code to the above program to figure out who has the most messages in the file.After all the data has been read and the dictionary has been created, look through the dictionary using a maximum loop (see Section [maximumloop]) to find who has the most messages and print how many messages the person has.
A13.
name = raw_input("Enter file:")
fhand=open(name)
words=list()
lst=list()
counts=dict()
for line in fhand:
line=line.rstrip()
if not line.startswith('From '):continue
words=line.split()
lst.append(words[1])
for x in lst:
counts[x]=counts.get(x,0)+1
bigcount=None
bigword=None
for word,count in counts.items():
if bigcount is None or count>bigcount:
bigcount=count
bigword=word
print bigword,bigcount
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Q14.
Finding Numbers in a Haystack
In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers.
Sample text:
What should you to write programs? 7746
12 1929 8827
Writing prams (or programming) is a creative
7 and rewaing activity. You can wrie programs for
many reasons, rang from making your living to so
8837 a diff data problem to having fun to helping 128
someone else solve a problem. assumes that
needs to know how to program ...
A14.
import re
hand=open('luck.txt')
numlist=list()
num=list()
for line in hand:
line=line.rstrip()
num=re.findall('[0-9]+',line)
if len(num)==0:continue
for x in num:
numlist.append(x)
sum=0
for x in numlist:
sum=sum+int(x)
print sum