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

【Python】ソートされた二乗配列

Last updated at Posted at 2023-08-05

作るもの

与えられた整数の配列を二乗して、それらの値を昇順でソートした新しい配列を返す関数。

実装

sortedSquaredArray.py
# sortedSquaredArray関数の定義。整数の配列を受け取り、二乗して昇順にソートした新しい配列を返す。
def sortedSquaredArray(array):
    # sortedSquaresという名前の新しいリストを作成し、arrayと同じ長さで0で初期化する。
    sortedSquares = [0 for _ in array]

    # arrayの要素を順番に処理するためのforループ
    for idx in range(len(array)):
        # 現在処理中の要素の値をvalue変数に代入する。
        value = array[idx]

        # sortedSquaresリストの対応する位置にvalueの二乗を格納する。
        sortedSquares[idx] = value * value

    # すべての要素の二乗がsortedSquaresリストに格納されたら、リストを昇順でソートする。
    sortedSquares.sort()

    # ソートされたsortedSquaresリストを返す。
    return sortedSquares

# テスト
if __name__ == "__main__":
    array = [-4, -2, 0, 2, 4]
    print(sortedSquaredArray(array))

参考

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?