Sie sind auf Seite 1von 56

Python program to check if

# given number is prime or not

num = 11

# If given number is greater than 1


if num > 1:

# Iterate from 2 to n / 2
for i in range(2, num//2):

# If num is divisible by any number between


# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")

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

Unit-1 Teaching Hours:10


Introduction and overview
Introduction, What is Python, Origin, Comparison, Comments,
Operators, Variables and Assignment, Numbers, Strings, Lists and
Tuples, Dictionaries, if Statement, while Loop, for Loop and the range()
Built-in Function, Files and the open() Built-in Function, Errors and
Exceptions, Functions, Classes, Modules Syntax and Style Statements
and Syntax, Variable Assignment, Identifiers, Basic Style Guidelines,
Memory Management, Python Application Examples
Unit-2 Teaching Hours:10
Python Objects
Python Objects, Standard Types, Other Built-in Types, Internal Types,
Standard Type Operators, Standard Type Built-in Functions,
Categorizing the Standard Types, Unsupported Types.

Numbers and Strings.Introduction to Numbers, Integers, Floating Point


Real Numbers, Complex Numbers, Operators, Built-in
Functions.Sequences: Strings, Lists, and Tuples, Sequences, Strings,
Strings and Operators, String-only Operators, Built-in Functions, String
Built-in Methods, Special Features of Strings
Unit-3 Teaching Hours:10
Lists
Operators, Built-in Functions, List Type Built-in Methods, Special
Features of Lists, Tuples, Tuple Operators and Built-in Functions,
Special Features of Tuples

Dictionaries

Introduction to Dictionaries, Operators, Built-in Functions, Built-in


Methods, Dictionary Keys, Conditionals and Loops: if statement, else
Statement, elif Statement, while Statement, for Statement, break
Statement, continue Statement, pass Statement, else Statement
Unit-4 Teaching Hours:10
Files and Input/Output
File Objects, File Built-in Function, File Built-in Methods, File Built-in
Attributes, Standard Files, Command-line Arguments, File System, File
Execution, Persistent Storage Modules
Unit-5 Teaching Hours:9
Regular Expressions
Introduction/Motivation, Special Symbols and Characters for REs, REs
and Python
Unit-6 Teaching Hours:11
Errors and Exceptions
What Are Exceptions? Exceptions in Python, Detecting and Handling
Exceptions, Exceptions as Strings, Raising Exceptions, Assertions,
Standard Exceptions

Functions: Functions, Calling Functions, Creating Functions, Formal


Arguments, Positional Arguments, Default Arguments, Why Default
Arguments?, Default Function Object Argument Example, Variable-
length Arguments, Non-keyword Variable Arguments (Tuple), Keyword
Variable Arguments (Dictionary)
Text Books And Reference Books:

[1] Chun, J Wesley, Core Python Programming, Second Edition,


Pearson, 2007 Reprint 2010
Essential Reading / Recommended Reading

[1] Barry, Paul, Head First Python, 2nd Edition, O Rielly, 2010

[2] Lutz, Mark, Learning Python, 4th Edition, O Rielly, 2009

BCA553D - PYTHON PROGRAMMING


LAB (2014 Batch)
Total Teaching Hours for No of Lecture
Semester:60 Hours/Week:4
Max Marks:100 Credits:2
Course Objectives/Course
Description
-
Learning Outcome
-
Unit-1 Teaching Hours:60
List of Programs
1. Implement a sequential search
2. Create a calculator program
3. Explore string functions
4. Implement Selection Sort
5. Implement Stack
6. Read and write into a file
7. Demonstrate usage of basic regular expression

8. Demonstrate use of advanced regular expressions for data validation.

9. Demonstrate use of List


10. Demonstrate use of Dictionaries

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

14. Demonstrate Exceptions in Python


Text Books And Reference Books:
Essential Reading / Recommended Reading
Evaluation Pattern

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:

1. Interpret the use of procedural statements like assignments, conditional


statements, loops and function calls.
2. Infer the supported data structures like lists, dictionaries and tuples
in Python.
3. Illustrate the application of matrices and regular expressions in building the
Python programs.
4. Discover the use of external modules in creating excel files and navigating
the file systems.
5. Describe the need for Object-oriented programming concepts in Python.

Sl. No. Programs


a) Write a Python program to print all the Disarium numbers between 1
and 100.
b) Write a Python program to encrypt the text using Caesar Cipher
1. technique. Display the encrypted text. Prompt the user for input and the
shift pattern.

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

Describe the Python language syntax including control L2


CO1 statements, loops and functions to write programs for a wide
variety problem in mathematics, science, and games.

Examine the core data structures like lists, dictionaries, L3


CO2 tuples and sets in Python to store, process and sort the
data.

Interpret the concepts of Object-oriented programming as L3


CO3 used in Python using encapsulation, polymorphism and
inheritance.

Discover the capabilities of Python regular expression for L2


CO4 data verification and utilize matrices for building
performance efficient Python programs.

Identify the external modules for creating and writing data to L2


CO5 excel files and inspect the file operations to navigate the file
systems.
Course Articulation Matrix (CO-PO Mapping)

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.

For example, 175 is a Disarium number:


As 11 + 72 + 53 = 175

Some other DISARIUM are 89, 135, 175, 518 etc.

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

Let's understand it with an easy example.


For example, suppose we have text "abcdef" to be encrypted. Then what we can do is replace
each of letter present in the text by another letter having fixed difference. Lets say we want right shift
by 3 then each letter of the above text have to replaced by the letter, positioned 3 steps from the
letter.

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)

# Code to generate Disarium number ends

# # Code for Caesar Cipher technique starts


def encrypt_text(input_text, shift_pattern):
cipher_result = ""
# Traverse the plain text
for each_char in input_text:
# Check for empty spaces
if each_char == " ":
cipher_result = cipher_result + each_char
elif each_char.isupper():
# Encrypt the uppercase characters in plain text
cipher_result = cipher_result + chr(
(ord(each_char) + shift_pattern - 65) % 26 + 65
)
else:
# Encrypt the lowercase characters in plain text
cipher_result = cipher_result + chr(
(ord(each_char) + shift_pattern - 97) % 26 + 97
)
return cipher_result

# # Code to apply Caesar Cipher technique end

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

Enter 2 to Encrypt the text using Caesar Cipher technique

Enter 3 to Exit the program

Disarium numbers between 1 and 100 are

1
2
3
4
5
6
7
8
9
89
Enter 1 to Print all the Disarium number between 1 and 100

Enter 2 to Encrypt the text using Caesar Cipher technique

Enter 3 to Exit the program

Enter a text:
abcdef
Enter Shift Pattern for encryption:
3
The encrypted text is defghi

Enter 1 to Print all the Disarium number between 1 and 100

Enter 2 to Encrypt the text using Caesar Cipher technique

Enter 3 to Exit the program

Q2.

Devise a Python program to implement the Rock-Paper-Scissor game.

-------------------------------------------------------------------------------------
----------------------------------------
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").

A play of paper will lose to a play of scissors ("scissors cuts paper").

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.

Winning Rules as follows :

rock vs paper-> paper wins


rock vs scissor-> rock wins
paper vs scissor-> scissor wins
In this game, the randint() inbuilt function is used for generating random integer value within the
given range.

-------------------------------------------------------------------------------------
----------------------------------------
In [3]:
# import random module
import random

# Print multiline instruction perform string concatenation of string


print(
"Winning Rules of the Rock paper scissor game as follows: \n"
+ "rock vs paper -> paper wins \n"
+ "rock vs scissor -> rock wins \n"
+ "paper vs scissor -> scissor wins \n"
)

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

# OR is the short-circuit operator


# if any one of the condition is true
# then it return True value

# looping until user enter invalid input


while choice > 3 or choice < 1:
choice = int(input("Enter valid input: "))

# initialize value of choice_name variable


# corresponding to the choice value
if choice == 1:
choice_name = "rock"
elif choice == 2:
choice_name = "paper"
else:
choice_name = "scissor"

# print user choice


print(f"User choice is: {choice_name}")
print("\nNow it is Computer's turn.......")
# Computer chooses randomly any number among 1 , 2 and 3. Using
randint method of random module
comp_choice = random.randint(1, 3)

# looping until comp_choice value is equal to the choice value


while comp_choice == choice:
comp_choice = random.randint(1, 3)

# initialize value of comp_choice_name variable corresponding to the


choice value
if comp_choice == 1:
comp_choice_name = "rock"
elif comp_choice == 2:
comp_choice_name = "paper"
else:
comp_choice_name = "scissor"

print(f"Computer choice is: {comp_choice_name}")

print(f"{choice_name} V/s {comp_choice_name}")

# condition for winning


if (choice == 1 and comp_choice == 2) or (choice == 2 and comp_choice
== 1):
print("paper wins => ", end="")
result = "paper"
elif (choice == 1 and comp_choice == 3) or (choice == 3 and
comp_choice == 1):
print("rock wins =>", end="")
result = "rock"
else:
print("scissor wins =>", end="")
result = "scissor"

# Print as either user or computer wins


if result == choice_name:
print("<== So User wins ==>")
else:
print("<== So Computer wins ==>")

print("Do you want to play again? (Y/N)")


ans = input()
# if user input n or N then condition is True
if ans == "n" or ans == "N":
break

# 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

Now it is Computer's turn.......


Computer choice is: paper
rock V/s paper
paper wins => <== So Computer wins ==>
Do you want to play again? (Y/N)
y
Enter choice
1. rock
2. paper
3. scissor

User turn: 2
User choice is: paper

Now it is Computer's turn.......


Computer choice is: scissor
paper V/s scissor
scissor wins =><== So Computer wins ==>
Do you want to play again? (Y/N)
y
Enter choice
1. rock
2. paper
3. scissor

User turn: 3
User choice is: scissor

Now it is Computer's turn.......


Computer choice is: rock
scissor V/s rock
rock wins =><== So Computer wins ==>
Do you want to play again? (Y/N)
n

Thanks for playing

Q3.

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
numbers.
-------------------------------------------------------------------------------------
----------------------------------------
Jump Search
Similar to Binary Search, Jump Search or Block Search is an algorithm only for ordered (sorted)
lists. The major idea behind this algorithm is to make less comparisons by skipping a definite amount
of elements in between the elements getting compared leading to less time required for the
searching process.

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

def jump_search(list_of_numbers, key):


list_length = len(list_of_numbers)

# Calculate jump size


jump = int(math.sqrt(list_length))

left, right = 0, 0 # These are the index values

# Find the block where key element is present (if it is present)


while left < list_length and list_of_numbers[left] <= key:
right = min(list_length - 1, left + jump)
if list_of_numbers[left] <= key <= list_of_numbers[right]:
break
left += jump

if left >= list_length or list_of_numbers[left] > key:


return -1

right = min(list_length - 1, right)


i = left
# Do linear search for key element in the block
while i <= right and list_of_numbers[i] <= key:
if list_of_numbers[i] == key:
return i # Return the position of the key element
i += 1

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]))

key = int(input("Enter the Key number to search: "))

index = jump_search(list_of_numbers, key)


if index == -1:
print("Entered key is not present")
else:
print(f"Key number {key} is found in Position {index + 1}")

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

while 0 < 9 and 1 <= 8:

right = min(8, 3)

right is 3
if 1 <= 8 <= 4 condition is False

left = 3

while 3 < 9 and 4 <= 8:

right = min(8, 6)

right is 6

if 4 <= 8 <= 7: condition is False

left = 6

while 6 < 9 and 7 <= 8:

right = min(8, 9)

right is 8

if 7 <= 8 <= 9: condition is True

break

right = min(8, 8)

right is 8

i = left

i is 6

while 6 <= 8 and 7 <= 8:

if 7 == 8: condition is False

i += 1

i is 7

while 7 <= 8 and 8 <= 8:

if 8 == 8: condition is True
return 7 here 7 is the index position and not the actual
element

print -> i + 1 position

Q4.

The celebrity problem is the problem of finding


the celebrity among n people. A celebrity is
someone who does not know anyone (including
themselves) but is known by everyone. Write a
Python program to solve the celebrity problem.
-------------------------------------------------------------------------------------
----------------------------------------
The celebrity problem is the problem of finding the celebrity among n people.

Consider the below mentioned scenario:

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).

Below are the steps in identifying 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.

Step 2. Create two


functions eliminate_non_celebrities() and check_if_celebrity().

Step 3. The function eliminate_non_celebrities() returns a candidate who maybe a


celebrity. It takes the matrix and n as argument.

Step 4. The function check_if_celebrity() determines whether a person is a celebrity. It


takes the matrix, possible_celebrity and n as argument.
Step 5. The function eliminate_non_celebrities() works on the principle that
if matrix[i][j] = True, that is i knows j, then i cannot be the celebrity and if matrix[i][j]
= False, that is i does not know j, then j cannot be the celebrity.

Step 6. The function check_if_celebrity() whether possible_celebrity is known by


everyone else and whether possible_celebrity does not know anyone. If so, it returns True.

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

def check_if_celebrity(possible_celebrity, matrix, n):


"""Take an n x n matrix that has m[i][j] = True iff i knows j and return
True if possible_celeb is a celebrity."""
for i in range(n):
if matrix[possible_celebrity][i] is True:
return False

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.

3. A possible celebrity is returned by the function eliminate_non_celebrities().

4. If check_if_celebrity() function returns True on the possible_celebrity, then


that person is the celebrity, otherwise there is no celebrity.

Q5.

Write a Python program to construct a linked


list. Prompt the user for input. Remove any
duplicate numbers from the linked list.
-------------------------------------------------------------------------------------
----------------------------------------
Problem Description
In this program, we need to remove the duplicate nodes from the given singly linked list.

Original List:

List after removing duplicate nodes:

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.

3. The add_node() method will add a new node to the list:


a. Create a new node.
b. It first checks, whether the head is equal to null which means the list is empty.
c. If the list is empty, both head and tail will point to a newly added node.
d. If the list is not empty, the new node will be added to end of the list such that tail's next
will point to a newly added node. This new node will become the new tail of the list.

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

# add_node() will add a new node to the list


def add_node(self, data):
# Create a new node
new_node = Node(data)

# Checks if the list is empty


if self.head == None:
# If list is empty, both head and tail will point to new node
self.head = new_node
self.tail = new_node
else:
# new_node will be added after tail such that tail's next will
point to new_node
self.tail.next = new_node
# newNode will become new tail of the list
self.tail = new_node

# removeDuplicate() will remove duplicate nodes from the list


def remove_duplicate(self):
# Node current will point to head
current = self.head
index = None
temp = 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

while index != None:


# If current node's data is equal to index node's data
if current.data == index.data:
# Here, index node is pointing to the node which is
duplicate of current node
# Skips the duplicate node by pointing to next node
temp.next = index.next
else:
# Temp will point to previous node of index.
temp = index
index = index.next
current = current.next

# display() will display all the nodes present in the list


def display(self):
# Node current will point to head
current = self.head
if self.head == None:
print("List is empty")
return
while current != None:
# Increment next to print each node
print(current.data)
current = current.next
def user_input():
slist = LinkedList()
# Add data to the list
data_list = input("Please enter the elements in the linked list:
").split()
for data in data_list:
slist.add_node(int(data))

# Display original list


print("Original List: ")
slist.display()

# Remove duplicate nodes (if any)


slist.remove_duplicate()

print("List after removing duplicate nodes: ")


slist.display()

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.

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.

b) Read a file contents and copy only the


contents at odd lines into a new file.
-------------------------------------------------------------------------------------
----------------------------------------
Approach to displaying the files and subdirectories in each level
1. Get path information from the user.

2. Check whether the path exists or not.

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).

Below functions are used in the program

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.

2. Open a file destination_file as out_file in write mode.

3. To read all the lines of a file use f.readlines().

4. Obtain the total number of lines in the file.

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")

print("File contents at odd lines copied to destination file \n")


display_menu()

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

File name(s) 1.txt

Found directory: C:\Test_Data\Root_Dir

File name(s) 2.txt

Found directory: C:\Test_Data\Root_Dir\Sub_Dir_1

File name(s) 3.txt

Found directory: C:\Test_Data\Root_Dir\Sub_Dir_1\Sub_Dir_2

File name(s) 4.txt

File name(s) 5.txt

Number of subdirectories are 3

Number of files are 5

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
2
Enter the Source file name: source_file.txt

Enter the Destination file name: destination_file.txt

File contents at odd lines copied to destination file


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
3

Q7.

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 the same
meaning, remove an entry, display all words
sorted alphabetically.
In [2]:
word_dict = {}

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()

print("\nDo you want to continue(y or n)?", end="")


ch = input()

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

Do you want to continue adding words(y or n):y

Enter word:b

Enter meaning:bat

Do you want to continue adding words(y or n):y

Enter word:c

Enter meaning:cat

Do you want to continue adding words(y or n):y

Enter word:d

Enter meaning:dog

Do you want to continue adding words(y or n):n


Do you want to continue(y or n)?y
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: 2

Enter word:e

Enter meaning:egg

Do you want to continue(y or n)?y


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

Enter word:kitten

Enter meaning:cat

Do you want to continue(y or n)?y


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: 3
Enter word:b
Meaning:bat

Do you want to continue(y or n)?y


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: 4
Enter meaning:cat
Words with same meaning:['c', 'kitten']

Do you want to continue(y or n)?y


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: 5
a ==> apple
b ==> bat
c ==> cat
d ==> dog
e ==> egg
kitten ==> cat
Sorted list of words :
['a', 'b', 'c', 'd', 'e', 'kitten']

Do you want to continue(y or n)?n

Q8.

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.

c) Match a word containing 'z' followed by one


or more o's.

Prompt the user for input.


-------------------------------------------------------------------------------------
----------------------------------------
Approach to identify a sequence of one upper case letter followed by lower case letters

To check if the sequence of one upper case letter followed by lower case letters we use regular
expression [A-Z]+[a-z]+$

Approach to find the patterns of 1(0+)1 in a given string

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.

Approach to match a word consisting of z followed by one or more o's

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.

\w -> represents any letter, numeric digit, or the underscore character.

* -> means zero or more occurrence of the character.

+ -> means one or more occurrence of the character.

-------------------------------------------------------------------------------------
----------------------------------------
In [19]:
import re

# Function to Find all the patterns of "1(0+)1" in a given string


def check_uc_lc_pattern(user_input):
# regex
pattern = re.compile("[A-Z]+[a-z]+$")

# 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

# find next occurrence just after previous sub-string for first


occurrence of the pattern
user_input = user_input[(substr.end() - 1) :]
substr = pattern.search(user_input)
print(f"The number of times the pattern appears in the string is {count}
\n")

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)

# If length of match_object is not equal to zero then it contains matched


string
if len(match_object) != 0:
print("String pattern match success \n")
else:
print("No match \n")
def menu():
while True:
print(
"1 --> Identify a word with a sequence of one upper case letter
followed by lower case letters"
)
print("2 --> Find all the patterns of '1(0+)1' in a given string")
print("3 --> Match a word containing 'z' followed by one or more
o's")
print("4 --> Exit the program")
choice = int(input("Enter a number to perform any of the operation:
"))
print("\n")
if choice == 1:
user_input = input(
"Enter a string with a sequence of Upper and Lower case
letters: "
)
print("\n")
check_uc_lc_pattern(user_input)
elif choice == 2:
user_input = input("Enter a string in the form of 1(0+)1 pattern:
")
print("\n")
count_pattern(user_input)
elif choice == 3:
user_input = input("Enter a string: ")
print("\n")
z_followed_by_o(user_input)
else:
break

# 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

String pattern match success

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

String pattern match success

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

String pattern match success

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

String fails the pattern


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

Enter a string in the form of 1(0+)1 pattern: 10101010001111

The number of times the pattern appears in the string is 4

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

Enter a string in the form of 1(0+)1 pattern: 110

The number of times the pattern appears in the string is 0

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

Enter a string: zoo

String pattern match success

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

Enter a string: zip

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.

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.
-------------------------------------------------------------------------------------
----------------------------------------
Microsoft Excel is a software program produced by Microsoft that allows users to organize,
format and calculate data with formulas using a spreadsheet system. This software is part of the
Microsoft Office suite and is compatible with other applications in the Office suite.

Microsoft Excel terminology

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

 100% compatible Excel XLSX files.


 Full formatting.
 Merged cells.
 Defined names.
 Charts.
 Autofilters.
 Data validation and drop down lists.
 Conditional formatting.
 Worksheet PNG/JPEG images.
 Rich multi-format strings.
 Cell comments.
 Memory optimisation mode for writing large files.
Advantages:

 It supports more Excel features than any of the alternative modules.


 It has a high degree of fidelity with files produced by Excel. In most cases the files produced
are 100% equivalent to files produced by Excel.
 It has extensive documentation, example files and tests.
 It is fast and can be configured to use very little memory even for very large output files.

Disadvantages:

 It cannot read or modify existing Excel XLSX files.

-------------------------------------------------------------------------------------
----------------------------------------
Description of the methods used in the program

xlsxwriter.Workbook() -> The Workbook() constructor is used to create a new Excel


workbook with a given filename.

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

# Workbook() takes one, non-optional, argument


# which is the filename that we want to create.
# The file is present in the working directory.
workbook = xlsxwriter.Workbook("line_chart.xlsx")

# The workbook object is then used to add new


# worksheet via the add_worksheet() method.
worksheet = workbook.add_worksheet() # Defaults to Sheet1.

# Create a new Format object to formats cells


# in worksheets using add_format() method .

# The properties of a cell that can be formatted include:


# fonts, colors, patterns, borders, alignment and number formatting.
# here we create bold format object .
bold = workbook.add_format({"bold": 1})

# create a data list .


headings = ["Year", "Microsoft", "Alphabet", "Amazon"]

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],
]

# Write a row of data starting from 'A1'


# with bold format .
worksheet.write_row("A1", headings, bold)

# Write a column of data starting from


# 'A2', 'B2', 'C2' 'D2' respectively .
worksheet.write_column("A2", data[0])
worksheet.write_column("B2", data[1])
worksheet.write_column("C2", data[2])
worksheet.write_column("D2", data[3])

# Create a chart object that can be added


# to a worksheet using add_chart() method.

# here we create a line chart object .


chart = workbook.add_chart({"type": "line"})

# Add a data series to a chart


# using add_series method.

# Configure the first series.


# = Sheet1!$A$1 is equivalent to ['Sheet1', 0, 0].

# note : spaces is not inserted in b / w


# = and Sheet1, Sheet1 and !
# if space is inserted it throws warning.
chart.add_series(
{
"name": "=Sheet1!$B$1",
"categories": "=Sheet1!$A$2:$A$9",
"values": "=Sheet1!$B$2:$B$9",
}
)

# Configure a second series.


# Note use of alternative syntax to define ranges.
# [sheetname, first_row, first_col, last_row, last_col].
chart.add_series(
{
"name": ["Sheet1", 0, 2],
"categories": ["Sheet1", 1, 0, 8, 0],
"values": ["Sheet1", 1, 2, 8, 2],
}
)

# Configure a third series.


# Note use of alternative syntax to define ranges.
# [sheetname, first_row, first_col, last_row, last_col].
chart.add_series(
{
"name": ["Sheet1", 0, 3],
"categories": ["Sheet1", 1, 1, 8, 1],
"values": ["Sheet1", 1, 3, 8, 3],
}
)

# Add a chart title


chart.set_title({"name": "Company Profit Analysis"})

# Add x-axis label


chart.set_x_axis({"name": "Year"})

# Add y-axis label


chart.set_y_axis({"name": "Profit (in Billions)"})

# Set an Excel chart style.


chart.set_style(4)

# add chart to the worksheet with given


# offset values at the top-left corner of
# a chart is anchored to cell D2 .
worksheet.insert_chart("D2", chart, {"x_offset": 25, "y_offset": 10})

# Finally, close the Excel file


# via the close() method.
workbook.close()

Q10.

Devise a Python program to implement the


Hangman Game.
-------------------------------------------------------------------------------------
----------------------------------------
Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word,
phrase or sentence and the other(s) tries to guess it by suggesting letters or numbers, within a
certain number of guesses.

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

# Create a while loop


# check if the turns are more than zero
while turns > 0:
# make a counter that starts with zero
failed = 0
# for every character in secret_word
for char in word:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print(char)
else:
# if not found, print a dash
print("_")
# and increase the failed counter with one
failed += 1

# if failed is equal to zero


# print You Won
if failed == 0:
print("You won the game :-)")
# exit the script
break

# ask the user go guess a character


guess = input("Guess a character: ")
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
# turns counter decreases with 1
turns -= 1
# print wrong
print("Wrong guess")
# how many turns are left
print(f"You have {turns} more guesses")

# if the turns are equal to zero


if turns == 0:
# print "You Loose"
print("You lost the game :-(")

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

Das könnte Ihnen auch gefallen