2013年1月5日土曜日

開発環境

『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の14章(文字列処理とソート)、14.5(練習問題)2を解いてみる。

その他参考書籍

2.

コード(BBEdit)

sample.pl

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

my %last_name = qw{
  fred flintstone Wilma flintstone Barney Rubble
  betty rubble Bamm-Bamm Rubble PEBBLES FLINTSTONE};

for(sort{
    "\L$last_name{$a}" cmp "\L$last_name{$b}" or
    "\L$a" cmp "\L$b"
  } keys %last_name){
  print "$_ $last_name{$_}\n";
}

入出力結果(Terminal)

$ ./sample.pl
fred flintstone
PEBBLES FLINTSTONE
Wilma flintstone
Bamm-Bamm Rubble
Barney Rubble
betty rubble
$

ちなみにJavaScriptの場合。

コード(BBEdit)


var result = "";
var last_name = [["fred","flintstone"], ["Wilma","flintstone"], ["Barney","Rubble"],
  ["betty","rubble"], ["Bamm-Bamm","Rubble"], ["PEBBLES","FLINTSTONE"]];
last_name.sort(function(a, b){
  if(a[1].toUpperCase() !== b[1].toUpperCase()){
    return a[1].toUpperCase() > b[1].toUpperCase();
  } else {
    return a[0].toUpperCase() > b[0].toUpperCase();
  }
  return 0;
});
for(var i = 0; i < last_name.length; i++){
  result += last_name[i][0] + " " + last_name[i][1] + "\n";
}
$('#pre0').text(result);




pythonの場合。

sample.py

コード(BBEdit)

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

last_name = [("fred","flintstone"), ("Wilma","flintstone"),
  ("Barney","Rubble"), ("betty","rubble"),
  ("Bamm-Bamm","Rubble"), ("PEBBLES","FLINTSTONE")]

last_name.sort(key=lambda x:(x[1].upper(), x[0].upper()))
for f, l in last_name:
    print(f, l)

入出力結果(Terminal)

$ ./sample.py
fred flintstone
PEBBLES FLINTSTONE
Wilma flintstone
Bamm-Bamm Rubble
Barney Rubble
betty rubble
$

0 コメント:

コメントを投稿