The Concept Behind itertoolss product Function

2024/11/9 6:06:08

so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.

    def product1(*args, **kwds):pools = map(tuple, args) * kwds.get('repeat', 1)n = len(pools)if n == 0:yield ()returnif any(len(pool) == 0 for pool in pools):returnindices = [0] * nyield tuple(pool[i] for pool, i in zip(pools, indices))while 1:for i in reversed(range(n)):  # right to leftif indices[i] == len(pools[i]) - 1:continueindices[i] += 1for j in range(i+1, n):indices[j] = 0yield tuple(pool[i] for pool, i in zip(pools, indices))breakelse:return
Answer

I would highly recommend using the well established and tested itertools standard module. Reinventing the wheel is never advisable as a programmer. That said, I would start by taking a look at the product() function in itertools.

As for not using itertools(), this problem is essentially a cartesian product problem (n-permutations with duplicates allowed). This is where recursion helps us! One possible solution below:

Method Body:

result = []
def permutations(alphabet, repeat, total = ''):if repeat >= 1:for i in alphabet:# Add the subsolutions.     permutations(alphabet, repeat - 1, total + i)  else:result.append(total)return result

And when we call with permutations()

Sample Outputs:

permutations('ab', 3) ->
$ ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
permutations('ab', 3) ->
$ ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa','bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']
permutations('ab', 1) ->
$ ['a', 'b']

How does it work?

This method works by nesting for loops in a recursive manner repeat-times. We then accumulate the result of the sub-solutions, appending to a result list. So if we use 4 as our repeat value, out expanded iterative trace of this problem would look like the following:

for i in alphabet:for j in alphabet:for k in alphabet:for l in alphabet:result.append(i + j + k + l)
https://en.xdnf.cn/q/120528.html

Related Q&A

how to read data from multiple sheets in a single csv file using python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking for code must demonstrate a minimal understanding of the problem being solved. Incl…

Quality Center: Set a Step Field in Python

I have a very simple problem here. I want to achieve the following VB script Code in Python:- dim objSfact dim objOrun dim mystep Set objOrun = QCutil.CurrentRun Set objSfact = objOrun.StepFactory…

Convert for loop from Python to C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Storing values in a CSV file into a list in python

Id like to create a list that stores all values of a single column. For example lets say my file has a column called FirstNames and for the first 3 rows, the names column has Merry, Pippin, Frodo.Id l…

Python arithmetic quiz task 1

I have no idea why this code is not working, as you can see Im trying to ask the user 10 questions display their score at the end. Everything works except that the score will always appear as a 0 or 1 …

Using Python to split long string, by given ‘separators’ [duplicate]

This question already has answers here:Split Strings into words with multiple word boundary delimiters(31 answers)Closed 9 years ago.Environment: Win 7; Python 2.76I want to split a long string into pi…

How do I return the number of unique digits in a positive integer

Example: unique_dig(123456) All unique 6Im trying to write code to have a function return how many unique numbers there are in a positive integer.count = 0for i in unique_digits:if count.has_key(i):cou…

Python check json file with variables

I have a json file which has 18 substrings like this: https://i.sstatic.net/aVWuw.png https://i.sstatic.net/RLlRX.pngBut I have more json files who have different number of these substrings. So I did t…

The Sum of Consecutive Numbers in Python

What I have to do is get the user input and add consecutive numbers starting with one using a loop until the sum equals or exceeds the input. Its an exercise, so Im trying to do this without using the …

how to write to a text file using python ?

I am trying to output a full for iteration. The output should be in a text file. How should I code for that ? The output should look like :Iteration 1 values --------> val1 < tab > val2 < …