Final Exam 2011 Problem 1

107 views
Skip to first unread message

Erwin Magnaye

unread,
Dec 12, 2012, 9:27:25 AM12/12/12
to csc-32...@googlegroups.com
How would you implement the reduce function using functional programming (using functions, recursion, if statements, but no loops)?
reduce (f,[a,b,c,d]) returns f(f(f(a,b),c),d)

def reduce(f,ls):
...

Erwin Magnaye

unread,
Dec 12, 2012, 9:42:39 AM12/12/12
to csc-32...@googlegroups.com

aya

unread,
Dec 12, 2012, 9:26:17 PM12/12/12
to csc-32...@googlegroups.com
here is my solution:

def reduce2(f, input):
    return reduce(lambda a, b: f(a, b), input)

Mustafa

unread,
Dec 12, 2012, 9:34:31 PM12/12/12
to csc-32...@googlegroups.com
Hmmmmm, i don't think you can do that. You can't use the function reduce when you are being asked to implement it. 
I think this is more fitting. 

For functional: 
def reduce(f,ls):
    out = f(ls[0],ls[1])
    ls.pop(0), ls.pop(0)
    
    def recurse(out):
         if(len(ls) == 1):
               out = f(out,ls[0])
               return out
          else: 
              out = f(out,ls.pop(0))
              return recurse(out)
     return recurse(out)
            


For Imperative:
def reduce(f,ls):
    out = f(ls[0],ls[1])
    ls.pop(0), ls.pop(0)
    for t in ls:
         out = f(out, t)
   return out

Mustafa

unread,
Dec 12, 2012, 9:34:58 PM12/12/12
to csc-32...@googlegroups.com
I'm sure there are better solutions. 

Wesley May

unread,
Dec 12, 2012, 9:36:28 PM12/12/12
to csc-32...@googlegroups.com
Hmmmm did you just implement reduce with reduce? XD

Mustafa

unread,
Dec 12, 2012, 9:38:04 PM12/12/12
to csc-32...@googlegroups.com
hahahahahah, i'll remember that for tomorrow. 

Vinh Hoang

unread,
Dec 12, 2012, 10:19:08 PM12/12/12
to csc-32...@googlegroups.com
This is mine

def reduce(f, ls):
    if len(ls) == 2:
        return f(ls[0], ls[1])
    elif len(ls) > 2:
        return reduce(f, [f(ls[0], ls[1])] + ls[2:])
    else:
        return None

Sheema Khan

unread,
Dec 12, 2012, 10:27:56 PM12/12/12
to csc-32...@googlegroups.com
Mine:

def helper(f,ans,ls):
    if len(ls) <  2: return f(ans,ls[0])
    return helper(f,f(ans,ls[0]),ls[1:])
                     
def reduce(f,ans,ls):
    ans = f(ls[0],ls[1])
    return helper(f, ans,ls[2:])

Sheema Khan

unread,
Dec 12, 2012, 10:28:49 PM12/12/12
to csc-32...@googlegroups.com
I assumed that I can only use if and not if-else statements

Vinh Hoang

unread,
Dec 12, 2012, 10:40:37 PM12/12/12
to csc-32...@googlegroups.com
I think you can... since it's trivial to modify if else to sequences of if

Wesley May

unread,
Dec 13, 2012, 12:26:27 AM12/13/12
to csc-32...@googlegroups.com
Agreed
Reply all
Reply to author
Forward
0 new messages