JamCoders

💾 Download

Lecture 4, Part 1 Exercises

Question 1: List Indexing and Reversing!

Execute all the following cells in order.

In [ ]:
# ALWAYS RUN THIS CELL

%config InteractiveShell.ast_node_interactivity="none"
def print_locals(*which):
    """Print the local variables in the caller's frame."""
    import inspect
    ls = inspect.currentframe().f_back.f_locals
    which = set(which if which else ls.keys())
    ll = {k: v for k, v in ls.items() if k in which}
    print("; ".join(f"{k}{v}" for k, v in ll.items()))

1.1

Write a list called my_list that contains 5 integers.

In [ ]:

1.2

Print the first element in my_list

In [ ]:

1.3

Remember from previous labs that you can use negative indices for lists. Print the second to last element in my_list using negative indices.

In [ ]:

1.4

Now, write a function reverseTwo that returns a two element list containing the last two elements of my_list in reversed order.

Ex: reverseTwo([1, 2, 3, 4]) ==> [4, 3]

In [ ]:
def reverseTwo(l):
    # Write your code here.


    # Here is a test case to check if your code works correctly.
    # Feel free to add your own!
print(reverseTwo([1, 2, 3, 4]))  # Should be [4, 3]
In [ ]:
k = 0
for i in range(3):
    print(k)

1.5

Write a function reverseList that takes in a list lst and returns the reversed list.

Ex: reverseList([1, 2, 3, 4]) => [4, 3, 2, 1]

In [ ]:
def reverseList(my_list):
    # Write your code here.


    # Here is a test case to check if your code works correctly.
    # Feel free to add your own!
print(reverseTwo([1, 2, 3, 4]))  # Should be [4, 3, 2, 1]
[4, 3]

Question 2: DN that A!

2.1

DNA has 4 bases: Adenine (A), Thymine (T), Cytosine (C), Guanine (G). In the DNA, each base fits like a puzzle piece, with another base. So, Adenine will pair up with Thymine (A-T base pairing) and Cytosine will pair up with Guanine (C-G base pairing), and vice versa. DNA is double stranded, so if we look at one side side of the strand, we can figure out the other side that matches. For example:

  • ATACGTACGATCA #this is the strand we know
  • TATGCATGCTAGT #this is the complement strand, that we can figure out.

Just as an exercise, figure out the complement strand to the following strands manually:

  1. ATCCGGGATCAA

  2. GGCCCCATTTTC

  3. TTACCAGGGGAT

Fill this in.

2.2

Given a string x that contains only A, C, G, and T characters, write a function called containsA that returns True if the string contains an Adenine, expressed as an 'A'.

In [ ]:
def containsA(dna):
    # Write your code here.

2.3

Given a string x that contains only A, C, G, and T characters, write a function called complementStrand that will return the complement DNA strand explained in 2.1.

In [ ]:
def complement(DNA):
    # Write your code here.


    # Here is a test case to check if your code works correctly.
    # Feel free to add your own!
print(complement('GATTACA'))  # Should be 'CTAATGT'
CTAATGT

Question 3: My Alphabet

Execute all the following cells in order.

3.1

Create a list called vowels that contains all the vowels from the English alphabet.

In [ ]:

3.2

Create a variable called my_letter that has the value "a".

In [ ]:

3.3

Now, write a conditional statement that returns True when my_letter is equal to "a".

In [ ]:

Out[ ]:
True

3.4

Write a function printVowels that iterates through vowels and prints each element.

In [ ]:
def printVowels():
    # Fill in your code here!
    # Note: You can use `vowels` from inside this function.


# Here is a test case to check if your code works correctly.
printVowels()

3.5

Now, write a function called isVowel that takes in a string letter and returns True if letter is a vowel and False otherwise. Do this by looping through vowels with a for loop.

In [ ]:
def isVowel(letter):
  # Write your code here.


# Here are test cases to check if your code works correctly.
print(isVowel('a'))  # Should be True
print(isVowel('b'))  # Should be False

3.6

Write a function isVowel2 that does the same thing as $3.5$, but using only conditional statements or boolean expressions.

In [ ]:
def isVowel2(letter):
    # Write your code here.


# Here are test cases to check if your code works correctly.
print(isVowel2('a'))  # Should be True
print(isVowel2('b'))  # Should be False

3.7

Create a function called isConsonant, that returns True if the input is not a vowel, and False otherwise.

In [ ]:
def isConsonant(letter):
    # Write your code here.

3.8

Try running the code below. Does it do what you expect?

In [ ]:
print(isConsonant("a"))
print(isConsonant("b"))
print(isConsonant("1"))
print(isConsonant("."))

3.9

Rewrite isConsonant so that it also returns False when it is not part of the alphabet.

In [ ]:
# Useful functions and variables for you to use:
alphabet = "abcdefghijklmnopqrstuvwxyz"

def isConsonant(letter):
    # Write your code here.


# Test your code here.
print(isConsonant("a"))
print(isConsonant("b"))
print(isConsonant("1"))
print(isConsonant("."))

# Extra challenge: can you edit your code so it works on upper and lower case text?

Question 4: Ready SET go!

4.1

Write a function inTheList that takes in a list lst and a target element t that returns True if t is in lst and False otherwise. Use a for-loop.

In [ ]:
def inTheList(lst, t):
  # Write your code here.



# Test your code here - what kinds of lists can you use your function on?
# Try to write your function so that it works on lists of any datatype, for example
music_list = ["kanye", "chronixx", "beyonce", "bobmarley"]  # list of strings
fibonacci_list = [1, 1, 2, 3, 5, 8, 13, 21, 34]             # list of integers

4.2

Write a function overlaps which takes in two lists, lst1 and lst2, and returns True if any element from lst1 is also in lst2 and False otherwise. You must use for-loops.

In [ ]:
def overlaps(lst1, lst2):
  # Write your code here.



# Test your code here.

4.3

Write a function intersection which takes in two lists, lst1 and lst2, and returns a list containing the all the elements present in both lists. You must use for-loops.

In [ ]:
def intersection(lst1, lst2):
  # Write your code here.


# Test your code here.
print(intersection([1, 2, 3], [2, 3, 4])) # should return [2, 3]
In [ ]:

`# This is formatted as code`


Question 5: Sum Fun!

5.1

Write a function cumulativeSum that takes in a list lst, and returns the list that represents the cumulative sum. In other words, the i-th element in the final list should be equal to the sum of the elements from 0 to i in the input list.

Ex: [1, 2, 3] => [1, 3, 6], [5, 10, 15] => [5, 15, 30]

Hint: You don't need 2 loops. If you have found the i-th element in the final list, how would use it to find the (i+1)-th element?

In [ ]:
def cumulativeSum(lst):
  # Write your code here.


    # Test your code here.
print(cumulativeSum([1, 2, 3]))  # Should be [1, 3, 6]
[1, 3, 6]

5.2

Write a function largestCumulativeSum that takes in a list lst, and returns an integer i for which the sum of the elements from $0$ to $i$ is the largest.

Please try to do this with only one loop as well.

Ex: [10, -6, 4, 8, -5] => 3, [20, -15, 3, 1, 1, 1, 5, 2] => 0

In [ ]:
def largestCumulativeSum(lst):
  # Write your code here.


    # Test your code here:
print(largestCumulativeSum([10, -6, 4, 8, -5]))  # Should be 3
3

Question 8: Prime Time

8.1

Write a function isPrime that takes in an integer x, and returns the boolean True if the number is prime, and false otherwise. As a reminder, a prime number is a number that is only divisible by itself and 1.

Hint: Use the modulo operator to check if x is divisible by a number.

In [ ]:
def isPrime(x):
    # Write your code here.


    # Test your code here.
print(isPrime(2))  # Should be True
print(isPrime(5))  # Should be True
print(isPrime(8))  # Should be False
True
True
False

8.2

Write a function primesToX that takes in an integer x, and returns a list of all the prime numbers smaller or equal to x.

In [ ]:
def primesToX(x):
    # Write your code here.

    # Test your code here

8.3

Write a function nextPrime that takes in an integer x, and returns the first prime greater than x.

In [ ]:
def nextPrime(x):
    # Write your code here.

    # Test your code here

Question 9: Hash

9.1

Write a function hashExtract that takes in a string s, and returns a list of all the words that start with a hashtag (#).

Ex: 'I'm so excited to code for #AddisCoder! Looking to learn lots of #CS." => ['AddisCoder', 'CS']

In [ ]:
def hashExtract(s):
    # Write your code here.


    # Test your code here.
print(hashExtract("I'm so excited to code for #AddisCoder! Looking to learn lots of #CS."))
['AddisCoder', 'CS']

Question 10: ListInterweave

9.1

Write a function interweave that takes in two lists, lst1 and lst2, and returns a list of the elements from lst1 and lst2 that first places an element from lst1, then places an element from lst2, and continues to do that until all the elements have been placed in the new list. You may assume that the list lengths are equivalent.

Ex: [1,2,3], [4, 5, 6] => [1, 4, 2, 5, 3, 6], [13, 4, 6, 8], [17, 2, 1, 5] => [13, 17, 4, 2, 6, 1, 8, 5]

In [ ]:
def interweave(lst1, lst2):
    # Write your code here.


    # Test your code here!
print(interweave([1, 2, 3], [4, 5, ]))