Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to get line numbers of a standard output

I found a solution of a problem and is a recursive function that gives me multiple combinations of numbers like:

  • 2 2 3
  • 2 4 2
  • 2 3 3
  • 2 2 4

and I need to find the number of combinations that the functions provides me but the function uses a print to return the values (I cannot store any variable to return because is recursive) and I cannot find a way to count the number of lines of the output which gives me the solution.

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

code:

def box_extraction(vec, index, target, reducedNum):
        if (reducedNum < 0):
           return
        if (reducedNum == 0):
            for i in range(index):
               print(vec[i], end = " ")
            print("")
            return 
        prev = 1 if(index == 0) else vec[index - 1]
        for k in [2,3,4]:
            vec[index] = k
            box_extraction(vec, index + 1, target, reducedNum - k)

def findSums(n):
    vector = [0] * n
    box_extraction(vector, 0, n, n)
 
n = 8;
findSums(n)

>Solution :

You can get the number of combinations by converting the functions to a generator as follows.

Code

def box_extraction(vec, index, target, reducedNum):
        if (reducedNum < 0):
           return
        if (reducedNum == 0):
            result = [vec[i] for i in range(index)]
            #for i in range(index):
            #   print(vec[i], end = " ")
            #print("")
            yield result
        prev = 1 if(index == 0) else vec[index - 1]
        for k in [2,3,4]:
            vec[index] = k
            yield from box_extraction(vec, index + 1, target, reducedNum - k)

def findSums(n):
    vector = [0] * n
    yield from box_extraction(vector, 0, n, n)

Usage

n = 8;

# To get the number of items:
print(f"Number of items: {len(list(findSums(n)))}")
print("items with an index")
# To generate result with an index
for i, result in enumerate(findSums(n), start = 1):
    print(f"{i}: {' '.join(str(x) for x in result)}")

Output

Number of items: 8
items with an index
1: 2 2 2 2
2: 2 2 4
3: 2 3 3
4: 2 4 2
5: 3 2 3
6: 3 3 2
7: 4 2 2
8: 4 4
​
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading