0% found this document useful (0 votes)
14 views

Python For Bioinformatics Cap 4

Uploaded by

celialove17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python For Bioinformatics Cap 4

Uploaded by

celialove17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CHAPTER 4

Programming: Flow Control


CONTENTS
4.1 If-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.1.1 Pass Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.2 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.3 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.4 Break: Breaking the Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.5 Wrapping It Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.5.1 Estimate the Net Charge of a Protein . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.5.2 Search for a Low-Degeneration Zone . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
First Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Version with While . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Version without List of Subchains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
4.6 Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.7 Self-Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

In order to be able to do something useful, programs must have some mechanism


to manage how and when instructions are executed. In the same way that traffic
lights control vehicular flow in a street, flow control structures direct that a code
portion is executed at a given time.
Python has only three flow control structures. There is one conditional and two
iteration structures. A conditional structure (if ) determines, after an expression
evaluation, whether a block of code is executed or not. Iteration structures (for
and while) allow multiple executions of the same code portion. How many times
is the code associated with an iteration structure executed? A for cycle executes
a code block many times as elements are available in a specified iterable element,
while the code under a while cycle is executed until a given condition turns false.1

4.1 IF-ELSE
The most classic control structure is the conditional one. It acts upon the result of
an evaluation. If you know any other computer language, chances are that you are
familiar with if-else.
1
This is equivalent to saying that the condition is executed while the condition is true.

69
70  Python for Bioinformatics

If evaluates an expression. If the expression is true, the block of code just after
the if clause is executed. Otherwise, the block under else is executed.
A basic schema of an if-else condition,

if EXPRESSION:
BLOCK1
else:
BLOCK2

EXPRESSION must be an expression that returns True or False. Like all


comparison operators: x < y (less than), x > y (greater than), x == y (equal to),
x! = y (not equal to), x <= y (less than or equal to), x >= y (greater than or
equal to).

Let’s see an example:

Listing 4.1: ifelse1.py: Basic if-else sample

1 height = float(input(’What is height? (in meters): ’))


2 if height > 1.40:
3 print(’You can get in’)
4 else:
5 print(’This ride is not for you’)

Program output,

What is height? (in meters): 1.80


You can get in

Tip: About the code in this book.

You don’t have to type the code in Listing 4.1 (or any other from this book).
It is available to download from its GitHub repository at https://github.com/
Serulab/Py4Bio. It also can be used online at Microsoft Azure Notebooks (https:
//notebooks.azure.com/library/py3.us). Both links are also available at the
book’s website (http://py3.us/).
Try to execute the code (either locally or online) rather than just read it from
this book.

Another example,

Listing 4.2: ifelse2.py: if-else in action


Programming: Flow Control  71

1 three_letter_code = {’A’:’Ala’,’N’:’Asn’,’D’:’Asp’,’C’:’Cys’}
2 aa = input(’Enter one letter: ’)
3 if aa in three_letter_code:
4 print(’The three letter code for {0} is {1}’.format(aa,
5 three_letter_code[aa]))
6 else:
7 print("Sorry, I don’t have it in my dictionary")

Program output,

Enter one letter: A


The three letter code for A is: Ala

To evaluate more than one condition, use elif :

if EXPRESSION1:
BLOCK1
elif EXPRESSION2:
BLOCK2
elif EXPRESSION3:
BLOCK3
else:
BLOCK4

You can use as many elif as conditions you want to evaluate. Take into account
that once a condition is evaluated as true, the remaining conditions are not checked.
The following program evaluates more than one condition using elif :

Listing 4.3: elif1.py: Using elif

1 dna = input(’Enter your primer sequence: ’)


2 seqsize = len(dna)
3 if seqsize < 10:
4 print(’The primer must have at least ten nucleotides’)
5 elif seqsize < 25:
6 print(’This size is OK’)
7 else:
8 print(’The primer is too long’)

This program (elif1.py) asks for a string with a DNA sequence entered with
the keyboard at runtime. This sequence is called dna. In line 2 its size is calculated
and this result is bound to the name seqsize. In line 3 there is an evaluation. If seqsize
is lower than ten, the message “The primer must have at least ten nucleotides” is
printed. The program flows goes to the end of this if statement, without evaluating
72  Python for Bioinformatics

any other condition in this if statement. But if it is not true (for example, if the
sequence length was 15), it would execute the next condition and its associated
block in case that condition is evaluated as true. If the sequence length were of a
value greater than 10, the program would skip line 4 (the block of code associated
with the first condition) and would evaluate the expression in line 5. If this condition
is met, it will print “This size is OK”. If there is no expression that evaluates as
true, the else block is executed.

Tip: What Is True?


Remember that the statement after the if condition is executed only when the
expression is evaluated as True. So the questions “What is True?” (and “What is
False?”) are relevant.
What is True?:

• Nonempty data structures (lists, dictionaries, tuples, strings, sets). Empty


data structures count as False.
• 0 and None count as False (while other values count as True).
• Keyword True is True and False is False.

If you have a doubt if an expression is True or False, use bool():

>>> bool(1==’1’)
False

Conditionals can be nested:

Listing 4.4: nested.py: Nested if

1 dna = input(’Enter your DNA sequence: ’)


2 seqsize = len(dna)
3 if seqsize < 10:
4 print(’Your primer must have at least ten nucleotides’)
5 if seqsize == 0:
6 print(’You must enter something!’)
7 elif seqsize < 25:
8 print(’This size is OK’)
9 else:
10 print(’Your primer is too long’)

In line 5 there is a condition inside another.


Note the double equal sign (“==” ) instead of the single equal. Double equal is
used to compare values, while the equal sign is used to assign values:
Programming: Flow Control  73

>>> answer=42
>>> answer
42
>>> answer==3
False
>>> answer==42
True

The nested if introduced in Listing 4.4, can be avoided:

Listing 4.5: elif2.py: Nested if

1 dna = input(’Enter your DNA sequence: ’)


2 seqsize = len(dna)
3 if seqsize == 0:
4 print(’You must enter something!’)
5 elif 0 < seqsize < 10:
6 print(’Your primer must have at least ten nucleotides’)
7 elif seqsize < 25:
8 print(’This size is OK’)
9 else:
10 print(’Your primer is too long’)

See how the expression is evaluated in line 5. This leads us to think about
inserting multiple statements in one if, like in Listing 4.6:

Listing 4.6: multiplepart.py: Multiple part condition

1 x = ’N/A’
2 if x != ’N/A’ and 5 < float(x) < 20:
3 print(’OK’)
4 else:
5 print(’Not OK’)

This expression is evaluated from left to right. If one part of the expression is
false, the following parts are not evaluated. Since x=’N/A’, the program will print
’Not OK’ (because the first condition is false). Look what happens when the same
expression is written in reverse order.
This listing (multiplepart2.py),

Listing 4.7: multiplepart2.py: Multiple part condition, inverted

1 x = ’N/A’
74  Python for Bioinformatics

2 if 5 < float(x) < 20 and x != ’N/A’:


3 print(’OK’)
4 else:
5 print(’Not OK’)

returns:

Traceback (most recent call last):


File "multiplepart2.py", line 2, in <module>
if 5 < float(x) < 20 and x != ’N/A’:
ValueError: could not convert string to float: ’N/A’

The ValueError is returned because the string ’N/A’ can’t be converted to


float. In Listing 4.7, x is also evaluated as ’N/A’, but there is no ValueError
because this part of the expression is skipped before evaluation.

4.1.1 Pass Statement


Sometimes there is no need for an alternative choice in an if statement. In this
case you just can avoid using else:

if EXPRESSION:
BLOCK
# Rest of the program...

To make the same code more readable, Python provides the pass statement.
This statement is like a placeholder; it has no other purpose than to put something
when a statement is required syntactically. The following code produces the same
output as the former code:

if CONDITION:
BLOCK
else:
pass
# Rest of the program...

Advanced Tip: Conditional Expressions.


Sometimes comes in handy: the availability of a special syntax to write an if con-
dition in one line

expression1 if condition else expression2

This line will take the value of expression1, if condition is true; otherwise, it will
take the value of expression2.
This syntax allows us to write:
Programming: Flow Control  75

>>> total = 5
>>> items = 2
>>> print(’Average = {0}’.format(total/items if items != 0 else ’N/A’))
Average = 2.5

instead of,

>>> total = 5
>>> items = 2
>>> if items != 0:
... print(’Average = {0}’.format(total/items))
... else:
... print(’Average = N/A’)
...
Average = 2.5

4.2 FOR LOOP


This control structure allows code to be repeatedly executed while keeping a variable
with the value of an iterable object.2 The generic form of a for loop is,

for VAR in ITERABLE:


BLOCK

For example:

for each_item in some_list:


# Do something with each_item
print(each_item)

Note the colon at the end of the first line. This is mandatory. As the indentation
of the block of code the colon is part of the for loop. This structure results in the
repetition of BLOCK as many times as elements are in the iterable object. On
each iteration, V AR takes the value of the current element in IT ERABLE. In
the following code, for walks through a list (bases) with four elements. On each
iteration, x takes the value of one of the elements in the list.

>>> bases = [’C’, ’T’, ’G’, ’A’]


>>> for x in bases:
... print(x)
...
2
The most common iterable objects are lists, tuples, strings, and dictionaries. Files and custom-
made objects can also be iterable.
76  Python for Bioinformatics

C
T
G
A

To know the position on the iterable you are iterating, the method enumerate
will return the index of the iterable along with the value.

>>> bases = [’C’, ’T’, ’G’, ’A’]


>>> for n, x in enumerate(bases):
... print(n, x)
...
0 C
1 T
2 G
3 A

In other languages, the for loop is used to allow a block of code to run a number
of times while changing a counter variable. This behavior can be reproduced in
Python by iterating over a list of numbers:

>>> for n in [0, 1, 2, 3, 4]:


... print(n)
...
0
1
2
3
4

Another alternative to iterate thought a list of numbers, is to generate them with


the built-in function3 range(n). This function returns an iterable object. Which
each time you call it, returns a number, from 0 to the first parameter entered in
the function minus one (that is, n-1).

>>> for x in range(4):


... print(x)
...
0
1
2
3
3
All built-in functions are described in https://docs.python.org/3.6/library/functions.
html.
Programming: Flow Control  77

The following code calculates the molecular weight of a protein based on its
individual amino acids.4 Since the amino acid is stored in a string, the program will
walk through each letter by using for.

Listing 4.8: protwfor.py: Using for to figure the weight of a protein

1 prot_seq = input(’Enter your protein sequence: ’)


2 prot_weight = {’A’:89, ’V’:117, ’L’:131, ’I’:131, ’P’:115,
3 ’F’:165, ’W’:204, ’M’:149, ’G’:75, ’S’:105,
4 ’C’:121, ’T’:119, ’Y’:181, ’N’:132, ’Q’:146,
5 ’D’:133, ’E’:147, ’K’:146, ’R’:174, ’H’:155}
6 total_weight = 0
7 for aa in prot_seq:
8 total_weight = total_weight + prot_weight.get(aa.upper(), 0)
9 total_weight = total_weight - (18 * (len(prot_seq) - 1))
10 print(’The net weight is: {0}’.format(total_weight))

Code explanation: On the first line the user is requested to enter a protein
sequence (for example, MKTFVLHIFIFALVAF). The string returned by input is named
protseq. From line 2 to 5, a dictionary (protweight) with the aminoa acid weights
is initialized. A for loop is used in line 7 to iterate over each element in protseq.
In each iteration, aa takes a value from an element from protseq. This value is
used to search in the protweight dictionary. After the cycle, totalW will end up
with the sum of the weight of all amino acids. In line 9 there is a correction due
to the fact that each bond involves the loss of a water molecule (with molecular
weight of 18). The last line prints out the net weight.

4.3 WHILE LOOP


A loop is very similar to for since it also executes a code portion in a repeated way.
In this case there is no iteration over an object, so this loop doesn’t end when the
iteration object is traversed, but when a given condition is not true.
Model of while loop:

while EXPRESSION:
BLOCK

It is very important to take into account that there should be an instruction


inside the block to make the while condition false. Otherwise, we could enter into
an infinite loop.
4
Amino acids are the building blocks of the proteins. Each amino acid (represented by a single
letter) has an individual weight. Since each amino acid bond releases a water molecule (with a
weight of 18 iu), the weight of all the water molecules released is subtracted from the total.
78  Python for Bioinformatics

>>> a = 10
>>> while a < 40:
... print(a)
... a += 10
...
10
20
30

A way to exit from a while loop is using break. In this case the loop is broken
without evaluating the loop condition. break is often used in conjunction with a
condition that is always true:

>>> a = 10
>>> while True:
... if a < 40:
... print(a)
... else:
... break
... a += 10
...
10
20
30

This is done to ensure the block inside the loop is executed at least once. In
other languages there is a separate loop type for these cases (do while), but it is
not present in Python.5

4.4 BREAK: BREAKING THE LOOP


break is used to escape from a loop structure. We’ve just seen a usage example
with while, but it can also be used under for.
It is not easy at first to realize where using a break statement actually makes
sense.
Take, for example, Listing 4.9:

Listing 4.9: seachinlist.py: Searching a value in a list of tuples

1 color_code = [(’red’, 1), (’green’, 2), (’blue’, 3), (’black’, 4)]


2 name = ’blue’
3 for color_pair in color_code:
4 if name == color_pair[0]:
5
A proposal to add this structure to Python was rejected in 2013.
Programming: Flow Control  79

5 code = color_pair[1]
6 print(code)

In this code there is a for loop to iterate over color_code list. For each element,
that is, for each tuple, it checks for the first element. When it matches our query
(name), the program stores the associated code in code.
So the output of this program is “3.”
The problem with this program is that the whole sequence is walked over, even
if we don’t need to. In this case, the condition in line 4 is evaluated once per each
element in color_code when it is clear that once the match is positive there is no
need to keep on testing. You can save some time and processing power by breaking
the loop just after the positive match:

Listing 4.10: seachinlist2.py: Searching a value in a list of tuples

1 color_code = [(’red’,1), (’green’,2), (’blue’,3), (’black’,4)]


2 name = ’blue’
3 for color_pair in color_code:
4 if name == color_pair[0]:
5 code = color_pair[1]
6 break
7 print(code)

This code is identical to Listing 4.9 with the exception of the break statement
in line 6. The output is the same as before, but this time you don’t waste CPU
cycles iterating over a sequence once the element is found. The time saved in this
example is negligible, but if the program has to do it several times over a big list
or file (you can also iterate over a file), break can speed it up in a significant way.
The use of break can be avoided, but the resulting code is not legible as in
Listing 4.10:

Listing 4.11: seachinlist3.py: Searching a value in a list of tuples

1 color_code = [(’red’,1), (’green’,2), (’blue’,3), (’black’,4)]


2 name = ’blue’
3 i = 0
4 while name != color_code[i][0]:
5 i += 1
6 code = color_code[i][1]
7 print(code)

In a case like this, with a list that can easily fit in memory, it is a better idea
to create a dictionary and query it:
80  Python for Bioinformatics

Listing 4.12: seachindict.py: Searching a value in a list of tuples using a dictio-


nary

1 color_code = [(’red’,1), (’green’,2), (’blue’,3), (’black’,4)]


2 name = ’blue’
3 color_code_d = dict(color_code)
4 print(color_code[name])

4.5 WRAPPING IT UP
Now we will combine if, for, while and the data type seen up to this point. Here
I present some small programs made with the tools we’ve just learned:

4.5.1 Estimate the Net Charge of a Protein


At a fixed pH, it is possible to calculate the net charge of a protein summing the
charge of its individual amino acids. This is an approximation since it doesn’t take
into account if the amino acids are exposed or buried in the protein structure.
This program also fails to take into account the fact that cysteine adds charge
only when it is not part of a disulfide bridge. Since it is an approximate value the
obtained values should be regarded as an estimation. Here is the first version of
protnetcharge.py:

Listing 4.13: protnetcharge.py: Net charge of a protein

1 prot_seq = input(’Enter protein sequence: ’).upper()


2 charge = -0.002
3 aa_charge = {’C’:-.045,’D’:-.999,’E’:-.998,’H’:.091,
4 ’K’:1,’R’:1,’Y’:-.001}
5 for aa in prot_seq:
6 if aa in aa_charge:
7 charge += aa_charge[aa]
8 print(charge)

The if statement in line 6 can be avoided with get():

Listing 4.14: protnetcharge2.py: Net charge of a protein using get

1 prot_seq = input(’Enter protein sequence: ’).upper()


2 charge = -0.002
3 aa_charge = {’C’:-.045,’D’:-.999,’E’:-.998,’H’:.091,
4 ’K’:1,’R’:1,’Y’:-.001}
5 for aa in prot_seq:
Programming: Flow Control  81

7 charge += aa_charge.get(’aa’, 0)
8 print(charge)

4.5.2 Search for a Low-Degeneration Zone


To find PCR primers, it is better to use a DNA region with less degeneration (or
more conservation). This give us a better chance to find the target sequence. The
aim of this program is to search for this region. Since a PCR primer has about 16
nucleotides, to give room for the primer design, the search space should be at least
45 nucleotides long. We should find a 15 amino acid region in the input sequence.
15–amino acids provides a search region of 45 nucleotides (3 nucleotides per amino
acid).
Each amino acid is encoded by a determined number of codons. For example,
valine (V) can be encoded by four different codons (GTT, GTA, GTC, GTG), while
tryptophan (W) is encoded only by one codon (TGG). Hence a region rich in valines
will have more variability than a region with lots of tryptophan.
A program that finds a low-degeneration region:

First Version

Listing 4.15: lowdeg.py: Search for a low degeneration zone

1 prot_seq = input(’Protein sequence: ’).upper()


2 prot_deg = {’A’:4, ’C’:2, ’D’:2, ’E’:2, ’F’:2, ’G’:4,
3 ’H’:2, ’I’:3, ’K’:2, ’L’:6, ’M’:1, ’N’:2,
4 ’P’:4, ’Q’:2, ’R’:6, ’S’:6, ’T’:4, ’V’:4,
5 ’W’:1, ’Y’:2}
6 segs_values = []
7 for aa in range(len(prot_seq)):
8 segment = prot_seq[aa:aa + 15]
9 degen = 0
10 if len(segment)==15:
11 for x in segment:
12 degen += prot_deg.get(x, 3.05)
13 segs_values.append(degen)
14 min_value = min(segs_values)
15 minpos = segs_values.index(min_value)
16 print(prot_seq[minpos:minpos + 15])

Code explanation: Takes a string (prot_seq) entered by the user. The pro-
gram uses a dictionary (prot_deg) to store the NUMBER of codons that corre-
sponds to each amino acid. From line 7 to 9, we generate sliding windows of length
15. For each 15 amino acid segments, the number of codons is evaluated, then we
82  Python for Bioinformatics

select the segment with less degeneration (line 14). Note that in line 10 there is a
check of the size of segment, since when the sequence of prot_seq slides away, the
subchain has less than 15 amino acids.

Version with While

Listing 4.16: lowdeg2.py: Searching for a low-degeneration zone; version with


while

1 prot_seq = input(’Protein sequence: ’).upper()


2 prot_deg = {’A’:4, ’C’:2, ’D’:2, ’E’:2, ’F’:2, ’G’:4,
3 ’H’:2, ’I’:3, ’K’:2, ’L’:6, ’M’:1, ’N’:2,
4 ’P’:4, ’Q’:2, ’R’:6, ’S’:6, ’T’:4, ’V’:4,
5 ’W’:1, ’Y’:2}
6 segs_values = []
7 segs_seqs = []
8 segment = prot_seq[:15]
9 a = 0
10 while len(segment)==15:
11 degen = 0
12 for x in segment:
13 degen += prot_deg.get(x, 3.05)
14 segs_values.append(degen)
15 segs_seqs.append(segment)
16 a += 1
17 segment = prot_seq[a:a+15]
18 print(segs_seqs[segs_values.index(min(segs_values))])

Code explanation: This version doesn’t use a for to walk over prot_seq;
instead, it uses while. Code will be executed as long as the sliding window is inside
prot_seq.

Version without List of Subchains

Listing 4.17: lowdeg3.py: Searching for a low-degeneration zone without sub-


chains

1 prot_seq = input(’Protein sequence: ’).upper()


2 prot_deg = {’A’:4, ’C’:2, ’D’:2, ’E’:2, ’F’:2, ’G’:4,
3 ’H’:2, ’I’:3, ’K’:2, ’L’:6, ’M’:1, ’N’:2,
4 ’P’:4, ’Q’:2, ’R’:6, ’S’:6, ’T’:4, ’V’:4,
5 ’W’:1, ’Y’:2}
6 degen_tmp = max(prot_deg.values()) * 15
Programming: Flow Control  83

7 for n in range(len(prot_seq) - 15):


8 degen = 0
9 for x in prot_seq[n:n + 15]:
10 degen += prot_deg.get(x, 3.05)
11 if degen <= degen_tmp:
12 degen_tmp = degen
13 seq = prot_seq[n:n + 15]
14 print(seq)

Code explanation: In this case every degeneration value is compared with the
last one (line 10), and if the current value is lower, it is stored. Note that the first
time a degeneration value is evaluated, there is no value to compare it with. This
problem is sorted in line 6 where a maximum theoretical value is provided.

4.6 ADDITIONAL RESOURCES


• Python tutorial: More control flow tools.
https://docs.python.org/3.6/tutorial/controlflow.html

• Python programming: Flow control.


http://en.wikibooks.org/wiki/Python_Programming/Flow_control

• Python Basics: Understanding The Flow Control Statements.


https://goo.gl/ss6uNh

• Python in a Nutshell, Second Edition. By Alex Martelli. Chapter 4.


Excerpt at http://www.devshed.com/c/a/Python/The-Python-Language

• Python break, continue and pass Statements.


http://www.tutorialspoint.com/python/python_loop_control.htm

4.7 SELF-EVALUATION
1. What is a control structure?

2. How many control structures does Python have? Name them.

3. When would you use for and when would you use while?

4. Some languages have a do while control structure. How can you get a similar
function in Python?

5. Explain when you would use pass and when you would use break.

6. In line 6 of Listing 4.16, the condition under the while can be changed from
len(P rotSeq[i : i + 15]) == 15 to i < (len(P rotSeq) − 7). Why?
84  Python for Bioinformatics

7. Make a program that outputs all possible IP addresses, that is, from 0.0.0.0
to 255.255.255.255.

8. Make a program to solve a linear equation with two variables. The equation
must have this form:
a1 .x + a2 .y = a3
b1 .x + b2 .y = b3
The program must ask for a1 , a2 , a3 , b1 , b2 , and b3 and return the value of x
and y.

9. Make a program to check if a given number is a palindrome (that is, it remains


the same when its digits are reversed, like 404).

10. Make a program to convert Fahrenheit temperature to Celsius and write the
result with only one decimal value. Use this formula to make the conversion:
Tc = (5/9) ∗ (Tf − 32)

11. Make a program that converts everything you type into Leetspeak, using the
following equivalence: 0 for O, 1 for I (or L), 2 for Z (or R), 3 for E, 4 for A,
5 for S, 6 for G (or B), 7 for T (or L), 8 for B, and 9 for P (or G and Q). So
“Hello world!” is rendered as “H3770 w02ld!”

12. Given two words, the program must determine if they rhyme or not. For this
question “rhyme” means that the last three letters are the same, like wizard
and lizard.

13. Given a protein sequence in the one-letter code, calculate the percentage of
methionine (M) and cysteine (C). For example, from MFKFASAVILCLVAASSTQA
the result must be 10% (1 M and 1 C over 20 amino acids).

14. Make a program like Listing 4.17 but without using a predefined maximum
value.

You might also like