Thursday, April 14, 2011

More programming woes.

I spent most of the day trying  to take 33 files that look like this:

0
0
0
2
5
11
5
20

...and so on, all the way to 1000 lines, and adding the numbers then dividing each number by the sum. This is somewhat easily accomplished in excel, but it is tedious and takes a prohibitively long time. So I thought, hey, I'll just write a program that will do the calculations on the original .txt files. I am learning python, afterall.

I know enough to know conceptually what needs to happen. I do not know enough to translate that into reality.

What I wrote yesterday about someone who knows what they're doing accomplishing this in 5 minutes, yep:

#!/usr/bin/perl -w
use strict;

die "please specify file on command line\n" unless scalar @ARGV > 0;
open READ, $ARGV[0] or die "could not read file $ARGV[0]\n";

my @data;
my $sum;
my $header = <READ>;
while (my $line = <READ>) {
    chomp $line;
    unless ($line =~ /^\d+$/) {
    warn "line $line does not contain a number, discarded...\n";
    next;
   }
    push (@data, $line);
    $sum += $line;
}

foreach my $num (@data) {
    print $num/$sum , "\n";
}



5 minutes. Maybe 7. That's in perl. Looks like a bunch of dollar signs and slashes to me too.

One day I will know something, though I'm sure even then satisfaction will remain just as illusory.

2 comments:

  1. ... fun.

    When I first saw the previous post, I thought my laptop was having a heart-attack. Now I know it's just you enjoying grad school life.
    I'm still jealous.

    ReplyDelete