Clarification on what the author meant (Learning Python 5th Edition) -


def mysum(l):     return 0 if not l else l[0] + mysum(l[1:])  def mysum(l):    return l[0] if len(l) == 1 else l[0] + mysum(l[1:])  def mysum(l):     first, *rest = l     return first if not rest else first + mysum(rest) 
  • the latter 2 work on single string argument e.g mysum('spam') because strings sequences of one-character strings.
  • the third variant works on arbitrary iterables, including open input files mysum(open(name)), others not because use index.
  • the function header def mysum(first *rest), although similar third variant, because expects individual arguments not single iterable.

the author seems implying variant (first, *rest) input arguments wouldn't work files after experimenting it, found work.

# code tried: def mysum(first, *rest):      return first if not rest else first + mysum(*rest) 

mysum(*open("script1.py")) works fine.

i think mysum(open("script1.py")) won't work because python see first = open("script1.py , rest = [] means it's gonna give me <_io.textiowrapper name='script1.py' mode='r' encoding='cp1252'> because not [] true.

the author wants function takes iterable (e.g. list, tuple, etc) input , returns sum, e.g. this:

mysum(open("script1.py")) 

when write

mysum(*open("script1.py")) 

this equivalent

f = open("script1.py").readlines() mysum(f[0], f[1], ..., f[n]) 

note here code not take interable input, instead takes several separate arguments which not author wanted.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -