Question:
I am asked to write a procedure that accepts as a parameter a vector containing positive numbers, which can contain duplicate values, and replaces each repeated element with -1 (minus one). The procedure must return the modified vector and the number of times it was modified. I did it like this:
vector = [1,2,3,4,4,3]
for i in range(0,6):
if vector[i] == vector[i]:
vector[i] = -1
print(vector)
but it replaces all the numbers by -1 not only the repeated ones.
Answer:
One solution is to traverse the array checking each element ( vector[i]
) against previous elements ( vector[:i]
).
I put the code in a function
def examinar(vector):
for i in range(1, len(vector)):
if vector[i] in vector[:i]:
vector[i] = -1
return vector
and i taste it
tests = [[],
[100],
[100, 100],
[1, 2, 3, 4],
[1, 2, 2, 4],
[5, 5, 5, 4, 5],
[-1, -1, 3, 100, 200, 3]]
for test in tests:
print(test, end=" => ")
print(examinar(test))
produce
[] => []
[100] => [100]
[100, 100] => [100, -1]
[1, 2, 3, 4] => [1, 2, 3, 4]
[1, 2, 2, 4] => [1, 2, -1, 4]
[5, 5, 5, 4, 5] => [5, -1, -1, 4, -1]
[-1, -1, 3, 100, 200, 3] => [-1, -1, 3, 100, 200, -1]