Class 3
Author: Jose Miguel Arrieta R.
Additional resource: http://cs231n.github.io/python-numpy-tutorial/#python-tuples
A tuple is an (immutable) ordered list of values.
*see examples
# Create a tuple
t = (5, 6)
# Create a tuple
tuplex = 'tuple', False, 3.2, 1
Only the following two methods are available.
*see more examples
my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
A list is the Python equivalent of an array, but is resizable and can contain elements of different types
*see examples
xs = [3, 1, 2] # Create a list
#See concatenate lists and methods
Python provides concise syntax to access sublists; this is known as slicing
*see examples
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
animals = ['cat', 'dog', 'monkey']
"""
Loops: You can loop over
the elements of a list like this
"""
for animal in animals:
print(animal)
"""
If you want access to the index of each element within the body of a loop,
use the built-in enumerate function
"""
for idx, animal in enumerate(animals):
print(str(idx)+') ' +animal)
"""
Bad alternative from Java style developers,
better use built in enumerate
"""
for i in range(0,len(animals))
print(animal[i])
A set is an unordered collection with
no duplicate elements.
animals = {'cat', 'dog','cat','dog','turtle'}
*see examples
A dictionary stores (key, value) pairs,
similar to a Map in Java or an object in Javascript.
# Create a new dictionary with some data
d = {'cat': 'cute', 'dog': 'furry'}
*see examples
#dict to lists
"""
Note: For python 2.7, python 3.x returns a 'Dictionary view objects'
"""
d = {'a': 'Jose', 'b': 'Miguel'}
d_keys = d.keys() #Returns list of dictionary dict's keys
d_values = d.values() #Returns list of dictionary dict's values
#set to list
words = "Blah", "Hello"
words_list = list(words)
#List to set
fruit = ['banana', 'orange', 'pineapple']
fruit_set = set(fruit)
#Test cases
>>> select_odds([24,30,44,55,12])
[55]
>>> select_odds([24,30,44,55,12,3,5,6])
[55, 3, 5]
>>>
def select_odds(listA):
odd_list = []
for number in listA:
if number%2 != 0:
odd_list.append(number)
return odd_list
#Test cases
>>> select_unique_values([2,2,2,2,3,3,1,2,6,7,8,9,9,10])
[1, 2, 3, 6, 7, 8, 9, 10]
>>> select_unique_values(['one','two','one','two','three','one'])
['three', 'two', 'one']
def select_unique_values(listA):
return list(set(listA))
#Test cases
d = {'a': 3, 'b': 4,'c':5}
>>> sum_values(d)
12
>>> d = {'a': 3, 'b': 4,'c':50,'d':1}
>>> get_max_min(d)
(50, 1)
>>> get_max_min_dict(d)
{'max': 50, 'min': 1}
use max() and min()
def get_max_min(dictionary):
maximum = max(d.values())
minimum = min(d.values())
return maximum,minimum
def get_max_min_dict(dictionary):
maximum = max(d.values())
minimum = min(d.values())
return {'max':maximum,'min':minimum}