2013年3月6日水曜日

開発環境

『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2)の6章(ハッシュ)、6.6(練習問題)2を解いてみる。

その他参考書籍

2.

コード(BBEdit)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';

my %count = ();
while (1) {
    chomp( my $word = <STDIN> );
    last if $word =~ /^\s*$/;
    $count{$word} += 1;
}
print map {"$_ $count{$_}回\n"} sort keys %count;

入出力結果(Terminal)

$ ./sample.pl
fred
barney
fred
dino
wilma
fred

barney 1回
dino 1回
fred 3回
wilma 1回
$

ちなみにJavaScriptの場合。

コード(BBEdit)

var count = {},
    words = [],
    word = "",
    result = "";
while (true) {
    word = prompt("単語を入力(空白で終了)","");
    if (/^\s*$/.test(word)) {
        break;
    }
    if (words.indexOf(word) === -1) {
        words.push(word);
        count[word] = 1;
    } else {
        count[word] += 1;
    }
}
words.sort();
for (i = 0, max = words.length; i < max; i += 1) {
    result += words[i] + " " + count[words[i]] + "回\n";
}
$('#pre0').text(result);



pythonの場合。

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

import re

count = {}
while True:
    word = input("単語: ")
    if re.search(r"^\s*$", word):
        break
    if word in count:
        count[word] += 1
    else:
        count[word] = 1

for x in sorted(count.keys()):
    print("{0} {1}回".format(x, count[x]))

入出力結果(Terminal)

$ ./sample.py
単語: fred
単語: barney
単語: fred
単語: dino
単語: wilma
単語: fred
単語: 
barney 1回
dino 1回
fred 3回
wilma 1回
$

0 コメント:

コメントを投稿