Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8175329
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T22:44:36+00:00 2026-06-06T22:44:36+00:00

When working with generators you can only pull out items on a single pass.

  • 0

When working with generators you can only pull out items on a single pass. An alternative is to load the generator into an list and do multiple passes but this involves a hit on performance and memory allocation.

Can anyone think of a better way of computing the following metrics from a generator in a single pass. Ideally the code computes the count, sum, average, sd, max, min and any other stats you can think of.

UPDATE

Initial horrid code in this gist.
See the gist here: https://gist.github.com/3038746

Using the great suggestions from @larsmans here is the final solution I went with. Using the named tuple really helped.

import random
from math import sqrt
from collections import namedtuple

def stat(gen):
    """Returns the namedtuple Stat as below."""
    Stat = namedtuple('Stat', 'total, sum, avg, sd, max, min')
    it = iter(gen)

    x0 = next(it)
    mx = mn = s = x0
    s2 = x0*x0
    n = 1

    for x in it:
        mx = max(mx, x)
        mn = min(mn, x)
        s += x
        s2 += x*x
        n += 1

    return Stat(n, s, s/n, sqrt(s2/n - s*s/n/n), mx, mn)

def random_int_list(size=100, start=0, end=1000):
    return (random.randrange(start,end,1) for x in xrange(size))

if __name__ == '__main__':
    r = stat(random_int_list())
    print r  #Stat(total=100, sum=56295, avg=562, sd=294.82537204250247, max=994, min=10)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T22:44:37+00:00Added an answer on June 6, 2026 at 10:44 pm
    def statistics(it):
        """Returns number of elements, sum, max, min"""
    
        it = iter(it)
    
        x0 = next(it)
        maximum = minimum = total = x0
        n = 1
    
        for x in it:
            maximum = max(maximum, x)
            minimum = min(minimum, x)
            total += x
            n += 1
    
        return n, total, maximum, minimum
    

    Add other statistics as you please. Consider using a namedtuple when the number of statistics to compute grows large.

    If you want to get really fancy, you can build an OO hierarchy of statistics collectors (untested):

    class Summer(object):
        def __init__(self, x0=0):
            self.value = x0
    
        def add(self, x):
            self.value += x
    
    class SquareSummer(Summer):
        def add(self, x):
            super(SquareSummer, self).add(x ** 2)
    
    class Maxer(object):
        def __init__(self, x0):
            self.value = x0
    
        def add(self, x):
            self.value = max(self.value, x)
    
    # example usage: collect([Maxer, Summer], iterable)
    def collect(collectors, it):
        it = iter(it)
    
        x0 = next(it)
        collectors = [c(x0) for c in collectors]
    
        for x in it:
            for c in collectors:
                c.add(x)
    
        return [c.value for c in collectors]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am working on a load generator app using akka actors. The app worked
Working on my first Rails project, I used Ryan Bates' Nifty-Generators to create the
I was working with generator functions and private functions of a class. I am
I'm working on a random name generator to be used in a game I'm
I am working on my own Lorem Ipsum generator, with the added bonus of
I have been working on a LiftSuggest - an automatic Product Recommendations generator. Now,I
I working on a maze generator in C# which generates big mazes and then
I'm working on a quick captcha generator for a simple site I'm putting together,
I'm working on an application that uses a list to handle previous guesses from
For a visual studio generator, can cmake be told to generate a solution that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.