Home > database >  Generating a list of tuples between a range of values
Generating a list of tuples between a range of values

Time:12-06

I'd like to define a function that takes in a list of integers, such as [3, 2, 2], and outputs a list of the following tuples, sorted in this order (from least to greatest).

The first element ranges from 0..2, since the first element of the input list is 3; the second from 0..1, since the second element of the input list is 2; the third from 0..1, since the second element of the input list is 2.

    (0, 0, 0)
    (0, 0, 1)
    (0, 1, 0)
    (0, 1, 1)
    (1, 0, 0)
    (1, 0, 1)
    (1, 1, 0)
    (1, 1, 1)
    (2, 0, 0)
    (2, 0, 1)
    (2, 1, 0)
    (2, 1, 1)

I'm having trouble writing this function. I'd like to see if the community can recommend ways to do this.

Thank you.

CodePudding user response:

You can use itertools.product.

from itertools import product

lst = [3, 2, 2]

result = list(product(*(range(l) for l in lst)))
# Or
# result = list(product(*map(range, lst)))

print(result)

Or as a function:

def prdct_lst(lst):
    return list(product(*map(range, lst)))

prdct_lst([3, 2, 2])

Output:

[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1),
 (2, 0, 0),
 (2, 0, 1),
 (2, 1, 0),
 (2, 1, 1)]

Explanation:

>>> list(product(*[[1, 2], [3, 4]])) # 1 with 3, 4 then 2 with 3, 4
[(1, 3), (1, 4), (2, 3), (2, 4)]
# then we need to product range(3) = [0, 1, 2] with range(2) =[0, 1] and range(2) = [0, 1]

CodePudding user response:

you want to get good at these kinds of problems you go to HackerRank or leetcode.com and you will encounter all sorts of different problems that will help you to get through any job Interview, you start easy problems , and always do it by your self and then go and see other people solutions. these places are the ones who develops your problem solving skills.

https://www.hackerrank.com/domains/python https://leetcode.com/problemset/all/

and if you want to input your list in the solution above you just add

 lst  = list(map(int,input().split()))
  • Related