PythonStructures
From
Third part of PythonMaterial.
list
""" Show list operations """ import sys print "Size of a list:", sys.getsizeof([]), sys.getsizeof([1, 2, 3, 4, 5]), print sys.getsizeof([1, 2, 3, 4, 'this is much bigger']) print print "Constants:", [1, 2, 3, 'a'] l = [1, 2, 2, 3] print "Operators:", l + ['a', 'b'], l * 2, l[1] print "Slicing:", l[1:3], l[2:], l[-1:], l[:-2], [1, 2, 3, 4, 5, 6, 7][::2] print "Functions:", len(l), max(l), min(l), l.index(2), l.count(2) del l[2] print "Removed 3:", l l += [3, 4, 5] print "Added some:", l l.append(6) print "Added more:", l l.extend([7, 8, 9]) print "Even more:", l del l[:2] print "Removed start:", l del l[-4:] print "Removed tail:", l print "Boolean:", l < [4], l == [3, 3, 4, 5] print "Loop", for v in l: print v * 2, print l[:2] = [1, 2, 3] print "Overwrite:", l, l.reverse() print l l.reverse() l.insert(3, 16) print "Insert:", l l.sort() print "Sorted:", l, sorted("Me and my house alone!".split(), key=str.lower) l.remove(16) print "Removed:", l print "Pop:", l.pop(), l, l.pop(0), l
- A vector like (1, 5) is an immutable list.
Assignment |
---|
1 Write a function that returns a list with every element multiplied with a given value. The first argument is the list the second the multiplier. Try it out with some test cases. |
2 When the first argument was a variable the contents should be unaltered after the function. Try it with the first argument a vector that cannot be altered. |
3 Try the function with a string as the first argument. And with a numerical list and another list in the second argument. |
4 Write a function that returns the 4 highest values in a list ordered with the lowest of them first till the highest last. |
5 Remove the key=str.lower argument from the example code and run it again. The ordering is different now. |
string
Strings have a second life as list of single characters.
""" Show list operations on strings """ l = "abcdef" print "Operators:", l[1], l[-3:], l[::2] print "Iterate string:", for c in "abcdef": print c * 2, print print "Zipping:", for c in zip(xrange(5), "abcdefgh"): print c, print print "Mutable strings:", l = [] l += "abc" print l, l += "efg" l[2] += "d" print l, "".join(l) print "Sorting:", l = [] l += "edabc" l += ["fg"] l.sort() print l, l.sort(reverse=True) print l
Assignment |
---|
1 Write a function that writes a string with each character on a separate line. |
2 Show a '!' after each capital letter and '#' after each numeric token and '.' after each space. |
3 Write a function that get's a string and when it is enclosed with " or ' quotes return the normal string. |
4 Alter to function to replace two " tokens with a single one or when it was enclosed in ' replace two tokens with a single one. |
5 Return an integer value when the argument was not enclosed in quotes and contains only numeric tokens or starts with a '-' token. Also show the type of the result. |
6 Return a float value when the string also contained a single 'e' or '.' or '+'/'-' after the 'e' token. |
set
""" Show set operations """ s = set([1, 2, 5]) t = set([1, 3, 5]) print "Constants:", s, t, "length", len(s) print "Operators:", print s | t, # s.union(t) print s & t, # s.intersection(t) print s - t, # s.difference(t) print s ^ t # s.symmetric_difference(t) print "Tests:", 2 in s, 5 not in s, print s.isdisjoint([4, 6, 2]), # True is there are no elements in common print s <= (s & frozenset(xrange(4))), s.issubset(xrange(6)), print s | t > set(xrange(4)) - set(xrange(1)) # (s | t).issuperset(o) s |= frozenset([6, 7]) # s.update([6,7]) s &= frozenset(xrange(7)) # s.intersection_update(xrange(7)) s ^= frozenset(xrange(9)) # s.symmetric_difference_update(xrange(9)) s -= frozenset([8]) # s.difference_update([8]) print "Change operators:", s s.add(5) s.remove(0) s.discard(0) print "Set mutations:", s, s.pop(), s s.clear()
A lot of the operators on sets also have set method alternatives.
Assignment |
---|
1 Fill a set with names of persons. Add a name twice and show that this name is only once in the set. |
2 Make a second set with names and show a list of persons in both sets and persons only in the second set. |
3 Show the persons that are only in one set and not in both. |
4 Remove from the set the person with the highest and the lowest sorted name. |
dict
""" Show usage of the dict type """ a = {1: 'this', 2: 'is'} a[3] = "no" a[4] = "list" b = dict(another=3, value=4) c = dict([(3, 'different'), (4, 'value')]) d = dict.fromkeys(xrange(1, 5), "a") print "Constants:", a, "length", len(a), b, c, d print "Keys:", for v in a: # a.iter() or a.iterkeys() or a.keys() print str(v) + ':' + a[v], print print "Values:", for v in a.itervalues(): # a.values() is possible but less efficient print v, print a[3] = "a" print "Items:", for k, v in a.iteritems(): # a.items() print str(k) + ':' + v, print del a[1] print "Removed:", a, a.get(1, "something") print "Tests:", 'another' in b, 1 not in a print "Dict mutation:", a.pop(3), a.popitem(), a.setdefault(4, ""), a a.clear() b.update(added=5, too=6) b.update([('another', 2)]) print "Update:", b, sorted(b)
Assignment |
---|
1 Create a dictionary with persons and a number. For example the estimated number of times you met. |
2 Write a function that add one to a person in the dictionary when already there or adds the persons when 1 when not in the dictionary. |
3 Show the persons on the dictionary but skip the persons you met less then 5 times. Now show them alphabetically ordered. |
4 Show the list ordered by the number of times you met with the highest times first. |