0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文系学生のプログラミング学習11日目ーPython パンデジタル数判定ー

Posted at

今日はPythonを使ってパンデジタル数の判定をするコードを書きました。
パンデジタル数とは、自然数の内 n 進法において0から n − 1 までの全ての数字を少なくとも1つ使って表される数のことです。(出典:Wikipedia)
今回は少し変更して、五桁なら1~5までの数字がすべて使われていたら真、使われていなかったら偽というようにしたいと思います。
例えば、
12345なら真、12234なら偽となります。

Forループによるパンデジタル判定

def is_pandigital(num):
	num_list = split_into_digits(num)
	y = [x for x in range(1, len(num_list)+1)]
	true = 0
	for i in y:
		if i in num_list:
			true += 1
	if true == len(num_list):
		return(True)
	else:
		return(False)

リストyに3桁なら1~3、5桁なら1~5までの数字を入れます。
for文とif文ではリストyのそれぞれの要素がすべて、num_listに含まれているか確認し、含まれていれば変数trueに1足します。
最終的にtrueの値がnum_listのlengthと同じになっていれば真と判定します。
これでもしっかり判定されるのですが、コードが長く読みづらいので、先日学習したlistcomprehensionを使って書いてみました。

List Comprehensionによるパンデジタル判定

def is_pandigital(num):
	num_list = split_into_digits(num)
	y = [x for x in range(1, len(num_list)+1)]
	return(all([i in num_list for i in y]))

たった4行で済みました。

[i in num_list for i in y]

この部分はリストyのそれぞれの値がnum_listに含まれていればTrue、含まれていなければFalseを返します。
True or Falseのリストが出来るので、それをall()で1つにするときちんと判定されます。

最近はコードをいかに短く分かりやすく書くかというのを少し意識しています。
List Comprehensionを使うと大幅にコードが短縮されるのでとても便利です。

0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?