Olga973
Olga973

Reputation: 11

How to count elements inside list with specific condition

I am making combination of six number is seems easy but i need output of specific combination

i think i need to use count function and loop?????

from itertools import combinations

comb = combinations([1, 2, 3, 4, 5, 6], 3) 
for n in list(comb):
  print (n)

Actual result give me 20 combination, but i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3,

so in my case it will be

(1,2,3) (1,3,4) (1,4,5) (1,5,6) (2,3,5) (2,4,6)

Upvotes: 1

Views: 55

Answers (3)

krokodilko
krokodilko

Reputation: 36107

Another solution:

result = [(x,y,z) for (x,y,z) in combinations([1, 2, 3, 4, 5, 6], 3) if x+y==z]
print(result)

[(1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (2, 3, 5), (2, 4, 6)]

Upvotes: 0

John Gordon
John Gordon

Reputation: 33310

i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3

Add that as an if statement inside the for loop:

for n in comb:
    if n[0] + n[1] == n[2]:
        print (n)

Upvotes: 1

yukashima huksay
yukashima huksay

Reputation: 6238

Try this oneliner:

from itertools import combinations as combs
print(list(filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3))))

Or if your want to print one combination at a time you can do:

from itertools import combinations as combs
for comb in filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3)):
    print(comb)

Upvotes: 0

Related Questions