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?

【Python実践自作問題集】No.3 整数?実数?

Last updated at Posted at 2025-06-07

1. はじめに

この問題集は、Pythonの基礎を習得した後、次の段階へ進みたい人のサポートをすることが目的です。
また、競技プログラミングとは異なり、複雑なアルゴリズムの問題ではなく「可読性の最大化」に焦点を当てた問題が中心となります。

目次
前の問題:list/tuple問題の解消
次の問題:型に厳密なデータクラス1

2. 問題

Question
"""
No.3 整数?実数?

次の要件を満たすように、関数flointを完成させてください。

* 引数valueが0.0, 1.0のように整数として扱えるとき、0, 1のように整数を返す。
* 引数valueが0.5, -0.5のように整数でないとき、0.5, -0.5のようにそのまま値を返す。
"""


def floint(value: float) -> int | float:
    ...

3. 解答例

Answer
def floint(value: float) -> int | float:
    if value.is_integer():
        return int(value)
    else:
        return value
Answer(条件演算式ver)
def floint(value: float) -> int | float:
    return int(value) if value.is_integer() else value

4. 採点基準

  • 整数/実数の判定ができていること

5. 解説

5.1 整数/実数の判定

float型にはis_integerメソッドがあり、これを使用して整数/実数判定を行うことができます。

Pythonで数値が整数か小数かを判定 - note.nkmk.me

テストコード
import math


value = 0.0
assert floint(value) == value
assert isinstance(floint(value), int)

value = 1.0
assert floint(value) == value
assert isinstance(floint(value), int)

value = 0.5
assert floint(value) == value
assert isinstance(floint(value), float)

value = -0.5
assert floint(value) == value
assert isinstance(floint(value), float)

value = math.inf
assert floint(value) == value
assert isinstance(floint(value), float)

value = -math.inf
assert floint(value) == value
assert isinstance(floint(value), float)

value = math.nan
assert math.isnan(floint(value))
assert isinstance(floint(value), float)

Excelから数値を読み込んだときなど、整数で入力されていても実数として読み込まれてしまうことがあります。
このような場合にfloint関数を使うことで、整数値に戻すことができます。
更にstr関数で文字列へ変換する場合に0.0ではなく0と出力できるようになります。

print(str(0.0))
print(str(0.5))
print(str(floint(0.0)))
print(str(floint(0.5)))
実行結果
0.0
0.5
0
0.5
0
0
1

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?