Lab Quiz 4 – Comments and Solutions

\(\boxdot\) Problem 7
  • The most common form of a solution:

    def alpha_stack(s1, s2):
       s3 = ''
       if len(s1) != len(s2):
           return 'Sorry, the strings must be the same length.'
       for i in range(len(s1)):
           if s1[i] < s2[i]:
               s3 += s1[i]  
           else:  
               s3 += s2[i]  
       return s3  
  • A fewer lines solution using list comprehension:

    def alpha_stack(s1, s2):
        if len(s1) != len(s2):
            return 'Sorry, the strings must be the same length.'
        return ''.join([min(s1[i], s2[i]) for i in range(len(s1))])
\(\boxdot\) Problem 8
  • Using a while loop:

    def int_list(n):
        new_l = []
        while sum(new_l) < 100 and len(new_l) < n:
            new_l.append(random.rand(1,76))  
        return new_l  
  • Another common solution without using a while loop:

    def int_list(n):
        new_l = []
        for i in range(n):
            new_l.append(random.rand(1,76))
            if sum(new_l) >= 100:
                return new_l
        return new_l  
\(\boxdot\) General Comments
  • Pay attention to what must be returned, is it a list, string, Boolean, … ?

  • Do not re-reference any parameters

    def alpha_stack(s1, s2):
        s1 = 'cat'  
        s2 = 'dog'  
  • Initialize a variable before accumulating

  • Cannot traverse (use a range() function) on an int object

  • Adding to a list object:

    l1 = [1, 2, 3, 4]  
    l2 = l1 + [5] = [1, 2, 3, 4, 5]  
    l1.append(5) = [1, 2, 3, 4, 5]  
    l1.append([5]) = [1, 2, 3, 4, [5]]