Py Lab
Py Lab
num = 11
# Iterate from 2 to n / 2
for i in range(2, num//2):
else:
print(num, "is not a prime number")
Output:
11 is a prime number
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))
BCA543D - PYTHON
PROGRAMMING (2014 Batch)
Total Teaching Hours for No of Lecture
Semester:60 Hours/Week:4
Max Marks:100 Credits:3
Course Objectives/Course
Description
Learn to program and programming paradigms brought in by Python
with a focus on File Handling and Regular Expressions
Learning Outcome
Able to walkthrough algorithm
Improve programming skills
Appreciate Python Programming Paradigm
Hands on Regular Expression
Ability to Text Processing scripts
Write to file handling scripts
Dictionaries
[1] Barry, Paul, Head First Python, 2nd Edition, O Rielly, 2010
11. Create Comma Separate Files (CSV), Load CSV files into internal Data
Structure
12. Write script to work like a SQL SELECT statement for internal Data
Structure made in earlier exercise
13. Write script to work like a SQL Inner Join for an internal Data
Structuremade in earlier exercise
This is the syllabus and solutions for Python Programming Laboratory course
prescribed for 3rd Semester Undergraduate Computer Science and Engineering
Programme starting from the year 2019 at Dr.Ambedkar Institute of Technology
(Dr.AIT), Bengaluru, Karnataka, India.
Course Title: Python Programming Laboratory
Course Title: Python Programming Laboratory
Course Code: 18CSL37
Exam Duration: 3 Hours
No. of Credits: 1 = 0: 0: 1 (L: T: P)
No. of Lecture Hours/Week: 2
Course objectives:
Solution
Devise a Python program to implement the Rock-Paper-Scissor game.
2.
Solution
Write a Python program to perform Jump Search for a given key and
report success or failure. Prompt the user to enter the key and a list of
3. numbers.
Solution
The celebrity problem is the problem of finding the celebrity among n
people. A celebrity is someone who does not know anyone (including
4.
themselves) but is known by everyone. Write a Python program to solve
the celebrity problem.
Solution
Write a Python program to construct a linked list. Prompt the user for
input. Remove any duplicate numbers from the linked list.
5.
Solution
Perform the following file operations using Python
a) Traverse a path and display all the files and subdirectories in each level
till the deepest level for a given path. Also, display the total number of
files and subdirectories.
6.
b) Read a file content and copy only the contents at odd lines into a new
file.
Solution
Create a menu drive Python program with a dictionary for words and their
meanings. Write functions to add a new entry (word: meaning), search for
a particular word and retrieve meaning, given meaning find words with
7. the same meaning, remove an entry, display all words sorted
alphabetically.
Solution
Using Regular Expressions, develop a Python program to
a) Identify a word with a sequence of one upper case letter followed by
lower case letters.
b) Find all the patterns of “1(0+)1” in a given string.
8.
c) Match a word containing ‘z’ followed by one or more o’s.
Prompt the user for input.
Solution
Write a Python program to plot the Line chart in MS Excel Sheet using
XlsxWriter module to display the annual net income of the companies
mentioned below.
9.
MS Excel Data
Solution
Devise a Python program to implement the Hangman Game.
10.
Solution
Course Outcomes
Bloom’s
COs Statements
Level
POs PSOs
CO
s PO PO PO PO PO PO PO PO PO PO1 PO1 PO1 PSO PSO PSO
1 2 3 4 5 6 7 8 9 0 1 2 1 2 3
CO1 3 3 2 2 3 - - - - - - - 1 3 -
CO2 3 2 2 3 3 - - - - - - - 2 3 -
CO3 3 3 3 2 3 - - - - - - - 2 3 -
CO4 2 1 2 2 3 - - - - - - - 1 2 -
CO5 2 1 2 1 3 - - - - - - - 1 1 -
Q1.
a) Write a Python program to print all the Disarium numbers between 1 and
100.
-------------------------------------------------------------------------------------
----------------------------------------
A Disarium number is a number defined by the following process:
A number is be called Disarium if the sum of its digits powered with their respective position is
equal with the number itself.
-------------------------------------------------------------------------------------
----------------------------------------
In this program, we need to print all the disarium numbers between 1 and 100 by following the
algorithm as given below:
ALGORITHM:
STEP 1:
calculate_length() counts the digits present in a number.
Use a while loop to check whether the number variable is equal to 0 or not.
Divide the number variable by 10 and increment the length variable by 1.
Return length.
STEP 2:
sum_of_digits() calculates the sum of digits raised to their respective positions.
Make a call to calculate_length() to get the number of digits present in a given number and
store the value in length variable.
Using the while loop calculate the remainder variable repeatedly by dividing the number with
10.
Calculate the value of result variable by adding the result variable to the remainder variable
raised to power its length position.
STEP 3:
To display all the Disarium numbers between 1 and 100.
Start a loop from 1 to 100, then make a call to sum_of_digits() method for each value from
1 to 100 and store the return value into the result variable. `
If the value of the result is equal to the number, it implies that the given number is a Disarium
number. Hence, display it.
-------------------------------------------------------------------------------------
----------------------------------------
Q1.
b) Write a Python program to encrypt the text using Caesar Cipher technique.
Display the encrypted text. Prompt the user for input and the shift pattern.
-------------------------------------------------------------------------------------
----------------------------------------
In cryptography, Caesar cipher is one of the simplest and most widely known encryption techniques.
It is also known with other names like Caesar's cipher, the shift cipher, Caesar's code or Caesar
shift. This encryption technique is used to encrypt plain text, so only the person you want can read it.
The method is named after Julius Caesar, who used it in his private correspondence.
In this encryption technique, to encrypt our data, we have to replace each letter in the text by some
other letter at a fixed difference. Let's say, there is a letter 'T' then with a right shift of 1 it will
be 'U' and with a left shift of 1 it will become 'S'. So here, the difference is 1 and the direction will
also be same for a text. Either we can use left shift or right, not both in same text.
Plaintext: abcdef
Ciphertext: defghi
Now user can't read this text until he/she have the decryption key. Decryption key is nothing just the
knowledge about how we have shifted those letters while encrypting it. To decrypt this we have to
left shift all the letters by 3.
That was the basic concept of Caesar cipher. If we see this encryption technique in mathematical
way then the formula to get encrypted letter will be:
c = (x + n) mod 26
where, c is the place value of encrypted letter, x is the place value of actual letter and n is the
number that shows us how many positions of letters we have to replace.
On other hand, to decrypt each letter we'll use the formula given below:
c = (x – n) mod 26
-------------------------------------------------------------------------------------
----------------------------------------
In [3]:
# Code to generate Disarium number starts
def calculate_length(number):
length = 0
while number != 0:
length = length + 1
number = number // 10
return length
# sum_of_digits() will calculates the sum of digits powered with their
respective position
def sum_of_digits(number):
remainder = result = 0
length = calculate_length(number)
while number > 0:
remainder = number % 10
result = result + (remainder ** length)
number = number // 10
length = length - 1
return result
def print_disarium():
result = 0
# Displays all Disarium numbers between 1 and 100
print("Disarium numbers between 1 and 100 are \n")
for each_number in range(1, 101):
result = sum_of_digits(each_number)
if result == each_number:
print(each_number)
def user_input():
while True:
print("Enter 1 to Print all the Disarium number between 1 and 100
\n")
print("Enter 2 to Encrypt the text using Caesar Cipher technique \n")
print("Enter 3 to Exit the program \n")
choice = int(input())
print("")
if choice == 1:
print_disarium()
elif choice == 2:
input_text = input("Enter a text: \n")
shift_pattern = int(input("Enter Shift Pattern for encryption:
\n"))
encrypted_text = encrypt_text(input_text, shift_pattern)
print(f"The encrypted text is {encrypted_text} \n")
else:
break
if __name__ == "__main__":
user_input()
Enter 1 to Print all the Disarium number between 1 and 100
1
2
3
4
5
6
7
8
9
89
Enter 1 to Print all the Disarium number between 1 and 100
Enter a text:
abcdef
Enter Shift Pattern for encryption:
3
The encrypted text is defghi
Q2.
-------------------------------------------------------------------------------------
----------------------------------------
rock-paper-scissors (also known as scissors-rock-paper or other variants) is a hand game usually
played between two people, in which each player simultaneously forms one of three shapes with an
outstretched hand.
These shapes are "rock" (a closed fist), "paper" (a flat hand), and "scissors" (a fist with the index
finger and middle finger extended, forming a V).
"Scissors" is identical to the two-fingered V sign (also indicating "victory" or "peace") except that it is
pointed horizontally instead of being held upright in the air.
A simultaneous, zero-sum game, it has only two possible outcomes: a draw, or a win for one player
and a loss for the other.
A player who decides to play rock will beat another player who has chosen scissors ("rock crushes
scissors" or sometimes "blunts scissors"), but will lose to one who has played paper ("paper covers
rock").
If both players choose the same shape, the game is tied and is usually immediately replayed to
break the tie.
-------------------------------------------------------------------------------------
----------------------------------------
In the program, the user gets the first chance to pick the option among rock, paper and scissor. After
that the computer selects from the remaining two choices (randomly), then winner is decided as per
the rules.
-------------------------------------------------------------------------------------
----------------------------------------
In [3]:
# import random module
import random
def main():
while True:
print("Enter choice \n 1. rock \n 2. paper \n 3. scissor \n")
# take the input from user
choice = int(input("User turn: "))
# After coming out of the while loop we print thanks for playing
print("\nThanks for playing")
if __name__ == "__main__":
main()
Winning Rules of the Rock paper scissor game as follows:
rock vs paper -> paper wins
rock vs scissor -> rock wins
paper vs scissor -> scissor wins
Enter choice
1. rock
2. paper
3. scissor
User turn: 1
User choice is: rock
User turn: 2
User choice is: paper
User turn: 3
User choice is: scissor
Q3.
It can be classified as an improvement of the linear search algorithm since it depends on linear
search to perform the actual comparison when searching for a value.
-------------------------------------------------------------------------------------
----------------------------------------
Jump Search Steps
In Jump search, it is not necessary to scan all the elements in the list to find the desired value. We
just check an element and if it is less than the desired value, then some of the elements following it
are skipped by jumping ahead.
After moving a little forward again, the element is checked. If the checked element is greater than
the desired value, then we have a boundary and we are sure that the desired value lies between the
previously checked element and the currently checked element. However, if the checked element is
less than the value being searched for, then we again make a small jump and repeat the process.
Given a sorted list, instead of searching through the list elements incrementally, we search by jump.
The optimal size for jump is N−−√N where the N is the length of the list.
So in our input list list_of_numbers, if we have a jump size of jump then our algorithm will
consider the elements between list_of_numbers[0] and list_of_numbers[0 +
number_of_jumps], if the key element is not found then we will consider the other elements
between list_of_numbers[0 + number_of_jumps] and list_of_numbers[0 +
2*number_of_jumps], again if the key element is not found then we consider the elements
between list_of_numbers[0 + 2*number_of_jumps], and list_of_numbers[0 +
3*number_of_jumps] and so on.
With each jump, we store the previous value we looked at and its index. When we find a set of
values where list_of_numbers[i] < key_element < list_of_numbers[i +
number_of_jumps], we perform a linear search with list_of_numbers[i] as the left-most
element and list_of_numbers[i + number_of_jumps] as the right-most element in our
search block.
For example, consider a list of [1, 2, 3, 4, 5, 6, 7, 8, 9].The length of the list is 9 and
the size of jump is 3. If we have to find the key element 8 then the following steps are performed
using the Jump search technique.
Step 1: First three elements are checked. Since 3 is smaller than 8, we will have to make a jump
ahead.
Step 2: Next three elements are checked. Since 6 is smaller than 8, we will have to make a jump
ahead.
Step 3: Next three elements are checked. Since 9 is greater than 8, the desired value lies within
the current boundary.
Step 4: A linear search is now done to find the value in the array.
-------------------------------------------------------------------------------------
----------------------------------------
In [8]:
import math
return -1
def user_input():
list_of_numbers = list()
total_elements = input("Enter a list of numbers in ascending order with
space between each other: ").split()
for each_element in range(len(total_elements)):
list_of_numbers.append(int(total_elements[each_element]))
if __name__ == "__main__":
user_input()
Enter a list of numbers in ascending order with space between each other: 1 2
3 4 5 6 7 8 9
Enter the Key number to search: 8
Key number 8 is found in Position 8
-------------------------------------------------------------------------------------
----------------------------------------
Step by Step tracing of the above code
Elements -> 1 2 3 4 5 6 7 8 9
Index -> 0 1 2 3 4 5 6 7 8
left = 0
right = 0
list_length = 9
jump = 3
right = min(8, 3)
right is 3
if 1 <= 8 <= 4 condition is False
left = 3
right = min(8, 6)
right is 6
left = 6
right = min(8, 9)
right is 8
break
right = min(8, 8)
right is 8
i = left
i is 6
if 7 == 8: condition is False
i += 1
i is 7
if 8 == 8: condition is True
return 7 here 7 is the index position and not the actual
element
Q4.
Ruby, a columnist for the Times of India, is covering a party. Ruby's job is to identify a celebrity, if
one exists. A celebrity is someone who does not know anyone (including themselves) but is known
by everyone. Now, the problem is to find who the celebrity is in the party by asking questions to all
the guests in the party of the following form, "Excuse me. Do you know the person over there?"
Assume that all of the guests at the party are polite (even the celebrity).
-------------------------------------------------------------------------------------
----------------------------------------
Celebrity Identification Steps
Step 1. The program uses a matrix such that matrix[i][j] is True if and only if i knows j.
-------------------------------------------------------------------------------------
----------------------------------------
In [1]:
def eliminate_non_celebrities(matrix, n):
"""Take an n x n matrix that has m[i][j] = True iff i knows j and return
person who is maybe a celebrity."""
possible_celebrity = 0
n = len(matrix)
for p in range(1, n):
if (matrix[possible_celebrity][p]
or not matrix[p][possible_celebrity]):
possible_celebrity = p
return possible_celebrity
for i in range(n):
if matrix[i][possible_celebrity] is False:
if i != possible_celebrity:
return False
return True
def user_input():
n = int(input('Number of people: '))
# create n x n matrix initialized to False that has m[i][j] = True iff i
knows j
m = []
for i in range(n):
m.append([False]*n)
for i in range(n):
people = input(f'Enter list of people known to {i}: ').split()
for p in people:
p = int(p)
m[i][p] = True
possible_celebrity = eliminate_non_celebrities(m, n)
if check_if_celebrity(possible_celebrity, m, n):
print(f'{possible_celebrity} is the celebrity.')
else:
print('There is no celebrity.')
if __name__ == "__main__":
user_input()
Number of people: 6
Enter list of people known to 0: 3 2 0
Enter list of people known to 1: 1 0 2 3
Enter list of people known to 2: 4 1 3
Enter list of people known to 3:
Enter list of people known to 4: 0 1 2 3 4 5
Enter list of people known to 5: 3
3 is the celebrity.
-------------------------------------------------------------------------------------
----------------------------------------
Program Explanation
1. The user is asked to enter the number of people n.
2. The user is asked to specify the people known to each person and the matrix is updated.
Q5.
Original List:
In the above list, node 2 is repeated thrice, and node 1 is repeated twice. Node current will point to
head, and index will point to node next to current. Start traversing the list till a duplicate is found that
is when current's data is equal to index's data. In the above example, the first duplicate will be found
at position 4. Assign current to another node temp. Connect temp's next node with index's next
node. Delete index which was pointing to duplicate node. This process will continue until all
duplicates are removed.
-------------------------------------------------------------------------------------
----------------------------------------
Steps for removing duplicate number(s) from the linked list
1. Create a class Node which has two data attributes: data and next. The data
attribute next points to the next node in the list.
2. Create another class LinkedList which has two data attributes: head and tail.
4. The remove_duplicate() method will remove duplicate nodes from the list.
a. Define a new node current which will initially point to head.
b. Node temp will point to current and index will always point to node next to current.
c. Loop through the list till current points to null.
d. Check whether current's data is equal to index's data that means index is duplicate
of current.
e. Since index points to duplicate node so skip it by making node next to temp to will point to
node next to index, i.e. temp.next = index.next.
5. The display() method will display the nodes present in the list:
a. Define a node current which will initially point to the head of the list.
b. Traverse through the list till current points to null.
c. Display each node by making current to point to node next to it in each iteration.
-------------------------------------------------------------------------------------
----------------------------------------
In [1]:
# Represent a node of the singly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Represent the head and tail of the singly linked list
def __init__(self):
self.head = None
self.tail = None
if self.head == None:
return
else:
while current != None:
# Node temp will point to previous node to index.
temp = current
# Index will point to node next to current
index = current.next
if __name__ == "__main__":
user_input()
Please enter the elements in the linked list: 1 2 3 2 2 4 1
Original List:
1
2
3
2
2
4
1
List after removing duplicate nodes:
1
2
3
4
Q6.
3. If the path exists, then walk through all the file and subdirectories (including root directory)
using os.walk() function.
4. Normalize the paths and count the number of subdirectories and files in each of those
subdirectories.
5. Display the names of subdirectories and files in subdirectories (including root directory).
os.path.exists(path)
Return True if path refers to an existing path. Returns False for broken symbolic links. On some
platforms, this function may return False if permission is not granted to access the requested file,
even if the path physically exists.
os.path.normpath(path)
Normalize a pathname by collapsing redundant separators and up-level references so that A//B,
A/B/, A/./B and A/foo/../B all become A/B. On Windows, it converts forward slashes to backward
slashes.
os.walk(topdir[, topdown=True])
Generate the file names in a directory tree by walking the tree either top-down (default) or bottom-up
(topdown = False). Specifying argument topdown is optional. For each directory in the tree rooted at
directory topdir (including topdir itself), it yields a 3-tuple (dirpath, dirnames, filenames).
1. dirpath is a string, the path to the directory.
2. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..').
3. filenames is a list of the names of the non-directory files in dirpath. Note that the names in
the lists contain no path components. To get a full path (which begins with top) to a file or
directory in dirpath, do os.path.join(dirpath, name).
-------------------------------------------------------------------------------------
----------------------------------------
Approach to copy the contents from one file to another file at odd lines
1. Open a file source_file as in_file in read mode.
5. Check the line number which is not divisible by 2 and then write the contents to out_file else
pass.
-------------------------------------------------------------------------------------
-----------------------------------
In [1]:
import os
def display_files():
# Set the directory to start from
print("Enter path to traverse: ")
root_dir = input()
if os.path.exists(root_dir):
dir_count = 0
file_count = 0
for dir_name, sub_dir_list, file_list in os.walk(root_dir):
print(f"Found directory: {dir_name} \n")
# check to ignore starting directory while taking directory count
# normpath returns the normalized path eliminating double slashes
etc.
if os.path.normpath(root_dir) != os.path.normpath(dir_name):
dir_count += 1
for each_file_name in file_list:
file_count += 1
print(f"File name(s) {each_file_name} \n")
print(f"Number of subdirectories are {dir_count} \n")
print(f"Number of files are {file_count} \n")
display_menu()
else:
print("Entered path doesn't exist")
display_menu()
def copy_contents_to_file():
source_file = input("Enter the Source file name: ")
print("\n")
destination_file = input("Enter the Destination file name: ")
print("\n")
try:
with open(source_file) as in_file, open(destination_file, "w") as
out_file:
list_of_lines = in_file.readlines()
for i in range(0, len(list_of_lines)):
if i % 2 != 0:
out_file.write(list_of_lines[i])
except IOError:
print("Error in file names")
def display_menu():
print("Enter your choice")
print("Press 1 --> Display files and directories for a given path and
their count")
print("Press 2 --> Copy the contents present at odd lines to another
file")
print("Press 3 --> Exit the program")
choice = int(input())
if choice == 1:
display_files()
elif choice == 2:
copy_contents_to_file()
else:
exit()
if __name__ == "__main__":
display_menu()
Enter your choice
Press 1 --> Display files and directories for a given path and their count
Press 2 --> Copy the contents present at odd lines to another file
Press 3 --> Exit the program
1
Enter path to traverse:
C:\Test_Data
Found directory: C:\Test_Data
Q7.
def create_dict():
global word_dict
word_dict = {}
ch = "y"
while (ch == "y") or (ch == "Y"):
print("\nEnter word:", end="")
word = input()
print("\nEnter meaning:", end="")
meaning = input()
word_dict[word] = meaning
print("\nDo you want to continue adding words(y or n):", end="")
ch = input()
def add_word():
global word_dict
print("\nEnter word:", end="")
word = input()
print("\nEnter meaning:", end="")
meaning = input()
word_dict[word] = meaning
def find_meaning(w):
return word_dict[w]
def find_word_same_meaning(mng):
words = []
for w, m in word_dict.items():
if mng == m:
words.append(w)
return words
def display_sorted():
for w, m in word_dict.items():
print(f"{w} ==> {m}")
print("Sorted list of words : ")
print(sorted(word_dict.keys()))
def main():
ch = "y"
while ch == "Y" or ch == "y":
print("1: Create new dictionary")
print("2: Add new word")
print("3: Find meaning")
print("4: Find word with same meaning")
print("5: Display sorted list of words")
print("6: Quit")
print("Enter Choice: ", end="")
option = int(input())
if option == 1:
create_dict()
elif option == 2:
add_word()
elif option == 3:
print("Enter word:", end="")
word = input()
print("Meaning:%s" % (find_meaning(word)))
elif option == 4:
print("Enter meaning:", end="")
meaning = input()
print("Words with same meaning:", end="")
print(find_word_same_meaning(meaning))
elif option == 5:
display_sorted()
elif option == 6:
exit()
if __name__ == "__main__":
main()
1: Create new dictionary
2: Add new word
3: Find meaning
4: Find word with same meaning
5: Display sorted list of words
6: Quit
Enter Choice: 1
Enter word:a
Enter meaning:apple
Enter word:b
Enter meaning:bat
Enter word:c
Enter meaning:cat
Enter word:d
Enter meaning:dog
Enter word:e
Enter meaning:egg
Enter word:kitten
Enter meaning:cat
Q8.
To check if the sequence of one upper case letter followed by lower case letters we use regular
expression [A-Z]+[a-z]+$
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive
sequence of 0's.
First compile a pattern which follows 1(0+)1 using re.compile(regex) method. Search a first sub-
string in original string which follows 1(0+)1 pattern using pattern.search(string) method.
substr = pattern.search(string) returns None if it doesn't find the given regex as sub-
string in original string otherwise it returns first matched sub-string which follows 1(0+)1 pattern.
substr.start() gives us starting index of matched regex and substr.end() gives us ending
index of matched regex. Whenever we find regex as sub-string then increase count by 1 and again
search for given regex starting from ending index of previous sub-string. The patterns are allowed
to overlap.
Compile a pattern which follows zo+\w*, that matches a word which contains 'z' followed by one
or more o's.
Then pass a string to the findall() method. This method returns the list of the matched strings. If
the length of this list is equal to zero then it doesn't contain a matched string.
-------------------------------------------------------------------------------------
----------------------------------------
In [19]:
import re
# searching pattern
if pattern.search(user_input):
print("String pattern match success \n")
else:
print("String fails the pattern \n")
def count_pattern(user_input):
# search regex '10+1' in original string search() function return first
occurrence
# of regex '10+1' otherwise None '10+1' means sub-string starting and
ending with 1
# and at least 1 or more zeros in between
count = 0
pattern = re.compile("10+1")
substr = pattern.search(user_input)
# search for regex in original string until we are done with complete
string
while substr != None:
# if we find any occurrence then increase count by 1
count = count + 1
def z_followed_by_o(user_input):
# Regex \w * zo+\w * will match text that contains 'z', followed by one
or more 'o'
pattern = re.compile("zo+\w*")
# The findall() method returns all matching strings of the regex pattern
match_object = pattern.findall(user_input)
# Main
if __name__ == "__main__":
menu()
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 1
Enter a string with a sequence of Upper and Lower case letters:
Arunachalpradesh
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 1
Enter a string with a sequence of Upper and Lower case letters: madhyaPradesh
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 1
Enter a string with a sequence of Upper and Lower case letters: MadhyaPradesh
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 1
Enter a string with a sequence of Upper and Lower case letters: andhrapradesh
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 2
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 3
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 3
No match
1 --> Identify a word with a sequence of one upper case letter followed by
lower case letters
2 --> Find all the patterns of '1(0+)1' in a given string
3 --> Match a word containing 'z' followed by one or more o's
4 --> Exit the program
Enter a number to perform any of the operation: 4
Q9.
Workbook ->The workbook refers to an Excel spreadsheet file. The workbook houses all of
the data that you have entered and allows you to sort or calculate the results. A workbook
that is available to be viewed and edited by multiple users on a network is known as a
Shared Workbook. A single workbook is saved in a file with the .xlsx extension.
Worksheet -> Within the workbook is where you'll find documents called worksheets. Also
known as spreadsheets, you can have multiple worksheets nestled in a workbook. Tabs at
the bottom of the of the screen will indicate which of your worksheets you are currently
working on. This is also known as an active worksheet or active sheet.
Cell -> A cell is a rectangle or block housed in a worksheet. Any data that you want to
enter into your worksheet must be placed in a cell. Cells can be color coded, display text,
numbers and the results of calculations, based on what you want to accomplish. An Active
Cell is one that is currently opened for editing.
Columns and Rows -> Columns and Rows refer to how your cells are aligned. Columns
are aligned vertically while rows are aligned horizontally.
Column and Row headings -> These headings are the lettered and numbered gray
areas found just outside of columns and rows. Clicking on a heading will select the entire row
or column. You can also alter the row height or column width using the headings.
Workspace -> Much like worksheets in a workbook, a workspace allows you to open
numerous files simultaneously.
Ribbon -> Above the workbook is a section of command tabs called the Ribbon. A
multitude of options are found behind each tab of the ribbon
Cell Reference -> A cell reference is a set of coordinates that identifies a specific cell.
It's a combination of letters and numbers. A5, for example, would point to the cell located
where column A and row 5 intersect.
Cell Range -> A Cell range is a collection of cells that have been identified as a group
based on a variety of criteria. By using a colon (:) between cell references, Excel can
determine the range, also known as an array. A range in a row, for example, could look
like A1:C1, telling the formula to look at the cells in a row between A1 and C1,
while B4:D9 would tell the formula to look at all cells in a box bounded by
columns B and D and rows 4 and 9.
-------------------------------------------------------------------------------------
----------------------------------------
About XlsxWriter
XlsxWriter is a Python module for writing files in the Excel 2007+ XLSX file format.
XlsxWriter can be used to write text, numbers, formulas and hyperlinks to multiple worksheets
and it supports features such as formatting and many more, including:
Disadvantages:
-------------------------------------------------------------------------------------
----------------------------------------
Description of the methods used in the program
add_worksheet() -> The add_worksheet() method adds a new worksheet to a workbook. At least
one worksheet should be added to a new workbook.
add_format() -> The add_format() method can be used to create new Format objects which are
used to apply formatting to a cell. You can either define the properties at creation time via a
dictionary of property values or later via method calls.
write_row() -> The write_row() method can be used to write a list of data in one go. Write a row
of data starting from (row, col).
write_column() -> The write_column() method can be used to write a list of data in one go. Write
a column of data starting from (row, col).
add_chart() -> This method is use to create a new chart object that can be inserted into a
worksheet via the insert_chart() Worksheet method. For plotting the Line chart on an excel sheet,
use add_chart() method with type line keyword argument of a workbook object.
insert_chart() -> This method can be used to insert a chart into a worksheet. A chart object is
created via the Workbook add_chart() method where the chart type is specified.
add_series() -> Add a data series to a chart. In Excel a chart series is a collection of information
that defines which data is plotted such as values, axis labels and formatting. The series options that
can be set are:
values: This is the most important property of a series and is mandatory for every chart
object. This option links the chart with the worksheet data that it displays. The data range
can be set using a formula such as "=Sheet1!$B$2:$B$9" or a list with a sheetname, row
and column such as ["Sheet1", 1, 2, 8, 2].
categories: This sets the chart category labels. The category is more or less the same as
the X axis. In most chart types the categories property is optional and the chart will just
assume a sequential series from 1..n.
name: Set the name for the series. The name is displayed in the formula bar. For non-
Pie/Doughnut charts, it is also displayed in the legend. The name property is optional and if it
isn't supplied it will default to Series 1..n. The name can also be a formula such
as =Sheet1!$B$1 or a list with a sheetname, row and column such as ["Sheet1", 0,
2].
set_style() -> Set the chart style type. The set_style() method is used to set the style of the
chart to one of the 48 built-in styles available on the 'Design' tab in Excel. The style index number is
counted from 1 on the top left. The default style is 2.
set_title() -> The set_title() method is used to set properties of the chart title.
set_x_axis() -> The set_x_axis() method is used to set properties of the X axis.
set_y_axis() -> The set_y_axis() method is used to set properties of the Y axis.
close() -> The workbook close() method writes all data to the xlsx file and closes it.
-------------------------------------------------------------------------------------
----------------------------------------
In [8]:
# import xlsxwriter module
import xlsxwriter
data = [
[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
[18.76, 23.15, 16.98, 21.86, 22.07, 12.19, 16.8, 21.2],
[8.376, 9.706, 10.179, 12.733, 14.136, 16.348, 19.478, 12.662],
[1.152, 0.631, 0.139, 0.274, 0.241, 0.596, 2.371, 3.033],
]
Q10.
The word to guess is represented by a row of dashes, representing each letter of the word. In most
variants, proper nouns, such as names, places, and brands, are not allowed. Slang words,
sometimes referred to as informal or shortened words, are also not allowed.
If the guessing player suggests a letter which occurs in the word, the other player writes it in all its
correct positions. If the suggested letter does not occur in the word, the other player draws one
element of a hanged man stick figure as a tally mark.
The player guessing the word may, at any time, attempt to guess the whole word. If the word is
correct, the game is over and the guesser wins. Otherwise, the other player may choose to penalize
the guesser by adding an element to the diagram.
On the other hand, if the other player makes enough incorrect guesses to allow his opponent to
complete the diagram, the game is also over, this time with the guesser losing. However, the
guesser can also win by guessing all the letters or numbers that appears in the word, thereby
completing the word, before the diagram is completed.
The above image shows an example game of Hangman in progress. The underlined letters appear
in the word in their correct places, while the crossed-out letters do not appear, and each crossed-out
letter corresponds to one part of the drawing. In this case, the secret word is “hangman”.
-------------------------------------------------------------------------------------
----------------------------------------
Approach to solve the game
In this game, we set a secret word.
The guesser first has to input his name, and then, will be asked to guess any alphabet.
If the random word contains that alphabet, it will be shown as the output (with correct placement)
else the program will ask you to guess another alphabet.
Guesser will be given length_of_word+2 turns (can be changed accordingly) to guess the complete
word.
If the guesser guesses all the letters in the word within the number of turns then he wins the game
else loses the game.
-------------------------------------------------------------------------------------
----------------------------------------
In [1]:
def play_hangman():
name = input("What is your name? ")
print(f"Hello {name}, Time to play hangman!")
print("Start guessing...")
print("HINT: word is the name of a fruit\n")
# here we set the secret word
word = "apple"
# creates an variable with an empty value
guesses = ""
# determine the number of turns
turns = len(word) + 2
if __name__ == "__main__":
play_hangman()
What is your name? Babloo
Hello Babloo, Time to play hangman!
Start guessing...
HINT: word is the name of a fruit
_
_
_
_
_
Guess a character: z
Wrong guess
You have 6 more guesses
_
_
_
_
_
Guess a character: a
a
_
_
_
_
Guess a character: r
Wrong guess
You have 5 more guesses
a
_
_
_
_
Guess a character: p
a
p
p
_
_
Guess a character: q
Wrong guess
You have 4 more guesses
a
p
p
_
_
Guess a character: p
a
p
p
_
_
Guess a character: c
Wrong guess
You have 3 more guesses
a
p
p
_
_
Guess a character: e
a
p
p
_
e
Guess a character: j
Wrong guess
You have 2 more guesses
a
p
p
_
e
Guess a character: l
a
p
p
l
e
You won the game :-)