Python Assignment
Python Assignment
Python Assignment
1. Write a Python program to print the following string in a specific format (see the output).
Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so
high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
Output :
2. Write a Python program which accept the radius of a circle from the user and compute the
area.
3. Write a Python program which accept the user's first and last name and print them in reverse
order with a space between them.
4. Write a Python program that accept an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
5. Write a Python program to print the documents (syntax, description etc.) of Python built-in
function(s).
Sample function : abs()
Expected Result :
abs(number) -> number
Return the absolute value of the argument.
6. Write a Python program to print the calendar of a given month and year.
Note : Use 'calendar' module.
7. Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days
8. Write a Python program to get the volume of a sphere with radius 6.
9. Write a Python program to get the difference between a given number and 17, if the number
is greater than 17 return double the absolute difference.
10. Write a Python program to test whether a number is within 100 of 1000 or 2000
11. Write a Python program to calculate the sum of three given numbers, if the values are equal
then return thrice of their sum.
12. Write a Python program to get a new string from a given string where "Is" has been added to
the front. If the given string already begins with "Is" then return the string unchanged.
13. Write a Python program to get a string which is n (non-negative integer) copies of a given
string.
14. Write a Python program to find whether a given number (accept from the user) is even or
odd, print out an appropriate message to the user.
15. Write a Python program to get the n (non-negative integer) copies of the first 2 characters of
a given string. Return the n copies of the whole string if the length is less than 2.
16. Write a Python program to test whether a passed letter is a vowel or not.
17. Write a Python program that will accept the base and height of a triangle and compute the
area.
18. Write a Python program to compute the greatest common divisor (GCD) of two positive
integers.
19. Write a Python program to get the least common multiple (LCM) of two positive integers.
20. Write a Python program to sum of three given integers. However, if two values are equal
sum will be zero.
21. Write a Python program to sum of two given integers. However if the sum is between 15 to
20 it will return 20.
22. Write a Python program that will return true if the two given integer values are equal or their
sum or difference is 5.
23. Write a Python program to add two objects if both objects are integer type.
24. Write a Python program to solve (x + y) * (x + y).
Test Data : x = 4, y = 3
Expected Output : (4 + 3) ^ 2) = 49
25. Write a Python program to compute the future value of a specified principal amount, rate of
interest, and number of years
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
26. Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
1
23
456
7 8 9 10
11 12 13 14 15
43. Write a Python program to get the Python version you are using.
44. Write a Python program to display the current date and time.
Assignment (String)
ADJECTIVE NOUN
good boy
bad girl
1) good boy
2) good girl
3) bad boy
4) bad girl
10. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a
string. If the string length is less than 2, return instead the empty string.
Sample String : 'w3resource'
Expected Result : 'w3ce'
Sample String : 'w3'
Expected Result : 'w3w3'
Sample String : ' w'
Expected Result : Empty String
11. Write a Python program to get a string from a given string where all occurrences of its first
char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
12. Write a Python program to get a single string from two given strings, separated by a space
and swap the first two characters of each string.
Sample String : 'abc', 'xyz'
Expected Result : 'xyc abz'
13. Write a Python program to add 'ing' at the end of a given string (length should be at least 3).
If the given string is already ends with 'ing' then add 'ly' instead. If the string length of the given
string is less than 3, leave it unchanged.
Sample String : 'abc'
Expected Result : 'abcing'
Sample String : 'string'
Expected Result : 'stringly'
14. Write a Python program to find the first appearance of the substring 'not' and 'poor' from a
given string, if 'bad' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'.
Return the resulting string.
Sample String : 'The lyrics is not that poor!'
Expected Result : 'The lyrics is good!'
15. Write a Python program to remove the nth index character from a non empty string.
16. Write a Python program to change a given string to a new string where the first and last
chars have been exchanged.
17. Write a Python program to remove the characters which have odd index values of a given
string.
18. Write a Python script that takes input from the user and displays that input back in upper
and lower cases.
19. Write a Python program that accepts a comma separated sequence of words as input and
prints the unique words in sorted form (alphanumerically).
Sample Words : red, white, black, red, green, black
Expected Result : black, green, red, white
20. Write a program that accepts a sentence and calculate the number of upper case letters and
lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
21. Using while loop print an input string in the following pattern (say input string is Kolkata):
K
Ko
Kol
Kolk
Kolka
Kolkat
Kolkata
K
Ko
Kol
Kolk
Kolka
Kolkat
Kolkata
22. Write a program using loop to count the length of an input string
23. Write a program using loop to count number of vowel and consonant of an input string.
24. Write a program using loop for counting number of words in a sentence.
25. Write a program using loop for converting full name to initial:
For example: Atal Bihary Bajpai → A B Bajpai
26. Write a program using loop to check whether a string is palindrome or not. For example
“madam” is a palindrome.
27. Write a program using loop for showing a string in reverse order.
Assignment (List)
Notice that the words in the output strings should all be lower cased and separated by only one
space and make sure your words match the following spellings:
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen,
sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty,
ninety, hundred, thousand
Assignment (Function)
1. Write function Binary2Dec(Binary) that take input a binary number as string and return
the decimal equivalent of it.
2. Write a function EuclideanDist(v1,v2) that take two lists (int/float) as input and return the
Euclidean distance between two list.
3. Write a function MinimumDist(lst, lstLst) that take input a list and a list of list of same
order e.g. lst=[1,2,3] and lstLst=[[1,1,2], [2,4,5], [7,1,3], [1,2,3]] and return the list element
from lstLst which has minimum EuclideanDist when compared to lst.
4. Write a function named find_word_horizontal that accepts a 2-dimensional list of
characters (like a crossword puzzle) and a string (word) as input arguments. This
function searches the rows of the 2d list to find a match for the word. If a match is found,
this functions returns a list containing row index and column index of the start of the
match, otherwise it returns the value None (no quotations).
For example if the function is called as shown below:
crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word='cat'
find_word_horizontal(crosswords,word)
then your function should return
[2,1]
Notice that the 2d input list represents a 2d crossword and the starting index of the horizontal
word 'cat' is [2,1]
s d o g
c u c m
a c a t
t e t k
Note: In case of multiple matches only return the match with lower row index. If you find two
matches in the same row then return the match with lower column index.
c u c m
a c a t
t e t k
Note: In case of multiple matches only return the match with lower column index. If you find two
matches in the same column then return the match with lower row index.
C u c m
A x a t
T e t k
Example 2: if the function is called as shown below:
crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word='cat'
capitalize_word_in_crossword(crosswords,word)
then your function should return:
[['s','d','o','g'],['c','u','c','m'],['a','C','A','T'],['t','e','t','k']]
Notice that the above list is a representation for a 2-dimensional crossword puzzle as shown
below.
s d o g
c u c m
a C A T
t e t k
Note: If both a horizontal and a vertical match is found then only select the horizontal match. For
example, in the above case there is a horizontal match starting at [2,1] and there is also a
veritcal match starting at [1,0]. Notice that only the characters in the horizontal match should be
capitalized in the returned list.
Hint: You should use the functions that you developed in part 1 and part 2 as helper functions
for part 3.
Assignment (Recursion)
1. Write a function named calculate_fibonacci that receives a positive integer 'n' as
parameter and calculates and returns the nth fibonacci number using recursion.
Notes
● Fibonacci numbers are the numbers in the sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...
● The 0th Fibonacci number is 0, the 1st Fibonacci number is 1.
● All other numbers are sum of the previous two numbers.
For example, when your function is called as:
calculate_fibonacci(10)
2. Write a function named calculate_factorial that receives a positive integer 'n' as parameter
and calculates and returns the factorial of n using recursion.
Notes
Factorial is the product of an integer with all the integers below it. For example, the factorial of 5
is 5*4*3*2*1 = 120. Note that the factorial of both 0 and 1 is 1. For example, when your function
is called as:
calculate_factorial(10)
Then, your function should return the number:
3628800
3. Write a function named calculate_exponent that receives two positive integers a and b as
parameter and calculates and returns a to the power of b using recursion. For example, when
your function is called as:
calculate_exponent(5, 3)
Then, your function should return: 125
4. Write a function named nested_list_sum that receives a nested list of integers as parameter
and calculates and returns the total sum of the integers in the list using recursion. Keep in mind
that the inner elements may be integers or other nested lists themselves.
1. Write a user defined function in python to read the content from a text file myfile.txt,
count and display the number of blank spaces present init.
2. Write a function in python to count the number of alphabets present in a text file
“alpha.txt”.
3. Write a function in python to count and display the number of words starting with a vowel
present in a given text file “mytext.txt”.
4. Write a function which reads an already existing file “text1.txt” and write digits (0-9) into a
new text file “DIGIT.TXT” and non digit files into NONDIG.TXT.
5. Write a function in python to count the number of lines present in a text file
“STORY.TXT”.
6. Assuming that a text file named TEXT1.TXT already contains some text written into it.
Write a function named vowelwords(), that reads the file TEXT1.TXT and creates a new
file named TEXT2.TXT , which shall contain only those words from the file TEXT1.TXT
which don’t start with an uppercase vowel.
7. Write an interactive python program to read a text file and display the following :
(i) Frequency table of all the alphabetic characters(ii)Number of numeric characters
present in the file
8. Write a function that accepts a filename as input argument and reads the file and saves
each line of the file as an element in a list (without the new line ("\n")character) and
returns the list. Each line of the file has comma separated values: For example if the
content of the file looks like this:
Lucas,Turing,22
Alan,Williams,27
Layla,Trinh,21
Brayden,Huang,22
Oliver,Greek,20
11. Write a function that accepts a filename as input argument, the file contains the
information about a persons expenses on milk and bread and returns a dictionary that
contains exactly the strings 'milk' and 'bread' as the keys and their floating point values
in a list as values. Each line of the file may start with a 'm' or a 'b' denoting milk or bread
respectively. For example if the contents of the file are:
m000
b251
b354
m100
b531
m010
b245
12. Write a function that accepts a file name as input argument and constructs and returns a
nested dictionary from it. The keys of this dictionary should be last names, and the
values should be dictionaries that contain first names as the keys and integer ages as
the values. Note that the data may contain multiple people with the same last name, but
it will have unique first names. Ignore any lines that start with '#' The file will contain
comma separated values (CSV) For example if the contents of the file are:
#first_name,last_name,age
Matthew,Abbey,65
Chloe,Orion,49
Yohaan,Adams,54
Krishna,Adams,35
Resa,Orion,86
Lucas,Abbey,60
Courtney,Abbey,67
Joseph,Orion,45
Mark,Abbey,60
Eva,Orion,76
13. Write a function named create_grades_dict that accepts a string as the name of a file.
Assuming that the file is a text file which includes name and grades of students, your
function should read the file and return a dictionary with the exact format as shown
below: The format of the input file is:
Student ID, Last_name, Test_x, grade, Test_x, grade, ..
Student ID, Last_name, Test_x, grade, Test_x, grade, ..
Student ID, Last_name, Test_x, grade, Test_x, grade, ..
....
An example of the input file is shown below. Sample Input Output Assuming that
the input file "student_grades.txt" contains the following text:
1000123456, Rubble, Test_3, 80, Test_4 , 80
1000123459, Chipmunk, Test_4, 96, Test_1, 86 , Quiz_1 , 88
Notes:
● Items are seperated by comma and one or more spaces may exist between the
items.
● The "ID" of each student is unique. Two students may have the same Name (but
IDs will be different)
● The "Name" of each student will only include a last name with no punctuation.
Maximum of 15 characters.
● There will be an integer grade for each test (0-100)
● There are only four valid tests, i.e. Test_1, Test_2, Test_3, Test_4. There may be
other grades in the file and you should ignore those grades.
○ Each student may have missing grade(s) for the tests. A missing grades should
be considered as 0.
○ Grades may not be in order i.e. Test_3 may appear before Test_1.
Your function should read the input file, calculate the average test grade for each
student and return a dictionary with the following format:
{'Student_ID':[Last_name,Test_1_grade,Test_2_grade,Test_3_grade,Test_4_grade,aver
age], ...}
For example in the case of sample input file shown above, your function should return
the following dictionary:
{'1000123456': ['Rubble', 0, 0, 80, 80, 40.0], '1000123459': ['Chipmunk', 86, 0, 0, 96,
45.5]}
14. Write a function in python to print the count of word the as an independent word in a text
file STORY.TXT. for example, if the content of the file STORY.TXT is
There was a monkey in the zoo. The monkey was very naughty.
Assignment (Tuple)
1. Write a function that accepts a tuple of positive integers and returns the mean and
median of the integers as a tuple. For example if the input tuple is:
(3, 3, 0, 1, 12, 13, 15, 16)
then your function should return a tuple that contains the mean and median as:
(7.875, 7.5)
You may use (import) the numpy package in your function. Do not use the "statistics" package.
2. Write a function that accepts a dictionary as input and returns a tuple of tuples. That is your
first tuple should be the tuple of all the keys, and the second tuple should be tuple of all the
values in the dictionary. For example if the input dictionary is:
input_dictionary = {1:"a", 2:"b", 3:"c", 4:"d"}
then you should return a tuple(tuple of keys, tuple of values) such as:
((1, 2, 3, 4), ('a', 'b', 'c', 'd'))
1. You are trying to concatenate two strings and you need to write a function to perform the
task. The function takes two arguments. You do not know the type of the first argument
in advance but the second argument is certainly a string. Write a function that takes an
unknown input and a string as input and tries to handle the error when you try to
concatenate this unknown input to the string using the try..except..else clause. The
unknown input could be either an integer or a string or a float. If the concatenation fails
your function should return the value None (exactly without the quotes), If successful
your function should return the resulting string.
2. You are trying to divide two numbers and you need to write a function to perform the
task. The function takes two arguments. The first argument is a float but you are unsure
about the second argument (there is a chance that the second argument could be a
zero). Write a function that takes a float and an unknown input and tries to handle the
error when you try to divide the float by the unknown input using the try..except..else
clause. The unknown input could be either an integer or a string or a float. If the
operation fails your function should return the value None (exactly without the quotes), If
successful your function should return the result.
3. You are trying to modify the content of a list and you need to write a function to perform
the task. The function takes three arguments. The first argument is the list itself, the
second argument is an index 'n' and the third argument is a string. Your job is to set the
'n'th (index) item of the list as the given string and return the modified list if successful. In
case of a failure your function should return the original list. Write a function that
performs this task using the try...except...else statements.
Assignment (OOP)
1. Write a program using python to simulate a Bank with account creation, deposit
and withdraw facility. Create class BankAccount which has methods like (a)
make_account (b) withdraw(account, amount) and (b) deposit(account, amount)
and a variable “balance: will be initialized to 0 after calling make_account() and it
will be increase and decrease with the calling of functions deposit and withdraw
method simultaneously.
2. Write a program to implement a STACK using python. Create class Stack with
following methods: (a) isEmpty (b) push (c) pop (d) peek i.e. top of the Stack (e)
size