# EXERCISE 1: Contains list1 = [1, 2, 'apple', 3, 'banana'] found_3 = False for value in list1: if value == 3: found_3 = True if found_3: print 'list1 has a 3' else: print 'list1 has no 3s' # EXERCISE 2: Counting values list2 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] ones_count = 0 for value in list2: if value == 1: ones_count += 1 print 'list2 has', ones_count, 'ones' # EXERCISE 3: Repeats list3 = [12, 32, 34, 34, 23, 23, 12, 12] previous_value = list3[0] two_in_a_row = False # Start at the SECOND value in the list: for value in list3[1:] : if value == previous_value: two_in_a_row = True previous_value = value if two_in_a_row: print 'list3 has 2 in a row' else: print 'list3 does not have 2 in a row' # EXERCISE 4: Stats list4 = [12, 32, 33, 35, 23, 23, 12, 12] total = 0 for value in list4: total += value print 'sum:', total # EXERCISE 5: Palindromes list5 = [1, 2, 3, 4, 3, 2, 1] for index in range(len(list5)): if list5[index] % 2 == 1: print 'odd value at index',index # EXERCISE 6: Transitions list6 = [1, 1, 1, 3, 3, 1, 1, 1, 0, 2, 2, 2] previous_value = list6[0] current_run_length = 1 for value in list6[1:] : if value == previous_value: current_run_length += 1 else: # a run just finished! Report it, and start counting again print 'A run of', current_run_length, previous_value current_run_length = 1 previous_value = value # There will always be a run left over: print 'A run of', current_run_length, previous_value