Detect Floating Point Number
・問題
You are given a string .
Your task is to verify that is a floating point number.
In this task, a valid float number must satisfy all of the following requirements:
Number can start with +
, -
or .
symbol.
For example:
+4.50
-1.0
.5
-.7
+.4
-+4.5
Number must contain at least decimal value.
For example:
12.
12.0
Number must have exactly one .
symbol.
Number must not give any exceptions when converted using .
Input Format
The first line contains an integer , the number of test cases.
The next line(s) contains a string .
Constraints
Output Format
Output True or False for each test case.
Sample Input 0
4
4.0O0
-1.00
+4.54
SomeRandomStuff
Sample Output 0
False
True
True
False
Explanation 0
: O is not a digit.
: is valid.
: is valid.
SomeRandomStuff: is not a number.
・コメント
標準入力から入ったものが、浮動小数点表示かどうかを判別するプログラムを書く問題。
reモジュールをインポートするところからスタートする。reとは正規表現操作ということらしい....(良く分からない)
どうも、入力から得られた文字列に一致するところがないかなどを調べるときに使うらしい。
reにはmatch()やsearch()など様々なメソッドが存在するが、今回はmatch()を用いる。
bool(re.match(r'条件',a[n]))
という形ならば、条件を満たすものがa[n]の先頭にあればTrueを返すし、満たしていなければ、Falseを返すという塩梅で用いる。
一見難しくなさそうだが、この条件の書き方が何とも難解である。
以下の表を参考にして議論を進めることにしよう。
正規表現パターン | 意味 | 例 | ヒット例 | ヒットしない例 |
---|---|---|---|---|
. | 任意一文字 | c.t | cat, cut | cast |
^ | 先頭 | ^get | getName | mygetName |
$ | 文字列末尾 | foo$ | foo, barfoo | foobar |
* | 0回以上反復 | ab* | a,ab,abbb | bb |
+ | 1回以上反復 | ab+ | ab,abbb | a,bb |
? | 0or1回登場 | ab? | a,ab | abb |
{m} | m回反復 | a{3} | aaa | aa,aaaa |
{m,n} | m~n回反復 | a{3,5} | aaa,aaaa,aaaaa | aa,aaaaaa |
*?, +*, ??, {m,n}? | non-greedyマッチ 最も小さくマッチする |
- | - | - |
[ ] | 集合 | [aiu] | a,i,u | e,o |
[ - ] | 集合:範囲指定 | [a-z] | a,i,u,w,z | 1,!,$ |
[a-m0-9] | a,g,m,0,5 | !,$ | ||
[^] | 集合:否定 | [^a-z] | 1,!,$ | a,i,u,q,z |
| | 和集合 | a|b | a,b | c,d |
( ) | グループ化 反復をグループに適用 |
(abc){2} | abcabc | abc |
\ | エスケープ 特殊文字直前に置く |
- | - | - |
今回は浮動小数点表示かどうかを判断する問題であり、問題文には浮動小数点表示について以下のようなことが書かれている。
まず、先頭に+か-がある場合とない場合があり、その次に0~9の数字が0個以上存在し、かつその次に小数点があり、その後に、0~9の数字が1個以上存在する。
そこで、先ほどのソースコードに戻ってみよう。すると、re.match()の中に
[-+]?[0-9]*\.[0-9]+$
というものが含まれているがこれを分割して考えてみると、
[-+]? : -または+が0回または1回出現する
[0-9]* : 0~9の数字が0回以上出現する
\. : 小数点(\が無ければ、上表一番上のように認識されてしまう)
[0-9]+ : 0~9の数字が1回以上出現する
$ : 終了
となることが、表より見て取れる。
・URL
https://www.hackerrank.com/challenges/introduction-to-regex/problem