You are on page 1of 11

5)Recursive Python program to display the Fibonacci

sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
5)Iterative

def fib (n):

if( n == 0):
return 0
else:
x=0
y=1
for i in range(1,n):
z = (x + y)
x=y
y=z
return y

for i in range(10):
print (fib(i))
6) Write a program that prompts the user
to enter a list of words and stores in a
list only those words whose first letter
occurs again within the word (for
example, 'Baboon'). The program should
display the resulting list.

req_list =[]
i=0
n = int(input(“Enter the number of words to be
entered: “))
while i<n:
input_string = input(“Enter the word: “)
lowercase_input_string = input_string.lower()
input_first_letter = lowercase_input_string[0]
rem_string = lowercase_input_string[1:]
res = rem_string.find(input_first_letter)
if res!= -1:
req_list.append(input_string)
i += 1
7)Write a
version of
a
palindrome
recognizer
that also
accepts
phrase palindromes such as
"Go hang a salami I'm a
lasagna hog.",
"Was it a rat I saw?", "Step
on no pets", "Sit on a
potato pan, Otis",
"Lisa Bonet ate no basil",
"Satan, oscillate my
metallic sonatas",
"I roamed under it as a
tired nude Maori", "Rise to
vote sir", or
the exclamation "Dammit, I'm
mad!". Note that
punctuation, capitalization,
and spacing are usually
ignored."""

import string
ignored = string.punctuation
+ " "

def is_palindrome(str):
cleanstr = ""
for i in str:
cleanstr += "" if i in
ignored else i # I love
Python ternary operator

return cleanstr.lower() ==
cleanstr[::-1].lower()

print is_palindrome("Go hang


a salami I'm a lasagna
hog.")
print is_palindrome("Was it
a rat I saw?")
print is_palindrome("Step on
no pets")
print is_palindrome("Sit on
a potato pan, Otis!")
print is_palindrome("Lisa
Bonet ate no basil")
print is_palindrome("Satan,
oscillate my metallic
sonatas")
print is_palindrome("I
roamed under it as a tired
nude Maori")
print is_palindrome("Rise to
vote sir")
print is_palindrome("Dammit,
I'm mad!")
print is_palindrome("This is
not a palindrome")
8)
def make_ing_form(verb):
ifverb.endswith('ie'):
return verb[:-2] +
'ying'
elif verb.endswith('e') and
(verb[-2].endswith('e') or
len(verb) == 2):
return verb + 'ing'
elif verb.endswith('e'):
return verb[:-1] +
'ing'
elif not (verb[-1]) and
(verb[-2]) and not (verb[-
3]):
return verb + verb[-
1] + 'ing'
else:
return verb + 'ing'
if name == "main":
print(make_ing_form('be'))

print(make_ing_form('lie'))

print(make_ing_form('see'))

print(make_ing_form('move'))

print(make_ing_form('hug'))
9) Define a procedure histogram()
that takes a list of integers and prints
a histogram to the screen. For
example, histogram([4, 9, 7]) should
print the following:
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)

histogram([2, 3, 6, 5])

10) def ispangram(str):


alphabet =
"abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False

return True

string = 'the quick brown fox jumps


over the lazy dog'
if(ispangram(string) == True):
print("Yes")
else:
print("No"
11) Write a program to solve a classic ancient Chinese
puzzle: We count 35 heads and 94 legs among the
chickens and rabbits in a farm. How many rabbits and
how many chickens do we have?

rabbits, chickens = 35, 0

while rabbits >= 0:

legs = rabbits * 4 + chickens * 2

if legs == 92: print ("Rabbits : {} \n Chickens :


{}".format (rabbits, chickens ))

else: rabbits, chickens += -1, 1 else:


print ("There is no integer solution for this
problem")

12) A website requires the users to input username


and password to register. Write a program to check the
validity of password input by users. Following are the
criteria for checking the password: 1. At least 1 letter
between [a-z] 2. At least 1 number between [0-9] 3. At
least 1 character from [$#@] 4. Minimum length of
transaction password: 6 5. Maximum length of
transaction password: 12 6. At least 1 letter between
[A-Z] Your program should accept a sequence of
comma separated passwords and will check them
according to the above criteria. Passwords that match
the criteria are to be printed, each separated by a
comma.
import re
p= input("Input your password")
x = True
while x:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not re.search("[0-9]",p):
break
elif not re.search("[A-Z]",p):
break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
print("Valid Password")
x=False
break

if x:
print("Not a Valid Password")

13) Write a program that maps a list of


words into a list of integers
representing the lengths of the
correponding words. Write it in three
different ways: 1) using a for-loop, 2)
using the higher order function map(),
and 3) using list comprehensions

def
map_to_leng
ths_for(wor
ds):
lengths = []
for word in words:

lengths.append(len(word))
return lengths
def
map_to_lengths_map(words):
return map(len, words)

def
map_to_lengths_lists(words)
:
return [len(word) for
word in words]

if __name__ == "__main__":
words = ['abv', 'try
me', 'test']
print
map_to_lengths_for(words)
print
map_to_lengths_map(words)
print
map_to_lengths_lists(words)

15) Write a program to sort the


(name, age, height) tuples by
ascending order where name is
string, age and height are numbers.
The tuples are input by console. The
sort criteria is: 1: Sort based on
name 2: Then sort based on age; 3:
Then sort by score.
multiple_sort_keys.py
from operator import
itemgetter

people_info = []
while True:
individual_info =
input()

if individual_info
== "":
break
else:

people_info.append(tupl
e((individual_info.spli
t(","))))

people_info.sort(key =
itemgetter(0, 1, 2))
print(people_info)

You might also like