Create a function that accepts a single array as an argument. Given an array of integers, x, sort x and split the integers into three smaller arrays of equal length. If the length of x is not evenly divisible by three, increase the size of the smaller arrays by one starting from the first array. The function should return an array of arrays.

Respuesta :

Limosa

Answer:

Following are the program in the Python Programming Language.

#define a function

def div(x):

 #set variable and sort its elements

 x = sorted(x)

 #set variable and store its remainder

 remainder = len(x)%3

 #set variable and store sublist of length of elements

 sub_list = int(len(x)/3)

 #set array list

 arr = []

 #set if conditional statement

 if(remainder==2):

   #set variable to add elements to the 1st sub list

   ls1 = x[:(sub_list+1)]

   #set variable to add elements to the 2nd sub list

   ls2 = x[(sub_list+1):(2*sub_list+remainder)]

 else:

   #set variable to add numbers of extra elements to the sublists

   ls1 = x[:(sub_list+remainder)]

   ls2 = x[(sub_list+remainder):((2*sub_list)+remainder)]

   #set variable for the 3rd sublist

   ls3 = x[((2*sub_list)+remainder):]

 #add sublists in the array list.

 arr.append(ls1)

 arr.append(ls2)

 arr.append(ls3)

 return arr

#set variable to store array list

ar = [2,1,3,4,7,5,6,8,13,12,11,10,0,15,16,14]

#call and print the function

print(div(ar))

Output:

[[0, 1, 2, 3, 4, 5], [6, 7, 8, 10, 11], [12, 13, 14, 15, 16]]

Explanation:

Here, we define a function "div()" and pass an argument "x" in its parentheses.

  • set a variable "x" to store the sorted elements by using the function "sorted()".
  • set a variable "remainder" to store remainder length of the elements.
  • set a variable "sub_list" to store the sub list of the elements and then set a variable "arr" to store array list.
  • set the if statement to check the condition is the variable remainder is equal to 2 then, set two variable to add two sublists.
  • otherwise, add reminder number of the extra elements into the list and then set a variable to the 3rd store sub list.
  • Append all the list in the array list variable "arr".

Finally, set the array list variable to store the elements outside the function then call and print the following funtion.