LoginSignup
0
0

More than 3 years have passed since last update.

04. 元素記号

Last updated at Posted at 2019-11-29

04. 元素記号

"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.

Go

package main

import (
    "fmt"
    "strings"
)

func main() {
    var src = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.";
    var dw = map[int]bool{1: true, 5: true, 6: true, 7: true, 8: true, 9: true, 15: true, 16: true, 19: true}; //  1文字の単語番号
    var res map[string]int = map[string]int{};

    //  単語に分割
    words := strings.Split(src, " ")
    for i, word := range words {
        idx := i + 1

        //  配列の exists的関数がなさそうなので Map を使用...
        if dw[idx] {
            //  1文字を map へ保存
            res[word[0:1]] = idx
        } else {
            //  2文字を map へ保存
            res[word[0:2]] = idx
        }
    }

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

python

# -*- coding: utf-8 -*-
src = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
dw = [1, 5, 6, 7, 8, 9, 15, 16, 19]  # 1文字の単語番号
res = {}

#   単語に分割
words = src.split(" ")
for i in range(len(words)):
    #   単語番号
    idx = i + 1

    #   1文字の単語番号の場合
    if idx in dw:
        #   1文字を map へ保存
        res[words[i][0:1]] = idx
    else:
        #   2文字を map へ保存
        res[words[i][0:2]] = idx

#   結果を表示
print(res)

Javascript

var src = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
var dw = [1, 5, 6, 7, 8, 9, 15, 16, 19];    //  1文字の単語番号
var res = new Map();

//  単語を空白で分割し単語数処理
var words = src.split(' ');
for (var i = 0; i < words.length; i++) {
    //  単語番号
    var idx = i+1;

    //  1文字の単語指定の場合 (ES2017)
    if (dw.includes(i+1)) {
        //  1文字を map へ保存
        res.set(words[i].substring(0,1),idx);
    }
    else {
        //  2文字を map へ保存
        res.set(words[i].substring(0,2),idx);
    }
}

//  結果表示
console.log(res);

まとめ

if文で or を書くのがイマイチかと思い 1文字の単語番号をまとめてみた。
Goの配列などの存在チェックがイマイチ?。

次の「05. n-gram」 は問題のの意味がよくわからない、まずは問題の理解から初めて見る。

他の人のを確認したら Map の内容が [文字 => 単語番号] と逆だったため修正しました。

その他

もともと、C言語やPHPが長いので 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