Solutions

Exploring the Math Module

  1. Using help(math) we see that we’ve got pow(x,y) in addition to sqrt(x), so we could use pow(x, 0.5) to find a square root.
  2. The sqrt(x) function is arguably more readable than pow(x, 0.5) when implementing equations. Readability is a cornerstone of good programming, so it makes sense to provide a special function for this specific common case.

Also the math libraries are likely to be written in an optimsed way. Using the specific function sqrt is therefore likely to be more efficient that pow.

Locating the Right Module

The random module seems like it could help you.

The string has 11 characters, each having a positional index from 0 to 10. You could use random.randrange function (or the alias random.randint if you find that easier to remember) to get a random integer between 0 and 10, and then pick out the character at that position:

from random import randrange

random_index = randrange(len(bases))
print(bases[random_index])

or more compactly:

from random import randrange

print(bases[randrange(len(bases))])

Perhaps you found the random.sample function? It allows for slightly less typing:

from random import sample

print(sample(bases, 1)[0])

Note that this function returns a list of values.

There are also other functions you could use, but with more convoluted code as a result.

Jigsaw Puzzle (Parson’s Problem) Programming Example

import math 
import random
bases = "ACTTGCTTGAC" 
n_bases = len(bases)
idx = random.randrange(n_bases)
print("random base", bases[idx], "base index", idx)

You may have used different variable names in your successful solution!

When Is Help Available?

They have forgotten to import the module import math.

Importing Specific Items

from math import degrees, pi
angle = degrees(pi / 2)
print(angle)

Most likely you find this version easier to read since it’s less dense. The main reason not to use this form of import is to avoid name clashes. For instance, you wouldn’t import degrees this way if you also wanted to use the name degrees for a variable or function of your own. Or if you were to also import a function named degrees from another library