Random list of M non | Python3 implementation of the approach ; Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any random element from the array by 1 ; Print the generated list ; Driver code
from random import randint NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def randomList ( m , n ) : NEW_LINE INDENT arr = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ randint ( 0 , n ) % m ] += 1 ; NEW_LINE DEDENT printArr ( arr , m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 4 ; n = 8 ; NEW_LINE randomList ( m , n ) ; NEW_LINE DEDENT