3: Lists

3.1 Print List

Write a function that prints out a list, one element per line

3.1.1 Example

 1: breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
 2: 
 3: print_list(breakfast)
 4:  *** Output ***
 5: Sausage
 6: Eggs
 7: Beans
 8: Bacon
 9: Tomatoes
10: Mushrooms

3.2 Last Element of Array

Write a function that returns the last element of a string array

3.2.1 Example

1: breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
2: 
3: print(last_element(breakfast));
4:  *** Output ***
5: Mushrooms

3.3 Last But One Element of Array

Write a function that returns the last but one element of a string array

3.3.1 Example

1: breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
2: 
3: print(last_but_one(breakfast));
4:  *** Output ***
5: Tomatoes

3.4 Reverse a list, leaving original intact

Return a list in reverse order, while leaving the original list intact.

3.4.1 Example

 1: breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
 2: 
 3: print(my_reverse(breakfast))
 4: print(breakfast)
 5:  *** Output ***
 6: : Mushrooms
 7: : Tomatoes
 8: : Bacon
 9: : Beans
10: : Eggs
11: : Sausage
12: : Sausage
13: : Eggs
14: : Beans
15: : Bacon
16: : Tomatoes
17: : Mushrooms

3.5 Palindromic lists

Write a function that tests to see if a list is palindromic, i.e. the elements are the same when reversed.

3.5.1 Example

1: palindromic = ["Sausage", "Eggs", "Beans", "Beans", "Eggs", "Sausage"]
2: breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
3: 
4: print(is_palindrome(palindromic))
5: print(is_palindrome(breakfast))
6:  *** Output ***
7: True
8: False

3.6 Consecutive Duplicates

Write a function to print out list of integers with consecutive duplicates eliminated

1: nums = [1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4]
2: 
3: compress(nums)
4:  *** Output ***
5: : 1
6: : 3
7: : 2
8: : 1
9: : 4

3.7 Pack Duplicates

Pack consecutive duplicates of a char list into Strings

1: letters = ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']
2: 
3: pack(letters)
4:  *** Output ***
5: : aaaa, b, cc, aa, d, eeee

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.