0
1

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 1 year has passed since last update.

Pythonで各桁の和を求める

Last updated at Posted at 2023-04-27

結論

※shiracamus様からのご指摘より、こちらのコードが簡潔でした。ありがとうございます。

sumOfDigits.py
ans = sum(map(int, str(n))

自分が考えたコード

sumOfDigits1.py
ans = sum(list(map(int, list(str(n)))))

説明

list関数

Pythonのリスト関数は、他のデータ型をリストに変換する。特に文字列を渡したとき、文字列を分割して1文字ごとの文字列リストに変換する。

注意:リスト関数の引数は、イテラブルオブジェクトをとる。例えば range, リスト, タプル, 集合, 辞書, 文字列である。

list.py
list('444')
list('exe')

#実行結果
['4', '4', '4']
['e', 'x', 'e']

これは、各桁を分離するのに使用する。

map関数

公式ドキュメントより
map(function, iterable)
function を iterable の全ての要素に適用して結果を生成 (yield) するイテレータを返します。

要はiterableなobjectに対し、functionで操作したものを返すということ。

注意:map関数の返り値は、map関数で操作されたものではなく、mapオブジェクトである。ここでは、list化しておく。

map.py
a = [0,1,2]
list(map(str, a))

#実行結果
['0', '1', '2']

これにより、先の操作で分離した各桁をint型に変換できる。

まとめ

sumOfDigits1.py
n = str(n)
a = list(map(int,list(n)))
ans = sum(a)
  • str関数でnを文字列化
  • list関数で各桁が文字列で分離したリストを、整数型に変換
  • sum関数でリストの合計値を計算
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?