Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
10327 views
ubuntu2004
Kernel: Python 3 (system-wide)

Exercise 20.1

Write a function called reverse_string() which prints the reverse of a string passed to it.

The call to the function is already included in the following code cell. You just need to write the function.

  • Hint: See Notebook 6 for how to reverse a string

def reverse_string(s): '''Print reverse of string''' print(s[::-1]) reverse_string( 'ebmoG fo seeznapmihc ehT' )

Exercise 20.2

Write a function called average() that takes a list as an argument and prints out the average values in the list.

  • Hint: See Task 3.10 if you have forgotten how to calculate the average of a list of values.

arriving_penguins = [10, 156, 73, 376, 786, 432, 1035, 901, 1102, 2567, 1571, 916, 1560, 632, 943, 246, 654, 1456, 504, 632]
def average(x): '''Average of a list of numbers''' print( sum(x)/len(x) ) average( arriving_penguins )

Exercise 20.3

Write a function called multiply_two_numbers() that prints the product of two number passed to it.

def multiply_two_numbers(n1, n2): '''Product of two numbers''' print(n1*n2) n1 = float(input('Enter a number: ')) n2 = float(input('Enter another number: ')) multiply_two_numbers( n1, n2 )

Exercise 20.4

Write a function called count_bases() that takes two arguments. The first argument is a DNA sequence and the second is a string of the bases to be counted. If the second argument is missing then all bases should be counted.

The function should print the count of the specified bases.

  • Hint: Reuse the code in Notebook 13 on Nested loops

dna_seq = 'ACGCGCAGATAGGACGCAGGGAGGGAGGAGGTTTTAGAAGAGGATAGACCCA'
def count_bases(dna_seq, bases='ACGT'): '''Count the frequency of each base specfied in bases in dna_seq. If no bases are given count all four bases.''' # Print the DNA sequence. print(dna_seq) # Loop through each base in bases. for base in bases: # Count the number of occurrences of the current base in the DNA sequence. count_base = dna_seq.count(base) if count_base == 1: # If there is a single occurrence of the current base print this: print( f'There is {count_base} "{base}"' ) else: # Otherwise there are no, or more than one, occurrences so print this: print( f'There are {count_base} "{base}"s' ) count_bases(dna_seq, 'A') count_bases(dna_seq, 'AT') count_bases(dna_seq)