Task text: Generate ten lists of random numbers. Print them and the sum of their elements on the screen. Find among them one with the maximum sum of elements. Specify what it is in the account, re-display this list and the sum of its elements. Filling out the list and counting the sum of its elements arrange in the form of individual functions.

Now actually to the problem: in the first function (see below code) I have 10 lists filled in, in the second function the sum is found in 10 lists, but I generate new 10 lists, and I need to work with the result obtained in the first one, that is, with old lists, the question is how to fix it?

Problem number 2: I do not know how to re-list with the maximum sum of the elements and the list itself

import random n = int(input("Введите кол-во возможных случайных:")) b = int(input("Введите диапазон случайных значений:")) def func_1(n,b): d = [[random.randrange(b) for i in range(n)] for i in range(10)] print("Исходные 10 списков:",d) func_1(n,b) def func_2(n,b): d = [[sum(random.randrange(b) for i in range(n))] for i in range(10)] print("сумма элементов в каждом из 10 списков:",d) return d func_2(n,b) d = func_2(n,b) g = max(d) c = len(d) for i in range(c): if d[i] == g: print("Номер максимального элемента:",g,i) 

    1 answer 1

    Try to arrange the functions in such a way that they return the values ​​you are interested in, and not just print them on the screen.

     import random def gen_list(n,b): return [random.randrange(b) for i in range(n)] def sum_list(lst): return sum(lst) N = 5 n = 10 b = 100 lists = [gen_list(n,b) for _ in range(N)] print(lists) #[[31, 2, 61, 28, 85, 36, 7, 81, 40, 71], # [13, 59, 66, 52, 54, 75, 23, 66, 66, 23], # [50, 16, 99, 74, 82, 94, 32, 30, 70, 7], # [27, 88, 87, 15, 58, 86, 71, 47, 27, 29], # [27, 43, 74, 7, 60, 68, 75, 69, 77, 57]] print([sum_list(l) for l in lists]) #[442, 497, 554, 535, 557] idx_max = max(enumerate(lists), key=lambda x: sum_list(x[1]))[0] print(f'Max list: {lists[idx_max]}\nsum(max_list): {sum_list(lists[idx_max])}') #Max list: [27, 43, 74, 7, 60, 68, 75, 69, 77, 57] #sum(max_list): 557 
    • please explain print ([sum_list (l) for l in lists]) - user310802
    • @Noob_Prog, “list comprehension” is used here to print the sums of internal lists - MaxU
    • Thanks for the decision - user310802
    • lists = [gen_list (n, b) for _ in range (N)] explain why you need an underscore here? - user310802
    • The underscore is used as an “unnecessary” variable. Any free variable name could be used here. This variable is not used anywhere and is needed to iterate over “range ()”. - MaxU