Repeating a number based on position and value?
I am trying to learn about algorithmic thinking in my spare time from a book I got.
I am thinking about scenarios and trying to solve them using pseudocode in order to learn but I cannot approach this idea below. I am thinking of doing this with a nested loop but I don't know how to begin. Can you please assist?
If we have a 1d array that mentions how many times each position should be repeated for example:
With N = 5, the 1d array is z = 2,1,1,3,2
Based on that, we should populate a new array with the times each number appears. Therefore, based on z
we should have a 1d array A = 1,1,2,3,4,4,4,5,5.
Explanation: the first position of z
has the number 2
. Therefore, in the A array the number 1
should appear two times. continuing the number two of array z
has the number 1
, therefore the number 2
in the array A
should appear only once, and so one for the rest numbers. So there is a pattern between the two arrays.
NOTE: This should not be using any functions or turning values to string and multiplying them. I am interested in the theoretical side of it and want to learn how to think for such problems.
UPDATE
Would it help if we have
an array with unsorted items:
A: 2,3,1,2,4
and z
where calculates how many times each position is mentioned.
z: 1,2,1,1
can we create a new array that will make the the content of A
sorted based on the content of z
?
Solution 1:
You can use list comprehension with nested loop:
result = [i+1 for i, freq in enumerate(z) for _ in range(freq)]
Without list comprehension:
result = []
for i, freq in enumerate(z):
result.extend([i+1]*freq)
Without any functions (less Pythonic), using +=
and *
operators for lists:
result = []
i = 1
for freq in z:
result += [i] * freq
i += 1
Without *
operator for lists:
result = []
i = 1
for freq in z:
while freq > 0:
result += [i]
freq -= 1
i += 1
+= [i]
is really a clumsy way to append(i)
, but at least it avoids the function, which you seem to be looking for.