Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion Efficient processing of large nuumeric data file
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
bearophileh...@lycos.com  
View profile  
 More options Jan 18 2008, 7:37 pm
Newsgroups: comp.lang.python
From: bearophileH...@lycos.com
Date: Fri, 18 Jan 2008 16:37:49 -0800 (PST)
Local: Fri, Jan 18 2008 7:37 pm
Subject: Re: Efficient processing of large nuumeric data file
Matt:

> from collections import defaultdict

> def get_hist(file_name):
>     hist = defaultdict(int)
>     f = open(filename,"r")
>     for line in f:
>         vals = line.split()
>         val = int(vals[0])
>         try: # don't look to see if you will cause an error,
>              # just cause it and then deal with it
>             cnt = int(vals[1])
>         except IndexError:
>             cnt = 1
>         hist[val] += cnt
>     return hist

But usually in tight loops exceptions slow down the Python code, so
this is quite faster (2.5 times faster with Psyco, about 2 times
without, with  about 30% of lines with a space in it):

import psyco
from collections import defaultdict

def get_hist(file_name):
    hist = defaultdict(int)

    for line in open(file_name):
        if " " in line:
            pair = line.split()
            hist[int(pair[0])] += int(pair[1])
        else:
            hist[int(line)] += 1

    return hist

psyco.bind(get_hist)

It doesn't work if lines may contain spurious spaces...

Bye,
bearophile


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.