Harold Nelson
9/22/2021
Ex1
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times(‘Hi’, 2) → ‘HiHi’
string_times(‘Hi’, 3) → ‘HiHiHi’
string_times(‘Hi’, 1) → ‘Hi’
def string_times(str, n):
## 'HiHi'
## 'HiHiHi'
## 'Hi'
Given a string and a non-negative int n, we’ll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;
front_times(‘Chocolate’, 2) → ‘ChoCho’
front_times(‘Chocolate’, 3) → ‘ChoChoCho’
front_times(‘No’,2) → ’NoNo"
def front_times(str, n):
## 'ChoCho'
## 'ChoChoCho'
## 'NoNo'
Given a string, return a new string made of every other char starting with the first, so “Hello” yields “Hlo”.
string_bits(‘Hello’) → ‘Hlo’
string_bits(‘Hi’) → ‘H’
string_bits(‘Heeololeo’) → ‘Hello’
def string_bits(str):
Given an array of ints, return the number of 9’s in the array.
array_count9([1, 2, 9]) → 1
array_count9([1, 9, 9]) → 2
array_count9([1, 9, 9, 3, 9]) → 3
def array_count9(nums):
Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.
array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False
def array_front9(nums):
## True
## False
## True
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
def array123(nums):
## True
## False
## True
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So “xxcaazz” and “xxbaaz” yields 3, since the “xx”, “aa”, and “az” substrings appear in the same place in both strings.
string_match(‘xxcaazz’, ‘xxbaaz’) → 3
string_match(‘abc’, ‘abc’) → 2
string_match(‘abc’, ‘axc’) → 0
def string_match(a, b):
def string_match(a, b):
# Figure which string is shorter.
shorter = min(len(a), len(b))
count = 0
# Loop i over every substring starting spot.
# Use length-1 here, so can use char str[i+1] in the loop
for i in range(shorter-1):
a_sub = a[i:i+2]
b_sub = b[i:i+2]
if a_sub == b_sub:
count = count + 1
return count
## 3
## 2
## 0
Given a string s, return the number of vowels in the string. Exclude ‘y’, but include both upper and lower case vowels.
vowel_count(‘Help, I am drowning’) -> 5 vowel_count(‘abCdEf’) -> 2
def vowel_count(s):