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

Home Posts Topics Members FAQ

obtaining multiple values from a function.

hello all,

If I have a function that loops over a few elements and is expected to
throw out a few tuples as the output, then what should I be using in
place of return ?
Shriphani Palakodety.

Sep 25 '07 #1
5 1415
Shriphani wrote:
If I have a function that loops over a few elements and is expected to
throw out a few tuples as the output, then what should I be using in
place of return ?
Use a generator and have it /yield/ rather than /return/ results:
>>def f(items):
.... for item in items:
.... yield item.isdigit(), item.isupper()
....
>>for result in f("AAA bbb 111".split()):
.... print result
....
(False, True)
(False, False)
(True, False)

This is a very memory-efficient approach, particularly if the input items
are created on the fly, e. g. read from a file one at a time.

Peter
Sep 25 '07 #2
Shriphani <sh********@gma il.comwrites:
If I have a function that loops over a few elements and is expected to
throw out a few tuples as the output, then what should I be using in
place of return ?
If it makes sense for the set of results to be returned all at once,
then return the object that collects them all together — a list of
tuples, for example.
If, instead, it makes sense for the results to be iterated over, you
can write a function that yields results one at a time, without
necessarily knowing in advance what the entire set will be::
>>def fib(max_result) :
... """ Yield numbers in the Fibonacci sequence
... to a maximum value of max_result. """
... prev_results = [0, 0]
... result = 1
... while result < max_result:
... yield result
... prev_results = [prev_results[1], result]
... result = sum(prev_result s)
...

The function, when called, will return a generator object that you can
either iterate over::
>>fib_generat or = fib(100)
for n in fib_generator:
... print n
...
1
1
2
3
5
8
13
21
34
55
89

or directly call its 'next' method to get one result at a time until
it raises a 'StopIteration' exception::
>>fib_generat or = fib(5)
fib_generator .next()
1
>>fib_generator .next()
1
>>fib_generator .next()
2
>>fib_generator .next()
3
>>fib_generator .next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

--
\ "I have one rule to live by: Don't make it worse." -- Hazel |
`\ Woodcock |
_o__) |
Ben Finney
Sep 25 '07 #3
Ben Finney <bi************ ****@benfinney. id.auwrites:

>
If, instead, it makes sense for the results to be iterated over, you
can write a function that yields results one at a time, without
necessarily knowing in advance what the entire set will be::
>>def fib(max_result) :
Going off on a tangent a bit, but I was idly considering the absence
of itertools.iredu ce the other day. A problem is that reduce gives a
single result, so it's not clear what ireduce would do (perhaps why
it's not there). One obvious candidate would be to give the whole
sequence of partial reductions. I'm not sure if this would be
generally useful, but it would give a succinct way to do the Fibonacci
sequence:

itertools.iredu ce(operator.add , itertools.count ())

Sep 25 '07 #4
On Tue, 2007-09-25 at 10:41 +0100, Paul Rudin wrote:
Going off on a tangent a bit, but I was idly considering the absence
of itertools.iredu ce the other day. A problem is that reduce gives a
single result, so it's not clear what ireduce would do (perhaps why
it's not there). One obvious candidate would be to give the whole
sequence of partial reductions. I'm not sure if this would be
generally useful, but it would give a succinct way to do the Fibonacci
sequence:

itertools.iredu ce(operator.add , itertools.count ())
Let's try it:
>>def ireduce(op, iterable, partial=0):
.... for nxt in iterable:
.... partial = op(partial, nxt)
.... yield partial
....
>>import operator
from itertools import islice, count

for x in islice(ireduce( operator.add, count()), 0, 10):
.... print x
....
0
1
3
6
10
15
21
28
36
45

That's not the Fibonacci sequence.

--
Carsten Haese
http://informixdb.sourceforge.net
Sep 25 '07 #5
Carsten Haese <ca*****@uniqsy s.comwrites:

...
That's not the Fibonacci sequence.
Bah, you're right of course, I should be more more careful before
posting these things.

Sep 25 '07 #6

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

Similar topics

66
4967
by: Darren Dale | last post by:
Hello, def test(data): i = ? This is the line I have trouble with if i==1: return data else: return data a,b,c,d = test()
11
2495
by: seannakasone | last post by:
Is there a way to get the callstack level in c++? for example, take the following code: void call3() { //callstack level would be 3 } void call2() { //callstack level would be 2 call3();
11
4053
by: John Nagle | last post by:
The Python SSL object offers two methods from obtaining the info from an SSL certificate, "server()" and "issuer()". The actual values in the certificate are a series of name/value pairs in ASN.1 binary format. But what "server()" and "issuer()" return are strings, with the pairs separated by "/". The documentation at "http://docs.python.org/lib/ssl-objects.html" says "Returns a string containing the ASN.1 distinguished name identifying...
1
1589
by: dmitrey | last post by:
hi all, howto check is function capable of obtaining **kwargs? i.e. I have some funcs like def myfunc(a,b,c,...):... some like def myfunc(a,b,c,...,*args):... some like
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,...
1
8356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
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...
0
7184
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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.