CMU 15-110: Principles of Computing
1d Lists (Part 2)


  1. Swapping Elements
  2. List Aliases
  3. Sorting Lists
  4. Example: Anagrams

  1. Swapping Elements
    • Failed swap
      a = [ 2, 3, 5, 7 ] print('a =', a) a[0] = a[1] a[1] = a[0] print('After failed swap of a[0] and a[1]:') print(' a=',a)

    • Swap with a temp variable
      a = [ 2, 3, 5, 7 ] print('a =', a) temp = a[0] a[0] = a[1] a[1] = temp print('After swapping a[0] and a[1]:') print(' a=',a)

  2. List Aliases
    • Aliases example:
      # Create a list a = [ 2, 3, 5, 7 ] # Create an alias to the list b = a # We now have two references (aliases) to the SAME list a[0] = 42 b[1] = 99 print(a) print(b)

    • Copying lists:
      print('Use (a + [ ]) to copy a list:') a = [2, 3] b = a + [ ] # creates a copy of a a[0] = 42 print(a) print(b)

    • Copies are not aliases:
      # Create a list a = [ 2, 3, 5, 7 ] # Create a COPY of the list b = a + [ ] # creates a copy of a # These are not aliases -- changes to one do not affect the other a[0] = 42 b[1] = 99 print(a) print(b)

    • Function parameters are aliases:
      def f(a): a[0] = 42 a = [2, 3, 5, 7] f(a) print(a)

  3. Sorting Lists
    • Using sort is destructive (modifies the list)
      a = [ 7, 2, 5, 3, 5, 11, 7 ] a.sort() print(a)

    • Using sorted is non-destructive (creates a new list)
      a = [ 7, 2, 5, 3, 5, 11, 7 ] b = sorted(a) print(a) print(b)

  4. Example: Anagrams
    def letterCounts(s): counts = [0] * 26 for c in s.upper(): if (c.isalpha() == True): counts[ord(c) - ord('A')] += 1 return counts # Here are two very different ways to solve isAnagram: def isAnagram(s1, s2): return (letterCounts(s1) == letterCounts(s2)) def isAnagram(s1, s2): return sorted(s1.upper()) == sorted(s2.upper()) def testIsAnagram(): print('Testing isAnagram()...') assert(isAnagram('', '') == True) assert(isAnagram('abCdabCd', 'abcdabcd') == True) assert(isAnagram('abcdaBcD', 'AAbbcddc') == True) assert(isAnagram('abcdaabcd', 'aabbcddcb') == False) print('Passed!') testIsAnagram()