Home > Enterprise >  Checking every element in an array for a specific requirement
Checking every element in an array for a specific requirement

Time:11-24

I need to check every element in an array to see if it can be divided by 5 or more different numbers, if not - drop it into a different array.

For example, I have an array [3,32,6,8,0,16,3,45] and I have to get a result of [3,5,8,0,3]

I tried going for a simple while loop inside a for loop:

for i in array:
    n = 0
    div = 1
    while n <= 4 and div <= i:
        if i % div == 0:
            n  = 1
        div  = 1

    if n <= 4:
        sub_array.append(i)

return sub_array

It works just fine, but I need to make it so it will check the division with elements and not indexes. The moment I change all 'i' to 'array[i]': "list index out of range". Is there any way to solve this issue?
The reason why I'm trying to improve this code is because the tester I am using to check it returns errors from time to time.

CodePudding user response:

When you do for i in array it means the 'i' is the element in the array. If you want to iterate with using array[i] you should use for i in range(len(array))

The modified code is as follows:

for i in range(len(array)):
    n = 0
    div = 1
    while n <= 4 and div <= array[i]:
        if array[i] % div == 0:
            n  = 1
        div  = 1

    if n <= 4:
        sub_array.append(array[i])

return sub_array

CodePudding user response:

what I've understood from your question is that if any of the numbers from an array is not divisible by 5, you want them to be put into a different array. So, I've written this code for you. I hope it will solve your problem.

array = [3,32,6,8,0,16,3,45]
subarray = []
for i in array:
    if i%5==0:
        continue
    else:
        subarray.append(i)

print(subarray)
  • Related