Problem 1:
Sum the even numbers for the first n fibonacci numbers
Solution:
def fib(k):
"""Compute kth fibonacci number.
>>> fib(1)
0
>>> fib(2)
1
>>> fib(11)
55
"""
def recursive_fib(prev, curr, k):
if k - 1 == 0:
return curr
else:
return recursive_fib(curr, prev + curr, k - 1)
return recursive_fib(1, 0, k)
def iseven(n):
if n % 2 == 0:
return True
def sum_even_fibs(n):
"""Sum the first even fibonacci numbers
>>> sum_even_fibs(11)
44
"""
return sum(filter(iseven, map(fib, range(1, n + 1))))
def sum_even_fibs_gen(n):
"""Sum the first even fibonacci numbers
>>> sum_even_fibs_gen(11)
44
"""
return sum(fib(k) for k in range(1, n+1) if fib(k) % 2 == 0)
Problem 2:
List the letters in the acronym for a name, which includes the first letter of each capitalized word.
Solution:
def first(s):
return s[0]
def iscap(s):
return len(s) > 0 and s[0].isupper()
def acronym(name):
"""Return a tuple of the letters that form the acronym for name.
>>> acronym('University of California Berkeley')
('U', 'C', 'B')
"""
return tuple(map(first, filter(iscap,name.split())))
def acronym_gen(name):
"""Return a tuple of the letters that form the acronym for name.
>>> acronym_gen('University of California Berkeley')
('U', 'C', 'B')
"""
return tuple(w[0] for w in name.split() if iscap(w))
Functions fib
, acronym
and sum_even_fibs
are written in functional paradigm and tested.
Functions acronym_gen
and sum_even_fibs_gen
are written in imperative paradigm and tested.
My question:
After using predefined functions split
filter
map
in above 5 user defined functions, are the aforementioned paradigms being implemented correctly? If no, please let me know of the improvements.
sum_even_fibs_gen()
andacronym_gen()
are both perfectly valid functional programming, as each consists of a single expression with no side effects. I would consider them to be syntactically clearer expressions of the same goal assum_even_fibs()
andacronym()
. – 200_success♦ yesterdayw
inacronym_gen
is changing within an activation record. similarlyk
insum_even_fibs_gen
. – overexchange yesterdayw
refers to each of the words "simultaneously", but no mutation is occurring. That's allowable in FP. The generator is justmap()
with a different syntax. – 200_success♦ yesterdayw
would be pointing to new object every time. But if this programming style is moved to 'C' thenw
would be a memory area where the state of memory would change. – overexchange yesterday