This notebook is intended to test your comprehension of some important coding concepts that will be relevant moving forward so that you can write and interpret Python code. Please revisit old notebooks and lecture slides or search for help on online for topics that you find challenging. It is up to you to import any required libraries to accomplish the requested tasks.
All cells in this notebook are 'challenges' that you should try to complete as part of the assignment.
# create a string object and store it to a variable x
x = "hello world"
# create a string object with a newline character in it and print it.
y = "hello\nworld"
# create a list made up of a mixture of integers and floats
mix = [1, 2, 3.0, 6.6, 2e3]
# create a dictionary
mydict = {'a': 3, 'b': 4, 'c': 10}
# 1. Create a dictionary object with several key-value pairs
# 2. Iterate over the dict printing the key and value of each item
mydict = {'a': 3, 'b': 4, 'c': 10}
for key in mydict:
print(key, mydict[key])
# 1. Create a list of 25 randomly sampled integers.
# 2. Use list-comprehension to create a new list where another
# random integer is added to each item in the first list.
import random
intlist = [random.randint(0, 10) for i in range(25)]
sumlist = [intlist[i] + random.randint(0, 10) for i in range(25)]
# 1. Create a numpy array of 25 randomly sampled integers.
# 2. Create another array where a random integer is added to every
# item in the first array.
import numpy as np
arr1 = np.random.randint(0, 10, 25)
arrsum = arr1 + np.random.randint(0, 10, 25)
# 1. Create a list with several string objects in it.
# 2. Iterate over the items in the list.
# 3. For each item, use a conditional statement that will select
# some of the items but not others.
# 4. print the items that return True to the conditional statement.
slist = ['a', 'b', 'c', 'd']
for item in slist:
if item == 'b':
print(item)
# use bash or Python code to download the file from the following URL
URL = "https://eaton-lab.org/data/40578.fastq.gz"
%%bash
URL="https://eaton-lab.org/data/40578.fastq.gz"
wget $URL -q
# add comments after '#' in the following function.
# feel free to take apart and test parts of the function
# to learn what each part is doing.
def reverse_complement(dnastring):
"""
Returns the reverse-complement of a string of DNA.
"""
# a dictionary to convert bases to their complement
compdict = {
'A': 'T',
'C': 'G',
'G': 'C',
'T': 'A',
}
# list comprehension to get the complement of each base
complist = [compdict[i] for i in dnastring]
# string join command to convert list to a string
compstring = "".join(complist)
# reverse the order of items in the string
revcompstring = compstring[::-1]
# return the reverse complemented string
return revcompstring
# write a function to read the 40578.fastq.gz file and *return*
# the length of the *first sequenced read* in the file. And
# apply the function to the file to return the result.
import gzip
def get_fastq_length(infile):
with gzip.open(infile, 'rt') as indata:
# read first line (header)
indata.readline()
# read second line (first sequence)
return len(indata.readline())
# test it
get_fastq_length("40578.fastq.gz")
Please revisit your assignments, the lecture slides, and/or the documentation for tips on using Pandas and Numpy.
# Create a pandas dataframe with three columns composed of
# randomly generated data created using the numpy.random
# library. The first columns should be random integers,
# the second random float values, and the last one
# should a random string of A,C,G or T. Create 100
# rows of data in total.
import pandas as pd
df = pd.DataFrame({
"integers": np.random.randint(0, 50, 100),
"floats": np.random.normal(0, 1, 100),
"strings": np.random.choice(list("ACGT"), 100),
})
# show
df.head()
# Select all rows of the dataframe from above where the
# third column is equal to "A".
# select rows
selectA = df[df["strings"] == "A"]
# show result head
selectA.head()
# Select all rows of the dataframe from above where the
# third column is equal to "T" and change the values to "U".
# select ROWS and COL to change, use .loc or .iloc
df.loc[df["strings"] == "T", "strings"] = "U"
# show result head
df.head(20)
# Load a CSV file using the pandas library from the following URL
# and set appropriate names for the columns.
URL = "https://eaton-lab.org/data/iris-data-dirty.csv"
# load and set names
iris = pd.read_csv(URL, names=["trait1", "trait2", "trait3", "trait4", "taxon"])
# show
iris.head()
# print all *unique* values in the column with taxon names
iris["taxon"].unique()
# replace the names that appear to be typos in the names column
iris.loc[iris["taxon"] == "Iris-setsa", "taxon"] = "Iris-setosa"
iris.loc[iris["taxon"] == "Iris-versicolour", "taxon"] = "Iris-versicolor"
# write code here to save the new revised dataframe as a CSV file.
iris.to_csv("./iris-revised.csv")
# Write the contents of the string object below to a new
# file called "hello-world.txt".
mystring = "hello world"
with open("hello-world.txt", 'w') as out:
out.write(mystring)
# open the file "hello-world.txt" by writing the *full path*
# to the location of the file on your filesystem. Read
# the contents of the file and print it.
# write full path or get it using os.path
import os
fullpath = os.path.abspath("./hello-world.txt")
# write to full path
with open(fullpath, 'r') as indat:
print(indat.read())