Sunteți pe pagina 1din 53

CAVITE STATE UNIVERSITY

Don Severino delas Alas Campus

BACHELOR OF SCIENCE IN COMPUTER ENGINEERING

AIRA J. GANDINGCO

MIA PAMELA JAM GARCIA

A LABORATORY MANUAL IN
CPEN21A – PROGRAMMING LOGIC AND
DESIGN
(STRINGS)

Faculty-in-Charge:

JOVEN R. RAMOS

College of Engineering and Information Technology


Department of Computer and Electronics Engineering

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

Aira J. Gandingco was born on December 06,


2000 in the City of General Trias, Cavite and lived
there with her family since then. She has 5 siblings
and she was the fourth child of Mr. and Mrs.
Gandingco.
She started schooling when she was 5 years
old at Manggahan Day Care Center and then she
graduated Salutatorian when she was in Elementary
in Tropical Village Elementary School. She took her
7th to 9th grade in Governor Ferrer Memorial National
High School and a consistent top student there and
maintained her section to be in the star section. She
was a lyrist in their school band, Copy Reader in their school paper which is “Ang
Batis”. Unfortunately, she was transferred school for some personal reason and
graduated in Trece Martires City National High School year 2016-2017 with honor.
Then she attended her Senior High School at AMA Computer College – Cavite
Campus. She became a student-athlete there with a sport of Badminton for 2 years
and also graduated with honor.
Currently, she is freshman student taking a Bachelor of Science Computer
Engineering at Cavite State University – Main Campus as she takes the right path for
fulfilling her dream and career as the good future waiting for her because she believes
in verse Psalm 46:5 says “God is within her, she will not fall.”
Without the people behind her journey, she wasn’t be the better person as she
is right now. A lot of thanks to her family who supports her in every battle of her, in
every aspects of her life. To her closest friends for encouraging and the love that they
showered when life gets hard her. To her teachers that gave opportunity to experience
an amazing and memorable journey that made her tough as she is. To her classmates
who continuous to fight battle with her and last but not the least is to Almighty God, the
Designer of her life who made colourful and wonderful. Thank you for a great journey
with you all, guys!

ii
About the author

Mia Pamela Jam Garcia was born on May 06,


2001 in the city of Trece Martires, Cavite. She lived in
GMA Cavite.
She started schooling when she was 6 years old
at Presbitarian Academy and when she turned Grade
1 she studied at Area J Elementary School. She took
her first year high school at Grace Baptist Christian
School and a consistent honor sudent. She became
student athlete when she was in Grade 9. She
attended her Senior High School at Philippine
Christian University ,Cavite Campus with academic
track - Science Technology Engineering and Mathematics and graduated as honor
student.
Year 2019-2020 , She is taking her Bachelor degree as freshman Computer
Engineering Student at Cavite State University - Main Campus. She believes that
hardwork is better than intelligence.
First and for most I would like to thank God for always providing a new life and
knowledge that i need to accomplish this project.
I would like to express my deepest appreciation to my professor, Sir Joven who
gave us this kind of project that help me to improve more about programming. I would
also like to give thank to my family who support me financially in doing this. In addition,
I would like to thank my partner,Aira Gandingco who help me in creating this
Laboratory Manual.

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.

Concatenation and repetition


The operators + and * can be used on strings. The + operator combines two
strings. This operation is called concatenation. The * repeats a string a certain number
of times. Here are some examples.
Expression Result
'AB'+'cd' 'ABcd'
'A'+'7'+'B' 'A7B'
'Hi'*4 'HiHiHiHi'

Example 1: If we want to print a long row of dashes, we can do the following


print('-'*75)

Example 2: The + operator can be used to build up a string, piece by piece,


analogously to the way we built up counts and sums. Here is an example that
repeatedly asks the user to enter a letter and builds up a string consisting of only the
vowels that the user entered.

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)

This technique is very useful.

The in operator

The in operator is used to tell if a string contains something. For example:


if 'a' in string:
print('Your string contains the letter a.')

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

Example In the previous section we had the long if condition


if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':

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

Statement Result Description


s[0] P first character of s

s[1] y second character of

s s[-1] n last character of s

s[-2] o second-to-last character of s

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.

A common error: Suppose s='Python' and we try to do s[12]. There are


only six characters in the string and Python will raise the following error message:
IndexError: string index out of range

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

Code Result Description


s[2:5] cde characters at indices 2, 3, 4

s[ :5] abcde first five characters

s[5: ] fghij characters from index 5 to the end

s[-2: ] ij last two characters

s[ : ] abcdefghij entire string

s[1:7:2] bdf characters from index 1 to 6, by twos

s[ : :-1] jihgfedcba a negative step reverses the string

• The basic structure is


string name[starting location : ending location+1]

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

Changing individual characters of a string


Suppose we have a string called s and we want to change the character at
index 4 of s to 'X'. It is tempting to try s[4]='X', but that unfortunately will not work.
Python strings are immutable, which means we can’t modify any part of them. If we
want to change a character of s, we have to instead build a new string from s and
reassign it to s. Here is code that will change the character at index 4 to 'X':
s = s[:4] + 'X' + s[5:]

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

upper() returns a string with every letter of the original in uppercase

replace(x,y) returns a string with every occurrence of x replaced by y

count(x) counts the number of occurrences of x in the string

index(x) returns the location of the first occurrence of x

isalpha() returns True if every character of the string is a letter

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.

• \' for inserting apostrophes into strings.

• \" analogous to \'.

• \\ This is used to get the backslash itself

• \t the tab character

7
Procedure
Problem Description:
1. Write a program that asks the user to enter a string. The program should then
print the following:

(a) The total number of characters in the string

(b) The string repeated 10 times

(c) The first character of the string (remember that string indices start at 0)

(d) The first three characters of the string

(e) The last three characters of the string

(f) The string backwards

(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

(i) The string in all caps

(j) The string with every a replaced with an e


Program Algorithm:
Step 1: START
Step 2: INPUT string
Step 3: a. CALCULATE the length of the input string
b. SET the input string 10 times
c. DISPLAY the first characters of the string
d. DISPLAY the first three characters of the string
e. DISPLAY the last three characters of the string
f. INPUT [-1:: -1] to print the string backward
g. DISPLAY the seventh character of the string
h. DISPLAY the string without first and last characters.
i. SET all the string to capital letter
j. REPLACE the character a to e

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

#prints total number of characters in the string


print("total number of characters in the string:",len(string))

#string repeated 10 times


print(string *10)

#prints the first character of the string


print(string [0])

#prints the first 3 letters of the string


print(string [:3])

#prints the last 3 letters of the string


print(string [-3:])

#prints the string backwards


print(string [-1::-1])

#prints the 7th letter of the string


print(string [6])

# prints string with its first and last characters removed


print(string [1:(len(string)-1)])

# prints string in all caps


print(string.upper())

# prints string with every a replaced with an e


print(string.replace('a','e'))

#The string with every letter replaced by a space


print(len(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.

string = str(input('Enter a string:'))


print (string.count(' ')) #count the number of space

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

if formula.count('(')==formula.count(')'): #Conditions if the


input formula are equals to the parenthesis of the input formula
print('Parenthesis are equals in your formula !!')
#Indicates that the parenthesis are equals
else:
print('Something is wrong in your formula regarding
parenthesis !!') #indicates that the parenthesis are not equal

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

for i in word: #Range of words


if i in vowels:
a=1
vowels_in_word=vowels_in_word+i+', '

if a==1: #Condition if the input words containing vowels


print('Yes, your word contains vowels:',vowels_in_word)
#prints the vowels from the input words
else:
print('Sorry, no vowels found.') #Prints if the input
words doesn't have any vowels

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,' ')

print(string) #Prints the input string with lower case and


commas and periods replace with space

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

if readbackwards==string: #Condition if the input string


and readbackwards are the same if you read it backwards as
forward
print("Your string is a palindrome!") #Palindrome is
the input string
else:
print(string,"is not a palindrome!") #The input string is
not palindrome

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.

number_of_email = eval(input('Enter number of email ids : '))


#input number of emails to be input

email_of_prof=0 #Setting the email of the prof is 0


email_of_student=0 #Setting the email of the student is 0

for i in range(number_of_email): #indicates the range of the


number of email

email = input('Enter email id : ')#indicates the input


emails of the user

if '@prof' in email: #condition if the email is counted


to email of the prof
email_of_prof+=1
if '@student' in email: #condition if the email is
counted to email of the student
email_of_student+=1

print('No of prof email ids :',email_of_prof,' No of student


email ids :',email_of_student) #Prints the total emails
counted in prof and student

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

number= eval(input('Enter a number : ') #input number of the


user

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

print(word[:word2]) #Prints the first character up to "letter


A" character of the string.
print(word[word2:]) #prints the new string continuation of
characters from the word next to character letter A
Sample Output:

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

for i in range(len(string)): #Ranging of the string


if i%2==0: #Condition for the string
that is divisible by 2
print(string[i],end='') #prints the character of
the string alternate lower case and upper case and ends with
lower case characer
if i%2==1: #Condition for the string that is not
divisible by 2
print(string[i].upper(), end='') #prints the prints
the character of the string alternate lower case and upper
case but ends with upper case character

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

CALCULUS class was really HAPPY today. We learned how to PLAY


BASKETBALL today in class. I can't wait for tomorrow's class!

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

adjectcive='HAPPY' #Setting for the adjective

activity='PLAY BASKETBALL' #Setting for the activity

mysentence = classname + ' class was really '+ adjectcive + '


today. We learned how to '+ activity + ' today in class. I
can\'t wait for tomorrow\'s class!' #format paragraph

print(mysentence) #prints the paragraph with the assigned


value of college class, adjective and activity

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

for i in range(len(string)): #condition for displaying the


name and full name
if string [i] == ' ':
First_name = string [:i]

print('Dear' +' ' + string)


print('\n\n')
print('I am pleased to offer you our new Platinum Plus Rewards
card at a special introductory APR of 47.99%.'+ First_name+',
'+ '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, '+ First_name+', so call right
away.')

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

Step 7: SET conditions if the length of string is equal to finding_letters

Step 8: PRINT the result of the second condition


Step 9: SET the given string and letter to 0
Step 10: PRINT the result
Step 11: STOP

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

string = input('Enter a string : ') #input string


finding_letter = input('Enter a letter : ') #input letter

let=string.find('finding_letter')

#condition for finding the letters appears in string

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.

string = input('Enter a string : ') #input string


finding_letters = input('Enter a letter : ')
count=0
for i in range(len(string)):#counting the occurrence of letter
if string[i]==finding_letters:
count+=1
if count>0:
print('Yes',finding_letters,'is present
in',string,'for',count,'times.')
else:
print('No',finding_letters,'is not present in',string)

#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

string = input('Enter a string : ') #input string


finding_letters = input('Enter a letter : ') #input letter
f=0
l=0
for i in range(len(string)): #condition for the index of first
occurrence of the letter
if string[i]==finding_letters:
f=1
l=i
break

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.

#Eastern Time is 3 hours ahead of Pacific Time


#Central Time is 2 hours ahead of Pacific Time
#Mountain Time is 1 hour ahead of Pacific Time

#this lines codes will input Time, Starting zone,and Ending


zone
time = str(input('Time: '))
starting_zone = (str(input('Starting zone: '))).lower()
ending_zone = (str(input('Ending zone: '))).lower()

am_pm = (time[-2] + time[-1]).lower() #this line of code is to


know whether its am or pm.

#this condition will get the hour in integer.


if len(time) == 7:
time_hour = int(time[0:2])
elif len(time) == 6:
time_hour = int(time[0:1])

#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':

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

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:

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.

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

string = input('Enter a string: ') #this is where the user


will input a string.

list_string = [char for char in string] #to convert the


entered string into a single character element.

#this line of code is use to rearange the letters of that


string.
x = random.shuffle(list_string)

print('Random arrangement of',string,':',''.join(list_string))


#it will display the output of the random rearange string.

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

string_1 = str(input('Enter a string: ')) #this is where the


user will input a string to encrypt.
string_number = len(string_1) #the length of the input string.
even = ''
odd = ''

for ev in range(0,string_number,2): #this will loop starting


from 0 until to the value of the length of the string by 2.
even = even + string_1[ev]

for od in range(1,string_number,2):#this will loop starting


from 1 until to the value of the lenght of the string by 2.
odd = odd + string_1[od]

encrypted_string = print(even + odd) #it will display the


combined

print('')

39
#Write a program that decrypts a string that was encrypted
with this method.
print('(b)')

#Condition number 2

string = str(input('Enter a string you want to decrypt: '))


#this is where the user will input a string to decrypt.

while string != string_1: #this loop will not stop until the
condtion is met.
string_number = len(string)
even = ''
odd = ''

for ev in range(0,string_number,2): #this will loop


starting from 0 until to the value of the length of the string
by 2.
even = even + string[ev]

for od in range(1,string_number,2):#this will loop


starting from 1 until to the value of the lenght of the string
by 2.

odd = odd + string[od]

string = even + odd

print(string) #it will display the output string.

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)

# begin_poss=[i for i in range(0, len(message)-1,


num_in_each_set)]
# print(begin_poss)

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.

final_exponent = exponent - 1 #this line of code will get the


derivative of the user input.

print('The derivative of x^',exponent,' is


',exponent,'x^',final_exponent,' . ',sep='') #prints the
derivative

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 = []

#this loop will generate to input multiplication symbol in


algebraic expresssion.
for i in algebraic_expression:
if i.isalpha():
i = '*' + i
empty_list.append(i)

algebraic_expression = (''.join(empty_list))

#this loop will will generate if there are already


multiplication symbol in the input algebraic expression.
if '(*' in algebraic_expression:
algebraic_expression = algebraic_expression.replace('(*',
'*(')
if '(' in algebraic_expression:
algebraic_expression = algebraic_expression.replace('(',
'*(')
if '**' in algebraic_expression:
algebraic_expression = algebraic_expression.replace('**',
'*')

print(algebraic_expression) #it will display the algebraic


expression

44
Sample Output:

45
References:

[1] Python documentation. Available at www.python.org [The Python documentation


is terrific. It is nicely formatted, extensive, and easy to find things.]

[2] Lundh, Frederick. An Introduction to Tkinter. Available at www.effbot.org. [This is


a terrific reference for Tkinter.]

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

CvSU QUALITY POLICY

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.

COLLEGE OF ENGINEERING AND INFORMATION TECHNOLOGY GOALS

The College shall endeavor to achieve the following goals:


1. produce globally competent graduates imbued with technical expertise in
engineering, information technology, and allied fields with strong support for
environmental preservation and guided by high ethical standards;
2. conduct relevant research and development activities along engineering,
information technology and allied fields that would contribute to sustainable
development in its service areas;
3. implement effective training and outreach programs that emphasize self-help,
critical thinking and life-long learning;
4. manage projects and enterprises along engineering, information technology and
allied fields to promote economically viable and environment-friendly approaches
and techniques; and
5. establish strong linkages with industries, non-governmental organizations, and
other government entities in the local and international arena for the realization of
common goals.

PROGRAM OBJECTIVES

After completion, Bachelor of Science in Computer Engineering graduates can be


able to:
1. prepared to undertake research and development.
2. conduct systems analysis, perform system design and development and
implement project management.
3. provide appropriate technical support.
4. conduct personnel development
5. engage in continuing professional development
6. engage in technopreneurship and practice professional ethics.

S-ar putea să vă placă și