473,625 Members | 3,318 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursion gotcha?

cnb
this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

it returns none.

def summa(xs):
if not xs:
0
else:
xs[0]+summa(xs[1:])
Traceback (most recent call last):
File "<pyshell#6 >", line 1, in <module>
summa([1,2,3,4,5])
File "<pyshell#5 >", line 5, in summa
xs[0]+summa(xs[1:])
File "<pyshell#5 >", line 5, in summa
xs[0]+summa(xs[1:])
File "<pyshell#5 >", line 5, in summa
xs[0]+summa(xs[1:])
File "<pyshell#5 >", line 5, in summa
xs[0]+summa(xs[1:])
File "<pyshell#5 >", line 5, in summa
xs[0]+summa(xs[1:])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Sep 14 '08 #1
5 1574
On Sep 14, 9:01*am, cnb <circularf...@y ahoo.sewrote:
def suma(xs, acc=0):
* * * * if len(xs) == 0:
* * * * * * * * acc
* * * * else:
* * * * * * * * suma(xs[1:], acc+xs[0])

it returns none.
Yep, that's because there is no "return" statement anywhere. Python
doesn't return expressions "by default", like functional languages do,
so where you say "suma(xs[1:], acc+xs[0])" this just calls itself and
returns nothing.

Try this:

def suma(xs, acc=0):
if len(xs) == 0:
return acc
else:
return suma(xs[1:], acc+xs[0])

print suma([1, 2, 3, 4, 5])

(prints 15)

Roman
Sep 14 '08 #2
On Sun, Sep 14, 2008 at 10:01 AM, cnb <ci**********@y ahoo.sewrote:
this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])
You're just missing the "return" statements?

def suma(xs, acc=0):
if len(xs) == 0:
return acc
else:
return suma(xs[1:], acc+xs[0])
Regards
Marco
--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
Sep 14 '08 #3
On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri
<ma************ @gmail.comwrote :
On Sun, Sep 14, 2008 at 10:01 AM, cnb <ci**********@y ahoo.sewrote:
>this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

You're just missing the "return" statements?

def suma(xs, acc=0):
if len(xs) == 0:
return acc
else:
return suma(xs[1:], acc+xs[0])

Besides: you can avoid the "acc" parameter:

def suma(xs):
if len(xs) == 0:
return 0
else:
return xs[0] + suma(xs[1:])

Regards
Marco
--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
Sep 14 '08 #4
On Sep 14, 9:44*am, "Marco Bizzarri" <marco.bizza... @gmail.comwrote :
On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri

<marco.bizza... @gmail.comwrote :
On Sun, Sep 14, 2008 at 10:01 AM, cnb <circularf...@y ahoo.sewrote:
this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.
def suma(xs, acc=0):
* * * *if len(xs) == 0:
* * * * * * * *acc
* * * *else:
* * * * * * * *suma(xs[1:], acc+xs[0])
You're just missing the "return" statements?
def suma(xs, acc=0):
* * * if len(xs) == 0:
* * * * * * *return acc
* * * else:
* * * * * * *return suma(xs[1:], acc+xs[0])

Besides: you can avoid the "acc" parameter:

def suma(xs):
* * if len(xs) == 0:
* * * * return 0
* * else:
* * * * return xs[0] + suma(xs[1:])
I think the OP tried to make it tail-recursive, which of course has no
benefit in Python. In fact it looks like a Scheme implementation of
sum translated literally to Python.

In Python this algorithm is expressed naturally as:

def suma(xs):
acc = 0
for x in xs:
acc += x
return acc

--
Arnaud

Sep 14 '08 #5
cnb wrote:
this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

it returns none.
Without return statement, the only recursive solution is a lambda expr :
>>suma = lambda xs : xs[0]+suma(xs[1:]) if xs else 0
>>suma(range(10 1))
5050

Note that suma(xs[1:]) implies copying the remainder of xs, what in turn makes
the time grow quadratically with the length of xs. So instead of passing a
superfluous acc second variable, you could pass an index into the list, eg

def suma(xs,pos=0) :
if pos>=len(xs) :
return 0
else :
return xs[pos]+suma(xs,pos+1)

Cheers, BB

Sep 14 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3414
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this:
12
2749
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted in modern day applications. Should we readily use it when we can or only when absolutly forced to use it?
43
4146
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
2
1562
by: Csaba Gabor | last post by:
I suppose spring fever has hit at alt.math.undergrad since I didn't get any rise from them when I posted this a week ago, so I am reposting this to some of my favorite programming groups: I'm looking for problems that have double (or more) recursion, where the split is not clean (ie. where there may be overlap). Let's call this overlapped recursion, where the
75
5597
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
18
3713
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated!
3
2119
by: Tyrone Slothrop | last post by:
I have created a script which recurses a display of directories like so: <? $dir = "/path/to/base/directory"; function scan_dir_recurse ($dir,$tab) { global $fileArr; $tab++; if ($tab 4) { exit ("Tab length exceeded."); }
20
2981
by: athar.mirchi | last post by:
..plz define it.
35
4712
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
8256
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8694
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6118
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1500
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.