K
Koncept
Howdie Python folks! I am very new to Python ( 3rd day now ) and it has
already earned its place as my fav. language to work in. I hope to
continue, and I really would appreciate some good resources if anybody
would care to contribute.
My current head-scratcher concerns something I can do in Perl which I
would like to have duplicated for Python. I have noticed that it is not
possible to increment an unset value in Python, so I would like to know
how to duplicate the following bit of code using Python dictionaries.
#!/usr/bin/perl
# Parse comma delimited lines and create a final frequency hash
# Real example would read a file line by line
my %dict = {};
my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" );
foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); }
foreach( sort byKeys keys %dict ) {
print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n"
if $dict{ $_ } =~ /\d+/g;
}
sub byKeys { $dict{$b} <=> $dict{$a} }
__DATA__
Results:
Key: 5 Frequency: *****
Key: 4 Frequency: ****
Key: 3 Frequency: ***
Key: 2 Frequency: **
Key: 1 Frequency: *
already earned its place as my fav. language to work in. I hope to
continue, and I really would appreciate some good resources if anybody
would care to contribute.
My current head-scratcher concerns something I can do in Perl which I
would like to have duplicated for Python. I have noticed that it is not
possible to increment an unset value in Python, so I would like to know
how to duplicate the following bit of code using Python dictionaries.
#!/usr/bin/perl
# Parse comma delimited lines and create a final frequency hash
# Real example would read a file line by line
my %dict = {};
my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" );
foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); }
foreach( sort byKeys keys %dict ) {
print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n"
if $dict{ $_ } =~ /\d+/g;
}
sub byKeys { $dict{$b} <=> $dict{$a} }
__DATA__
Results:
Key: 5 Frequency: *****
Key: 4 Frequency: ****
Key: 3 Frequency: ***
Key: 2 Frequency: **
Key: 1 Frequency: *