Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonで合計kになるリスト内の任意の2つの数値を検索するプログラム


numsと呼ばれる数のリストがあり、別の数kがあるとすると、リストに存在する2つの数の合計がkになるかどうかを確認する必要があります。同じ要素を2回使用しないでください。また、数値は負または0にすることができます。

したがって、入力がnums =[45、18、9、13、12]、k =31のような場合、出力はTrueになります(18 + 13 =31

)。

これを解決するには、次の手順に従います-

  • temp_set:=新しいセット
  • numsの各numに対して、実行します
    • numがtemp_setにある場合、
      • Trueを返す
    • temp_setに(k-num)を追加します
  • Falseを返す

理解を深めるために、次の実装を見てみましょう-

class Solution:
   def solve(self, nums, k):
      temp_set=set()
      for num in nums:
         if num in temp_set:
            return True
            temp_set.add(k-num)
      return False
ob = Solution()
nums = [45, 18, 9, 13, 12] k = 31 print(ob.solve(nums, k))

入力

[45, 18, 9, 13, 12], 31

出力

True

  1. 2つのリストの共通部分を見つけるPythonプログラム?

    交差演算とは、リスト1とリスト2からすべての共通要素を取得する必要があり、すべての要素が別の3番目のリストに格納されることを意味します。 List1::[1,2,3] List2::[2,3,6] List3::[2,3] アルゴリズム Step 1: input lists. Step 2: first traverse all the elements in the first list and check with the elements in the second list. Step 3: if the elements are matched then store in t

  2. 2つ以上のリストのユニオンを見つけるPythonプログラム?

    和集合演算とは、リスト1とリスト2からすべての要素を取得し、すべての要素を別の3番目のリストに格納する必要があることを意味します。 List1::[1,2,3] List2::[4,5,6] List3::[1,2,3,4,5,6] アルゴリズム Step 1: Input two lists. Step 2: for union operation we just use + operator. サンプルコード # UNION OPERATION A=list() B=list() n=int(input(Enter the size of the List ::)) print(