预计阅读本页时间:-
Coding Alternatives
Interestingly, we can also use Python’s if/else ternary expression (described in Chapter 12) to save some code real-estate here. We can also generalize for any summable type (which is easier if we assume at least one item in the input, as we did in Chapter 18’s minimum value example) and use Python 3.0’s extended sequence assignment to make the first/rest unpacking simpler (as covered in Chapter 11):
def mysum(L):
return 0 if not L else L[0] + mysum(L[1:]) # Use ternary expression
def mysum(L):
return L[0] if len(L) == 1 else L[0] + mysum(L[1:]) # Any type, assume one
def mysum(L):
first, *rest = L
return first if not rest else first + mysum(rest) # Use 3.0 ext seq assign
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
The latter two of these fail for empty lists but allow for sequences of any object type that supports +, not just numbers:
>>> mysum([1]) # mysum([]) fails in last 2
1
>>> mysum([1, 2, 3, 4, 5])
15
>>> mysum(('s', 'p', 'a', 'm')) # But various types now work
'spam'
>>> mysum(['spam', 'ham', 'eggs'])
'spamhameggs'
If you study these three variants, you’ll find that the latter two also work on a single string argument (e.g., mysum ('spam')), because strings are sequences of one-character strings; the third variant works on arbitary iterables, including open input files, but the others do not because they index; and the function header def mysum(first, * rest), although similar to the third variant, wouldn’t work at all, because it expects individual arguments, not a single iterable.
Keep in mind that recursion can be direct, as in the examples so far, or indirect, as in the following (a function that calls another function, which calls back to its caller). The net effect is the same, though there are two function calls at each level instead of one:
>>> def mysum(L):
... if not L: return 0
... return nonempty(L) # Call a function that calls me
...
>>> def nonempty(L):
... return L[0] + mysum(L[1:]) # Indirectly recursive
...
>>> mysum([1.1, 2.2, 3.3, 4.4])
11.0