2015-05-18

PYTHON - Determine all possible factor combinations for a given number, from a given numeric array

Check this out at GitHub.com
https://github.com/falconerandloillc/factors


# 1. Sample call
#print( factors( 240, [2,3,4,5,6,7,8,9,10,11,12,24] ) );


# 2. The function... 
import time
def factors(target, arr):
    # Parameters test/fix
    if target == None or target == 0 or arr == None or len(arr) < 2:
        return None
    # Declarer
    start = int(round(time.time() * 1000))
    global iterations
    global combinations
    iterations=0
    combinations=[]
    # Keep only non-zero numbers
    arr = [x for x in arr if isinstance(x, float) or isinstance(x, int)]
    if len(arr) <= 1:
        return None
    # Sort
    arr.sort()
    # Recurse each array element
    for j in range(len(arr)):
        i = j
        r = []
        def recurse(v, i):
            global iterations, combinations
            while i < len(arr) and (v*arr[i-1]) < abs(target):
                iterations += 1
                r.append(arr[i])
                recurse(v*arr[i], i+1)
                i += 1
                r.pop()
            if v == target and len(r) > 1:
                combinations.append("".join(str(r)))
            return 1
        r.append(arr[j])
        recurse(arr[j], j+1)
    return {
        "combinations": combinations
        , "count": len(combinations)
        , "time": str(int(round(time.time()*1000))-start) + " ms"
        , "array": arr
        , "target": target
        , "iterations": iterations
    }


No comments:

Post a Comment