Sample Laboratory Manual For Programming Assignment PDF
Sample Laboratory Manual For Programming Assignment PDF
AIRA J. GANDINGCO
A LABORATORY MANUAL IN
CPEN21A – PROGRAMMING LOGIC AND
DESIGN
(STRINGS)
Faculty-in-Charge:
JOVEN R. RAMOS
Date of Submission
December 2019
Preface
As a part of Engineering Department and in order to gain practical knowledge in the
field of Computer programming. The author aims to state different Python program in
the book of Brian Heinold to help and guide some beginner programmers.
In this project we included the problem description, source code and the algorithm.
This project challenged the authors to enhance their own capabilities in terms of
Computer programming.
i
About the Author
ii
About the author
iii
Table of Contents
Preface ………………………………………………………………………………. i
About the Author ……………………………………………………………………. ii
Introduction ……………………………………………………………………….…. 1
Objectives ……………………………………………………………………………. 1
Materials ...………………………………………………………………………...…. 1
Procedures / Discussion …………………………………………………………….. 2
Description Problem 1 ……………………………………………………….. 8
Description Problem 2 ………………………………………………………. 11
Description Problem 3 ………………………………………………………. 12
Description Problem 4 ……………………………………………………….. 13
Description Problem 5 ………………………………………………………. 14
Description Problem 6 ………………………………………………………. 15
Description Problem 7 ………………………………………………………. 16
Description Problem 8 ………………………………………………………. 17
Description Problem 9 ………………………………………………………. 19
Description Problem 10 …………………………………………………….. 20
Description Problem 11 …………………………………………………….. 21
Description Problem 12 ……………………………………………………. 22
Description Problem 13 ……………………………………………………. 23
Description Problem 14 ……………………………………………………. 24
Description Problem 15 ……………………………………………………. 25
Description Problem 16 ……………………………………………………. 27
Description Problem 17 ……………………………………………………. 28
Description Problem 18 ……………………………………………………. 30
Description Problem 19 ……………………………………………………. 33
Description Problem 20 …………………………………………………… 34
Description Problem 21 …………………………………………………… 38
Description Problem 22 ……………………………………………………. 39
Description Problem 23 ……………………………………………………. 41
Description Problem 24 ……………………………………………………. 43
Description Problem 25 ……………………………………………………. 44
Preference …………………………………………………………………………. 46
Introduction
A string is a sequence of characters, an integer and floating-point unit but is used to
represent text rather than numbers. It is comprised of a set of characters that can also
contain spaces and numbers.
Python has a set of built-in methods that you can use on strings. All string methods
return new values that made it immutable which means they do not change the original
string.
Objectives
At the end of this activity, the students are expected to:
• create the basic structure and understand what string is
• be able to define the built-in methods using strings in Python
• perform the concatenation, repetition and operators that can be used for strings
• familiarized the common errors and methods while performing the said topic
• write a program that use strings and increase program modularity
Materials
The material will be used in writing a program is the Python that created by
Guido van Rossum which is a high-level, general-purpose, interpreted, interactive,
object-oriented dynamic programming language. The latest version of Python is
Python 3.8.1 that was released on December 18, 2019.
1
Strings
Strings are a data type in Python for dealing with text. Python has a number of powerful
features for manipulating strings.
Basics
Creating a string: A string is created by enclosing text in quotes. You can use either
single quotes, ', or double quotes, ". A triple-quote can be used for multi-line strings. Here are
some examples:
s = 'Hello'
t = "Hello"
m = """This is a long string that is spread across two lines."""
When getting numerical input we use an eval statement with the input statement, but
when getting text, we do not use eval. The difference is illustrated below:
num = eval(input('Enter a number: '))
string = input('Enter a string: ')
Empty string The empty string '' is the string equivalent of the number 0. It is
a string with nothing in it. We have seen it before, in the print statement’s optional
argument, sep=''.
Length: To get the length of a string (how many characters it has), use the
built-in function len. For example, len('Hello') is 5.
2
s = ''
for i in range(10):
t = input('Enter a letter: ')
if t=='a' or t=='e' or t=='i' or t=='o' or t=='u': s
= s + t
print(s)
The in operator
You can combine in with the not operator to tell if a string does not contain
something:
if ';' not in string:
print('Your string does not contain any semicolons.')
Using the in operator, we can replace that statement with the following:
if t in 'aeiou':
Indexing
We will often want to pick out individual characters from a string. Python uses square
brackets to do this. The table below gives some examples of indexing the string
s='Python'.
3
• The first character of s is s[0], not s[1]. Remember that in programming,
counting usually starts at 0, not 1.
• Negative indices count backwards from the end of the string.
You will see this message again. Remember that it happens when you try to read past
the end of a string.
Slices
A slice is used to pick out part of a string. It behaves like a combination of indexing and
the range function. Below we have some examples with the string
s='abcdefghij'.
index: 0 1 2 3 4 5 6 7 8 9
letters: a b c d e f g h i j
• Slices have the same quirk as the range function in that they does not include
the ending location. For instance, in the example above, s[2:5] gives the
characters in indices 2, 3, and 4, but not the character in index 5.
• We can leave either the starting or ending locations blank. If we leave the
starting location blank, it defaults to the start of the string. So s[:5] gives the
first five characters of s. If we leave the ending location blank, it defaults to the
4
• end of the string. So s[5:] will give all the characters from index 5 to the end.
If we use negative indices, we can get the ending characters of the string. For
instance, s[-2:] gives the last two characters.
• There is an optional third argument, just like in the range statement, that can
specify the step. For example, s[1:7:2] steps through the string by twos,
selecting the characters at indices 1, 3, and 5 (but not 7, because of the
aforementioned quirk). The most useful step is -1, which steps backwards
through the string, reversing the order of the characters.
The idea of this is we take all the characters up to index 4, then X, and then all
of the characters after index 4.
Looping
Very often we will want to scan through a string one character at a time. A for loop like
the one below can be used to do that. It loops through a string called s, printing the
string, character by character, each on a separate line:
for i in range(len(s)):
print (s[i])
In the range statement we have len(s) that returns how long s is. So, if s were 5
characters long, this would be like having range(5) and the loop variable i would
run from 0 to 4. This means that s[i] will run through the characters of s. This way of
looping is useful if we need to keep track of our location in the string during the loop.
If we don’t need to keep track of our location, then there is a simpler type of loop we
can use:
for c in s: print(c)
This loop will step throughs, character by character, with c holding the current
character. You can almost read this like an English sentence, “For every character c
in s, print that character.”
5
String methods
Strings come with a ton of methods, functions that return information about the string
or return a new string that is a modified version of the original. Here are some of the
most useful ones:
Method Description
lower() returns a string with every letter of the original in lowercase
Important note: One very important note about lower, upper, and replace is that
they do not change the original string. If you want to change a string, s, to all lower
case, it is not enough to just use s.lower(). You need to do the following:
s = s.lower()
isalpha The isalpha method is used to tell if a character is a letter or not. It returns
True if the character is a letter and False otherwise. When used with an entire string,
it will only return True if every character of the string is a letter. The values True and
False are called Booleans. Just remember that you can use isalpha in if conditions.
A note about index If you try to find the index of something that is not in a string,
Python will raise an error. For instance, if s='abc' and you try s.index('z'),you
will get an error. One way around this is to check first, like below:
if 'z' in s: location = s.index('z')
Other string methods There are many more string methods. For instance, there are
methods isdigit and isalnum, which are analogous to isalpha. Some other
useful methods we will learn about later are join and split. To see a list of all the
string methods, type dir(str) into the Python shell. If you do this, you will see a
bunch of names that start with __. You can ignore them. To read Python’s
documentation for one of the methods, say the isdigit method, type
help(str.isdigit).
6
Escape characters
The backslash, \,is used to get certain special characters, called escape characters,
into your string. There are a variety of escape characters, and here are the most useful
ones:
• \n the newline character. It is used to advance to the next line.
7
Procedure
Problem Description:
1. Write a program that asks the user to enter a string. The program should then
print the following:
(c) The first character of the string (remember that string indices start at 0)
(g) The seventh character of the string if the string is long enough and a
message otherwise.
(h) The string with its first and last characters removed
8
Step 4: PRINT the desire output of each condition
Step 5: STOP
Program Solution:
#A program that asks the user to enter a string. The program
should then print the following:
string=input("Enter a String: ")
9
Sample Output:
10
Problem Description:
2. A simple way to estimate the number of words in a string is to count the number
of spaces in the string. Write a program that asks the user for a string and
returns an estimate of how many words are in the string.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: GET the length of the characters using the function .count()
Step 4: PRINT the program
Step 5: STOP
Program Solution:
#A program that asks the user for a string and returns an
estimate of how many words are in the string.
Sample Output:
11
Problem Description:
3. People often forget closing parentheses when entering formulas. Write a
program that asks the user to enter a formula and prints out whether the
formula has the same number of opening and closing parentheses.
Program Algorithm:
Step 1: START
Step 2: INPUT formula
Step 3: if formula.count('(')==formula.count(')'):
print('Parenthesis are equals in your formula !!')
else:
print('Something is wrong in your formula regarding parenthesis !!')
Step 4: PRINT the result based on a given condition
Step 5: STOP
Program Solution:
#A program that asks the user to enter a formula and prints out
whether the formula has the same number of opening and closing
parentheses.
formula = input('Enter a formula :') #input formula
Sample Output:
12
Problem Description:
4. Write a program that asks the user to enter a word and prints out whether that
word contains any vowels.
Program Algorithm:
Step 1: START
Step 2: INPUT word
Step 3: DISPLAY the input word
Step 4: COUNT every singular vowels present in the word
Step 5: PRINT and display the result of the program
Step 6: STOP
Program Solution:
#A program that asks the user to enter a word and prints out
whether that word contains any vowels.
word= input('Enter a word: ')
a=0
vowels_in_word='' #indicates the vowels in the input word
vowels='aeiouAEIOU' #Vowels presents in input word
Sample Output:
13
Problem Description:
5. Write a program that asks the user to enter a string. The program should create
a new string called new_string from the user’s string such that the second
character is changed to an asterisk and three exclamation points are attached
to the end of the string. Finally, print new_string.
Typical output is shown below:
Enter your string: Qbert
Q*ert!!!
Program Algorithm:
Step 1: START
Step 2: INPUT first_string
Step 3: REPLACE the second character to asterisk
Step 4: DISPLAY three exclamation point at the end of string
Step 5: STOP
Program Solution:
#A program that asks the user to enter a string. The program
should create a new string called new_string from the user’s
string such that the second character is changed to an asterisk
and three exclamation points are attached to the end of the
string.
first_string = input('Enter your string : ')
new_string = first_string[:1]+'*'+first_string[2:]+'!!!'
print(new_string) #input word with the second character as
asterisk then having 3 exclamation point after the last
character of the word
Sample Output:
14
Problem Description:
6. Write a program that asks the user to enter a string s and then converts s to
lowercase, removes all the periods and commas from s, and prints the resulting
string.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: CONVERT all letter S to lowercase
Step 4: SET the string without commas and period
Step 5: PRINT the result
Step 6: STOP
Program Solution:
#A program that asks the user to enter a string s and then
converts s to lowercase, removes all the periods and commas from
s, and prints the resulting string.
string=input('Enter a string: ')
string=string.lower() #Convert the letter s in the string
into lower case
for p_c in ',.': #Setting the period and commmas to be
replace
string=string.replace(p_c,' ')
Sample Output:
15
Problem Description:
7. Write a program that asks the user to enter a word and determines whether the
word is a palindrome or not. A palindrome is a word that reads the same
backwards as forwards.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the given string backward using [::-1]
Step 4: if readbackwards==string:
print("Your string is a palindrome!")
else:
print(string,"is not a palindrome!")
Step 5: PRINT the result base on the given condtion
Step 6: STOP
Program Solution:
#A program that asks the user to enter a word and determines
whether the word is a palindrome or not.
string=input("Enter a string: ") #input string
readbackwards=string[::-1] #indicates of the code
reads the words the same backwards as forwards
Sample Output:
16
Problem Description:
8. At a certain school, student email addresses end with @student.college.edu,
while professor email addresses end with @prof.college.edu. Write a program
that first asks the user how many email addresses they will be entering, and
then has the user enter those addresses. After all the email addresses are
entered, the program should print out a message indicating either that all the
addresses are student addresses or that there were some professor addresses
entered.
Program Algorithm:
Step 1: START
Step 2: INPUT number_of_email
Step 3: INPUT email ids based on the number of email
Step 4: SET the given email to 0
Step 5: for i in range(number_of_email):
email = input('Enter email id : ')
if '@prof' in email:
email_of_prof+=1
if '@student' in email:
email_of_student+=1
print('No of prof email ids :',email_of_prof,' No of student email ids
:',email_of_student)
Step 5: PRINT the result
Step 6: STOP
17
Program Solution:
#A program that first asks the user how many email addresses they
will be entering, and then has the user enter those addresses.
After all the email addresses are entered, the program should
print out a message indicating either that all the addresses are
student addresses or that there were some professor addresses
entered.
Sample Output:
18
Problem Description:
9. Ask the user for a number and then print the following, where the pattern
ends at the number that the user enters.
1
2
3
4
Program Algorithm:
Step 1: START
Step 2: INPUT number
Step 3: SET the program to a for loop condition
Step 4: PRINT the result
Step 5: STOP
Program Solution:
#A program that ask the user for a number and then print the
following, where the pattern ends at the number that the user
enters.
1
2
3
4
for i in range(number):
print(' '*i,i+1,sep='') #printing the result of the
starting and range of the number adding 1 space as separator
in each number of the string
Sample Output:
19
Problem Description:
10. Write a program that asks the user to enter a string, then prints out each letter
of the string doubled and on a separate line. For instance, if the user entered
HEY, the output would be
HH
EE
YY
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the program to a for loop condition
Step 4: PRINT each character of the string twice
Step 5: STOP
Program Solution:
#A program that asks the user to enter a string, then prints
out each letter of the string doubled and on a separate line.
string= input('Enter a string: ') #input string of the user
for i in string:
print(i*2) #Each character of the string will repeat twice
and creates a new string each character.
Sample Output:
20
Problem Description:
11. Write a program that asks the user to enter a word that contains the letter a.
The program should then print the following two lines: On the first line should
be the part of the string up to and including the first a ,and on the second line
should be the rest of the string. Sample output is shown below:
Enter a word: buffalo
buffa
lo
Program Algorithm:
Step 1: START
Step 2: INPUT any word with letter a
Step 3: DISPLAY the word ended with letter a
Step 4:DISPLAY the rest of the letters
Step 5: PRINT the result
Step 6: STOP
Program Solution:
#A program that ask the user to enter a word that contains the
letter a and it should print two strings where in the first line
prints the part of the strings up to and including the firs a
and on the second string should be the rest of the string.
word = input('Enter a word with letter A/a: ') #input word
containing letter A/a
word2 = word.index('a')+1
21
Problem Description:
12. Write a program that asks the user to enter a word and then capitalizes every
other letter of that word. So if the user enters rhinoceros, the program should
print rHiNoCeRoS.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the string to lowercase letter
Step 4: SET the program to for loop
Step 5: DISPLAY the string with a lower and uppercase letter alternatively
Step 6: PRINT the result
Step 7: STOP
Program Solution:
#A program that asks the user to enter a word and then
capitalizes every letter of that word.
string= input("Enter a string: ") #input string of the user
string=string.lower() #the string should start at lower
case
Sample Output:
22
Problem Description:
13. Write a program that asks the user to enter two strings of the same length. The
program should then check to see if the strings are of the same length. If they
are not, the program should print an appropriate message and exit. If they are
of the same length, the program should alternate the characters of the two
strings. For example, if the user enters abcde and ABCDE the program should
print out AaBbCcDdEe.
Program Algorithm:
Step 1: START
Step 2: INPUT first and second string
Step 3: DISPLAY the input strings
Step 4: GET the legth of two strings and compare it
Step 5: SET conditions if the two string are equal or not
Step 6: PRINT the result base on the given condition
Step 7: STOP
Program Solution:
#A program that asks the user to enter two strings of the same
length. The program should then check to see if the strings are
of the same length. If they are not, the program should print
an appropriate message and exit. If they are of the same length,
the program should alternate the characters of the two strings.
first_string = input("Enter your first string: ")
#Input first string of the user
second_string = input("Enter your second string with the same
length of the first string: ") #input second string of the
user
if len(first_string)==len(second_string): #indicates if
both first and second string has the same length
for i in range(len(first_string)):
print(first_string[i]+second_string[i],end='')
#Performs the alternating the characters of the two strings
else:
print('Both the strings are not of the same length !!')
#Print out if the strings are not having the same length
Sample Output:
23
Problem Description:
14. Write a program that asks the user to enter their name in lowercase and then
capitalizes the first letter of each word of their name.
Program Algorithm:
Step 1: START
Step 2: INPUT names in a lowercase letter
Step 3: SET the first letter of each name to uppercase letter
Step 4: PRINT the result
Step 5: STOP
Program Solution:
#A program that asks the user to enter their name in lowercase
then capitalizes the first letter of each word of their name.
upper_case_name = input('Enter your name: ') #input name of
the user
print(upper_case_name.title()) #Prints the capitalized the
first letter of each word in the string
Sample Output:
24
Problem Description:
15. When I was a kid, we used to play this game called MadLibs. The way it worked
was a friend would ask me for some words and then insert those words into a
story at specific places and read the story. The story would often turn out to be
pretty funny with the words I had given since I had no idea what the story was
about. The words were usually from a specific category, like a place, an animal,
etc. For this problem you will write a Mad Libs program. First, you should make
up a story and leave out some words of the story. Your program should ask the
user to enter some words and tell them what types of words to enter. Then print
the full story along with the inserted words. Here is a small example, but you
should use your own (longer) example:
Enter a college class: CALCULUS
Enter an adjective: HAPPY
Enter an activity: PLAY BASKETBALL
Program Algorithm:
Step 1: START
Step 2: INPUT word
Step 3: SET the class name to calculus
Step 4: SET the adjective to happy
Step 5: SET the activity to play basketball
Step 6: PRINT the result
Step 7: STOP
25
Program Solution:
#A program should print the full story along with the inserted
words
classname='CALCULUS' #Setting for College class
Sample Output:
26
Problem Description:
16. Companies often try to personalize their offers to make them more attractive.
One simple way to do this is just to insert the person’s name at various places
in the offer. Of course, companies don’t manually type in every person’s name;
everything is computer-generated. Write a program that asks the user for their
name and then generates an offer like the one below. For simplicity’s sake, you
may assume that the person’s first and last names are one word each.
Enter name: George Washington
Dear George Washington,
I am pleased to offer you our new Platinum Plus Rewards card at a special
introductory APR of 47.99%. George, an offer like this does not come along
every day, so I urge you to call now toll-free at 1-800-314-1592. We cannot
offer such a low rate for long, George, so call right away.
Program Algorithm:
Step 1: START
Step 2: INPUT name
Step 3: DISPLAY the input name and message
Step 4: SET the program to a for loop condition
Step 5: PRINT the resultt
Step 6: STOP
Program Solution:
#A program that asks the user for their name and then generates
an offer to the letter
string = input('What is the user name: ') #input name
27
Sample Ouput:
Problem Description:
17. Write a program that generates the 26-line block of letters partially shown
below. Use a loop containing one or two print statements.
abcdefghijklmnopqrstuvwxy
bcdefghijklmnopqrstuvwxyza
cdefghijklmnopqrstuvwxyzab
...
yzabcdefghijklmnopqrstuvwx
zabcdefghijklmnopqrstuvwxy
Program Algorithm:
Step 1: START
Step 2: INPUT alphabet
Step 3: SET the program to a for loop condition
Step 4: SET the alphabet orderly
Step 5: PRINT the result
Step 6: STOP
28
Program Solution:
#A program that generates the 26-line block of letters using
loop.
alphabet=input("Enter the alphabet letters: ") #Input of the
user
for i in range(len(alphabet)):
arrangement=alphabet[i:]+alphabet[:i] #Indicates how the
26-line of block of letter will generate
print(arrangement) #Prints the generate 26-line of
block of letters
Sample Output:
29
Problem Description:
18. The goal of this exercise is to see if you can mimic the behaviour of the in
operator and the count and index methods using only variables, for loops, and if
statements.
(a) Without using the in operator, write a program that asks the user for a string
and a letter and prints out whether or not the letter appears in the string.
(b) Without using the count method, write a program that asks the user for a string
and a letter and counts how many occurrences there are of the letter in the string.
(c) Without using the index method, write a program that asks the user for a string
and a letter and prints out the index of the first occurrence of the letter in the string.
If the letter is not in the string, the program should say so.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: INPUT letter
Step 4: SET conditions if the variable is greater than 0
Step 5: DISPLAY the result of the first condition
Step 6: SET the input string and letter to 0
30
Program Solution:
#A program that asks the user for a string and a letter and
prints out whether or not the letter appears in the string
without using in operator.
#Letter A
let=string.find('finding_letter')
if let>=0:
print('Yes',(finding_letter),'is present in',string)
else:
print('No',finding_letter,'is not present in',string)
#A program that asks the user for a string and a letter and
counts how many occurrences there are of the letter in the
string without using count method.
#Letter B.
#A program that asks the user for a string and a letter and
prints out the index of the first occurrence of the letter in
the string.
#Letter C
31
if f==1:
print('Yes',finding_letters,'is present in',string,'at
location :',l,'.')
else:
print('No',finding_letters,'is not present in',string)
Sample Output:
32
Problem Description:
19. Write a program that asks the user for a large integer and inserts commas into
it according to the standard American convention for commas in large numbers.
For instance, if the user enters 1000000, the output should be 1,000,000.
Program Algorithm:
Step 1:START
Step 2:INPUT number
Step 3:DISPLAY number with comma/s
Step 4:PRINT the result of the program
Step 5:STOP
Program Solution:
number = eval(input("Enter a number: ")) #input digit of the
user
print ('{:,}'.format(number)) #prints the digit with commas
according to its places
Sample Output:
33
Problem Description:
20. Write a program that converts a time from one time zone to another. The user
enters the time in the usual American way, such as 3:48pm or 11:26am. The
first time zone the user enters is that of the original time and the second is the
desired time zone. The possible time zones are Eastern, Central, Mountain, or
Pacific.
Time: 11:48pm
Starting zone: Pacific Ending
Zone: Eastern 2:48am
Program Algorithm:
Step 1:START
Step 2:INPUT time
Step 3:DISPLAY the different time base on a different location
Step 4:PRINT the result of the program
Step 5:STOP
Program Solution:
#A program that converts a time from one time zone to another.
#this condition will compute for the ending zone time if the
starting zone is pacific.
if starting_zone == 'pacific':
if ending_zone == 'eastern':
if (time_hour + 3) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
34
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour + 3) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour + 3) % 12) + time[-5:-
2] + final_am_pm
print(final_time) #it will display the final time.
elif ending_zone == 'central':
if (time_hour + 2) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour + 2) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour + 2) % 12) + time[-5:-2]+ final_am_pm
print(final_time) #it will display the final time.
elif ending_zone == 'mountain':
if (time_hour + 1) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour + 1) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour + 1) % 12) + time[-5:-
2] + final_am_pm
print(final_time) #it will display the final time.
##this condition will compute for the ending zone time if the
starting zone is eastern.
elif starting_zone == 'eastern':
if ending_zone == 'pacific':
if (time_hour - 3) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour - 3) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour - 3) % 12) + time[-5:-
2] + final_am_pm
35
print(final_time) #it will display the final
time. elif ending_zone == 'central':
if (time_hour - 1) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour - 1) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour - 1) % 12) + time[-5:-
2] + final_am_pm
print(final_time) #it will display the final time.
elif ending_zone == 'mountain':
if (time_hour - 2) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour - 2) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour - 2) % 12) + time[-5:-
2] + final_am_pm
print(final_time) #it will display the final time.
#this condition will compute for the ending zone time if the
starting zone is mountain.
elif starting_zone == 'mountain':
if ending_zone == 'pacific':
36
if ((time_hour + 1) % 12) == 0:
final_time = '12' + time[-5:-2] + final_am_pm
else:
final_time = str((time_hour + 1) % 12) + time[-5:-
2] + final_am_pm
print(final_time) #it will display the final time.
elif ending_zone == 'eastern':
if (time_hour + 2) >= 12:
if am_pm == 'am':
final_am_pm = 'pm'
elif am_pm == 'pm':
final_am_pm = 'am'
else:
final_am_pm = am_pm
if ((time_hour + 2) % 12) == 0:
Sample Output:
37
Problem Description:
21. An anagram of a word is a word that is created by rearranging the letters of the
original. For instance, two anagrams of idle are deli and lied. Finding anagrams
that are real words is beyond our reach until Chapter 12. Instead, write a
program that asks the user for a string and returns a random anagram of the
string—in other words,a random rearrangement of the letters of that string.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the list of string to be reshuffle to make it anagram
Step 4: DISPLAY the result
Step 6: PRINT the result
Step 7: STOP
Program Solution:
#A program that asks the user for a string and returns a random
anagram of the string.
import random #This will input the random module
Sample Output:
38
Problem Description:
22. A simple way of encrypting a message is to rearrange its characters. One
way to rearrange the characters is to pick out the characters at even indices,
put them first in the encrypted string, and follow them by the odd characters.
For example, the string message would be encrypted as msaeesg because the
even characters are m, s, a, e (at indices 0, 2, 4, and 6) and the odd characters
are e, s, g (at indices 1, 3, and 5).
(a) Write a program that asks the user for a string and uses this method to
encrypt the string.
(b) Write a program that decrypts a string that was encrypted with this method.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the given string to an encrypt format that will remove all repeated letters
Step 4: DISPLAY the result
Step 5: SET the encrypted letters to decrypted format
Step 6: PRINT the result
Step 7: STOP
Program Solution:
print('(a)')
#Condition number 1
print('')
39
#Write a program that decrypts a string that was encrypted
with this method.
print('(b)')
#Condition number 2
while string != string_1: #this loop will not stop until the
condtion is met.
string_number = len(string)
even = ''
odd = ''
Sample Output:
40
Problem Description:
23. A more general version of the above technique is the rail fence cipher, where
instead of breaking things into evens and odds, they are broken up by threes,
fours or something larger. For instance, in the case of threes, the string secret
message would be broken into three groups. The first group is sr sg, the
characters at indices 0, 3, 6, 9 and 12. The second group is eemse, the
characters at indices 1, 4, 7, 10, and 13. The last group is ctea, the characters
at indices 2, 5, 8, and 11. The encrypted message is sr sgeemsectea.
(a) Write a program the asks the user for a string and uses the rail fence cipher
in the threes case to encrypt the string.
(b) Write a decryption program for the threes case.
(c) Write a program that asks the user for a string, and an integer determining
whether to break things up by threes, fours, or whatever. Encrypt the string
using the rail-fence cipher.
(d) Write a decryption program for the general case.
Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: SET the input string to encrypted format
Step 4: GET the decrypted format of the encrypted letters
Step 5: PRINT the result
Step 6: STOP
41
Program Solution:
(a)A program the asks the user for a string and uses the rail
fence cipher in the threes case to encrypt the string.
(b) A decryption program for the threes case.
(c) A program that asks the user for a string, and an integer
determining whether to break things up by threes, fours, or
whatever. Encrypt the string using the rail-fence cipher.
(d)A decryption program for the general case.
message = 'secret message' #intial value of message
numofsets=3
import math #importing module
num_in_each_set=math.ceil(len(message)/numofsets)
print(num_in_each_set) # threes case to encrypt the string
gap=math.ceil(len(message)/num_in_each_set)
print(gap)
positionss=[]
for i in range(numofsets):
positions=[j for j in range(0+i, len(message), gap)]
positionss.append(positions)
print('positions are', positionss)
css=[]
for positions in positionss:
cs=[]
for position in positions:
c=(message[position])
cs.append(c)
css.append(''.join(cs))
print(''.join(css))
Sample Output:
42
Problem Description:
24. In calculus, the derivative of x4 is 4x3. The derivative of x5 is 5x4. The
derivative of x6 is 6x5. This pattern continues. Write a program that asks the
user for input like x^3 or x^25 and prints the derivative. For example, if the user
enters x^3, the program should print out 3x^2.
Program Algorithm:
Step 1: START
Step 2: INPUT numbersto be raised on x
Step 3: CALCULATE the derivative of the given number
Step 4: PRINT the result
Step 5: STOP
Program Solution:
exponent = int(input('Enter a number to be raised on x to find
its derivative:')) #this is where the user will input a number
to be raised to x and finds its dervatives.
Sample Output:
43
Problem Description:
25. In algebraic expressions, the symbol for multiplication is often left out, as in
3x+4y or 3(x+5). Computers prefer those expressions to include the
multiplication symbol, like 3*x+4*y or 3*(x+5). Write a program that asks the
user for an algebraic expression and then inserts multiplication symbols where
appropriate.
Program Algorithm:
Step 1: START
Step 2: INPUT algebraic expression
Step 3: SET the given algebraic expression to list
Step 4: SET conditions using for loop
Step 5: PRINT the result base on given condition
Step 6: STOP
Program Solution:
#A program that asks the user for an algebraic expression and
then inserts multiplication symbol where appropriate
algebraic_expression = input('Enter an algebraic expression:
') #input algebraic expression
empty_list = []
algebraic_expression = (''.join(empty_list))
44
Sample Output:
45
References:
[3] Lutz, Marc. Learning Python, 5th ed. O’Reilly Media, 2013. [I first learned Python
from the third edition. It is long, but has a lot of good information.]
[4] Lutz, Marc. Programming Python, 4th ed. O’Reilly Media, 2011.
[Thisisamoreadvancedbook.Thereissomegoodinformationinhere,especiallytheTkinter
chapters.]
[5] Beazley, Jeff. The Python Essential Reference, 4th ed. Addison-Wesley
Professional, 2009. [This is a short, but effective reference.]
46
CvSU VISION
The premier University in historic Cavite recognized for excellence in the development
of globally competitive and morally upright individuals.
CvSU MISSION
Cavite State University shall provide excellent, equitable, and relevant educational
opportunities in the arts, sciences and technology through quality instruction and
responsive research and development activities.
It shall produce professional, skilled and morally upright individuals for global
competitiveness.
We Commit to the highest standards of education, value our stakeholders, Strive for
continual improvement of our products and services, and Uphold the University’s
tenets of Truth, Excellence, and Service to produce globally competitive and morally
upright individuals.
PROGRAM OBJECTIVES