毎朝ちびちびCodewars。
Simple Fun #116: Prime String [6級] www.codewars.com
今日のお題:
""" The string is called prime if it cannot be constructed by concatenating some (more than one) equal strings together. For example, "abac" is prime, but "xyxy" is not("xyxy"="xy"+"xy"). Args: s (str): string Returns: bool: Given a string determine if it is prime or not. """
コード
me
def prime_string(s): ln = len(s) if ln > 1: for d in range(1, ln): q, m = divmod(ln, d) if m == 0 and s[0:d]*q == s: return False return True
- sが、ある部分文字列の繰り返しで合成されるとき、len(s)は、その部分文字列長の倍数なはずと考えた。
- len(s)を割り切れる数を探し、その文字数でスライスした部分文字列(をq倍したもの)と元の文字列sが 一致したら、sは合成文字列(Falseを返す)。
- "constructed by concatenating some (more than one) equal strings together" で more than one (1より大きい)と書かれており、部分文字列は2文字以上の想定で解いたらNGだった。NGだったテストケースを見ると 'cc' とか 'ggggg' が False(合成文字列である)判定されており、これがFalseになるには部分文字列は1文字もアリじゃないと成り立たない。
合格を貰うために、1文字の繰り返しもアリなようロジックを書き換えたが、more than one って言い方が1を含むのか否かが腑に落ちない。英語むずい(´・ε・̥ˋ๑)。
awesome
印象に残った他ユーザによるエレガントな解法。
def prime_string(s): return (s + s).find(s, 1) == len(s)
頑張って解いたつもりなのに、こうさらっと1行で済まされちゃうと、"自分センスなさすぎじゃね?!"って凹むにゃん ^^;;
文法、メソッドnote
変数名の英語
https://www.5ka9.com/2013/12/mathword.html
- 割る: divide
- 商, 余り: the quotient / remainder
- 倍数: multiple
- 約数: divisor
- 素数: prime number
str.find(sub[, start[, end]])
https://docs.python.org/ja/3/library/stdtypes.html?highlight=find#str.find
- 文字列のスライス str[start:end] に、部分文字列 subが含まれる場合に、最初の出現場所のインデックスを返す。
- subが含まれないなら -1 を返す。
divmod(a, b)
https://docs.python.org/ja/3/library/functions.html#divmod
- 商と剰余のペア (a // b, a % b) を返す。