2つのリストのすべての共通要素を出力するPythonプログラム。
2つのリストがある場合、2つのリストのすべての共通要素を印刷します。
例-
Input : L1 = [5, 6, 7, 8, 9]
L2 = [5, 13, 34, 22, 90]
Output : {5}
説明
両方のリストに共通する要素は5です。
アルゴリズム
Step1 : create two user input lists. Step2 : Convert the lists to sets and then print set1&set2. Step3 : set1 and set2 returns the common elements set, where set1 is the list1 and set2 is the list2.
サンプルコード
# Python program to find the common elements
# in two lists
def commonelemnets(a, b):
seta = set(a)
setb = set(b)
if (seta & setb):
print("Common Element ::>",seta & setb)
else:
print("No common elements")
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
B=list()
n=int(input("Enter the size of the Second List ::"))
print("Enter the Element of Second List ::")
for i in range(int(n)):
k=int(input(""))
B.append(k)
commonelemnets(A,B)
出力
Enter the size of the First List :: 4
Enter the Element of First List ::
4
5
6
7
Enter the size of the Second List :: 4
Enter the Element of Second List ::
1
2
3
4
Common Element ::> {4}
Enter the size of the First List :: 4
Enter the Element of First List ::
1
2
3
4
Enter the size of the Second List :: 4
Enter the Element of Second List ::
5
6
7
8
No common elements
-
3つのソートされた配列で共通の要素を見つけるPythonプログラム?
ここでは、最初にユーザー入力のソートされていない配列である3つの配列を作成し、次に3つのソートされていない配列すべてをソートします。配列のサイズはn1、n2、n3です。すべての配列の開始アドレスは0.i =0、j =0、k =0です。次に、3つの配列のすべての要素をトラバースし、3つの配列の要素が同じかどうかを確認します。そうでない場合は、要素を印刷し、そうでない場合は次の要素に進みます。 例 A = {1, 2, 3, 4, 5} B = {2, 5, 12, 22, 7} C = {1, 9, 2, 89, 80} 出力 2 アルゴリズム commonele(A1,A2,A3,n
-
リスト内のすべての数値を乗算するPythonプログラム?
まず、ユーザー入力用の3つのリストを作成します。ここでは、トラバース手法を使用します。 productの値を1に初期化して、すべての要素をトラバースし、リストの最後まですべての数値にproductを1つずつ掛けます。 例 Input: A=[5,6,3] Output:90 Explanation:5*6*3 アルゴリズム Step 1: input all numbers in the list (lst). Step 2: to multiply all values in the list we use traversing technique. Step 3: varia