N 個の最小要素

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

このチャレンジでは、与えられたリストから n 個の最小要素を返す Python 関数を書くことが求められます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/booleans -.-> lab-13695{{"N 個の最小要素"}} python/comments -.-> lab-13695{{"N 個の最小要素"}} python/lists -.-> lab-13695{{"N 個の最小要素"}} python/tuples -.-> lab-13695{{"N 個の最小要素"}} python/function_definition -.-> lab-13695{{"N 個の最小要素"}} python/default_arguments -.-> lab-13695{{"N 個の最小要素"}} python/build_in_functions -.-> lab-13695{{"N 個の最小要素"}} end

N 個の最小要素

min_n(lst, n = 1) という名前の関数を作成します。この関数は、リスト lst とオプションの整数 n(デフォルト値は 1)を受け取ります。関数は、元のリスト lst からの n 個の最小要素を含む新しいリストを返す必要があります。n が指定されない場合、関数は lst からの最小要素を含むリストを返す必要があります。

nlst の長さ以上の場合、関数は昇順にソートされた元のリストを返す必要があります。

関数は次の手順に従ってこれを達成する必要があります。

  1. 組み込みの sorted() 関数を使用して、リストを昇順にソートします。
  2. スライス表記を使用して、指定された数の要素を取得します。
  3. 結果のリストを返します。
def min_n(lst, n = 1):
  return sorted(lst, reverse = False)[:n]
min_n([1, 2, 3]) ## [1]
min_n([1, 2, 3], 2) ## [1, 2]

まとめ

このチャレンジでは、与えられたリストから n 個の最小要素を返す Python 関数を書く方法を学びました。また、このタスクを達成するために組み込みの sorted() 関数とスライス表記をどのように使用するかも学びました。