Online Book Reader

Home Category

Learning Python - Mark Lutz [590]

By Root 1937 0
effect with the sorted built-in, too:>>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7}

>>> D

{'f': 6, 'c': 3, 'a': 1, 'g': 7, 'e': 5, 'd': 4, 'b': 2}

>>>

>>> keys = list(D.keys()) # list() required in 3.0, not in 2.6

>>> keys.sort()

>>> for key in keys:

... print(key, '=>', D[key])

...

a => 1

b => 2

c => 3

d => 4

e => 5

f => 6

g => 7

>>> for key in sorted(D): # Better, in more recent Pythons

... print(key, '=>', D[key])

Program logic alternatives. Here’s some sample code for the solutions. For step e, assign the result of 2 ** X to a variable outside the loops of steps a and b, and use it inside the loop. Your results may vary a bit; this exercise is mostly designed to get you playing with code alternatives, so anything reasonable gets full credit:# a

L = [1, 2, 4, 8, 16, 32, 64]

X = 5

i = 0

while i < len(L):

if 2 ** X == L[i]:

print('at index', i)

break

i += 1

else:

print(X, 'not found')

# b

L = [1, 2, 4, 8, 16, 32, 64]

X = 5

for p in L:

if (2 ** X) == p:

print((2 ** X), 'was found at', L.index(p))

break

else:

print(X, 'not found')

# c

L = [1, 2, 4, 8, 16, 32, 64]

X = 5

if (2 ** X) in L:

print((2 ** X), 'was found at', L.index(2 ** X))

else:

print(X, 'not found')

# d

X = 5

L = []

for i in range(7): L.append(2 ** i)

print(L)

if (2 ** X) in L:

print((2 ** X), 'was found at', L.index(2 ** X))

else:

print(X, 'not found')

# f

X = 5

L = list(map(lambda x: 2**x, range(7))) # or [2**x for x in range(7)]

print(L) # list() to print all in 3.0, not 2.6

if (2 ** X) in L:

print((2 ** X), 'was found at', L.index(2 ** X))

else:

print(X, 'not found')

Part IV, Functions

See Test Your Knowledge: Part IV Exercises in Chapter 20 for the exercises.

The basics. There’s not much to this one, but notice that using print (and hence your function) is technically a polymorphic operation, which does the right thing for each type of object:% python

>>> def func(x): print(x)

...

>>> func("spam")

spam

>>> func(42)

42

>>> func([1, 2, 3])

[1, 2, 3]

>>> func({'food': 'spam'})

{'food': 'spam'}

Arguments. Here’s a sample solution. Remember that you have to use print to see results in the test calls because a file isn’t the same as code typed interactively; Python doesn’t normally echo the results of expression statements in files:def adder(x, y):

return x + y

print(adder(2, 3))

print(adder('spam', 'eggs'))

print(adder(['a', 'b'], ['c', 'd']))

% python mod.py

5

spameggs

['a', 'b', 'c', 'd']

varargs. Two alternative adder functions are shown in the following file, adders.py. The hard part here is figuring out how to initialize an accumulator to an empty value of whatever type is passed in. The first solution uses manual type testing to look for an integer, and an empty slice of the first argument (assumed to be a sequence) if the argument is determined not to be an integer. The second solution uses the first argument to initialize and scan items 2 and beyond, much like one of the min function variants shown in Chapter 18.

The second solution is better. Both of these assume all arguments are of the same type, and neither works on dictionaries (as we saw in Part II, + doesn’t work on mixed types or dictionaries). You could add a type test and special code to allow dictionaries, too, but that’s extra credit.def adder1(*args):

print('adder1', end=' ')

if type(args[0]) == type(0): # Integer?

sum = 0 # Init to zero

else: # else sequence:

sum = args[0][:0] # Use empty slice of arg1

for arg in args:

sum = sum + arg

return sum

def adder2(*args):

print('adder2', end=' ')

sum = args[0] # Init to arg1

for next in args[1:]:

sum += next # Add items 2..N

return sum

for func in (adder1, adder2):

print(func(2, 3, 4))

print(func('spam', 'eggs', 'toast'))

print(func(['a', 'b'], ['c', 'd'], ['e', 'f']))

% python adders.py

adder1 9

adder1 spameggstoast

adder1 ['a', 'b', 'c', 'd', 'e', 'f']

adder2 9

adder2 spameggstoast

adder2 ['a', 'b', 'c', 'd', 'e', 'f']

Keywords. Here is my solution to the

Return Main Page Previous Page Next Page

®Online Book Reader