LoginSignup
0
0

More than 3 years have passed since last update.

03. 円周率

Last updated at Posted at 2019-11-28

03. 円周率

"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.

Go

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    var src string = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
    var wlen []int
    rex := regexp.MustCompile("([a-zA-Z]+)")

    //  単語に分割
    words := strings.Split(src, " ")
    for _, word := range words {
        //  アルファベットのみを抽出
        match := rex.FindStringSubmatch(word)

        //  アルファベットの文字数を保存
        wlen = append(wlen, len(match[1]))
    }

    //  結果を表示
    fmt.Println(wlen)
}

python

# -*- coding: utf-8 -*-
import re

src = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
wlen = []

#   正規表現パターン定義(アルファベットのみ)
pattern = re.compile('([a-zA-Z]+)')

#   単語に分割
words = src.split(" ")
for word in words:
    #   アルファベットのみ抽出
    result = re.search(pattern, word).group()

    #   アルファベットの文字数を保存
    wlen.append(len(result))

#   結果を表示
print(wlen)

Javascript

var src = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
var wlen = [];

//  ループ版
var words = src.split(' ');
for (var i = 0; i < words.length; i++) {
    val = words[i].match(/[a-zA-Z]+/);
    wlen.push(val[0].length);
}
console.log(wlen);


//  forEach 版
var wlen = [];
src.split(' ').forEach(function (value) {
    this.push(value.match(/[a-zA-Z]+/)[0].length);
}, wlen)

console.log(wlen);

まとめ

以外と簡単と作ったが、他の人の結果を見て間違ってることに気づいた。 "." や "," は抜くのか。
アルファベット判別は少し悩んだが、正規表現で対応。Goの正規表現処理は遅いんだったかな?。

問題の円周率の意味が解った時は、なんとなく嬉しかった。w

トップ

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0