Advertisement
t_naveen_2308

Sum Over N Bound

Oct 11th, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from random import randint, shuffle
  2.  
  3.  
  4. def size_split(typ=0, size=10**5, spli=2, minn=1):
  5.     """
  6.    Splits a given size into unknown number of random positive integers, ensuring
  7.    that each integer is at least `minn`. The sum of the integers will equal
  8.    the initial size.
  9.  
  10.    Parameters:
  11.    typ (int): Type 0 means constant spliting while type 1 means random.
  12.    size (int): The total size to be split (default is 100,000).
  13.    spli (int): The number of parts to split the size into (default is 2).
  14.    minn (int): The minimum value each integer in the split must have (default is 1).
  15.  
  16.    Returns:
  17.    list: A list of known number in type 0 or unknown number of positive integers in type 1 that sum up to the
  18.          original size.
  19.  
  20.    Notes:
  21.    - If the size is less than n, an empty list will be returned.
  22.    - The output will be shuffled randomly.
  23.    """
  24.     if typ == 0:
  25.         if size % spli:
  26.             raise ValueError("spli should divide size.")
  27.         return [size // spli] * spli
  28.     else:
  29.         arr = []
  30.         tsize = size
  31.         while size >= spli:
  32.             x = randint(1, size // spli)
  33.             arr.append(x)
  34.             size -= x
  35.         arr.sort(reverse=True)
  36.         sumi = size
  37.         while arr and arr[-1] <= minn:
  38.             sumi += arr.pop()
  39.         if sumi>=minn:
  40.             arr.append(sumi)
  41.         else:
  42.             arr[-1] += sumi
  43.         assert sum(arr) == tsize
  44.         shuffle(arr)
  45.         return arr
  46.  
  47. # Example Usage
  48. if __name__ == "__main__":
  49.     result1 = size_split(typ=0, size=10**5, spli=1, minn=10)
  50.     print(result1)
  51.     result2 = size_split(typ=1, size=1000, spli=100, minn=1)
  52.     print(result2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement