I solved the problem in Python, but when using the random.shuffle module, periodically, the console does not display the correct answer. Without using the module errors do not occur!

Given the real numbers a1, a2, ..., an. Among them are positive and negative. Replace with zeros those numbers whose magnitude is greater than the maximum number (| ai |> max {a1, a2, ..., an}).

import random c = [2, -2, -6, -8, 7, -9, 1, -3, -5, -11, 3, -7, -10, 0, -1, 4, -4, -12, 5, 6] random.shuffle(c) b = max(c) for i in c: if abs(c[i]) > b: c[i] = 0 print(c) 

So, can withdraw such an answer:

 [0, -7, -2, 0, 0, -5, -3, 5, -6, -4, <strong>-11</strong>, 0, 3, -1, 4, 7, 1, 0, 2, 6]. 

Where <strong>-11</strong> should not be!

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Module shuffle nothing to do with it. You do not use the for loop correctly. i is not a loop counter, but an element from c . You need to separately start the counter and access through it to the element that you want to reset:

 import random c = [2, -2, -6, -8, 7, -9, 1, -3, -5, -11, 3, -7, -10, 0, -1, 4, -4, -12, 5, 6] random.shuffle(c) b = max(c) i = 0 for el in c: if abs(el) > b: c[i] = 0 i += 1 print(c) 

In general, the problem can be solved much shorter, without a loop, but using the built-in map function:

 import random c = [2, -2, -6, -8, 7, -9, 1, -3, -5, -11, 3, -7, -10, 0, -1, 4, -4, -12, 5, 6] random.shuffle(c) b = max(c) d = map(lambda x: 0 if abs(x) > b else x, c) print(list(d)) 
  • For the counter, they usually use enumerate , and do not get a separate variable that is constantly increased by 1. - Arnial
  • Damn, for sure! Tupanul! Thank you, doused. - Jürgen von Markoff
  • @Arnial, it would be all wrong anyway, I specifically led a more idiomatic solution. - Klym