Home > Back-end >  "For in range" not working as was suposed to, and I don't know why
"For in range" not working as was suposed to, and I don't know why

Time:11-05

I was trying to find a simple way to do the "code 1" below, but I don't know why the result is not the same. My teacher create a code that have 6 elif, and I thought that is not the practical way. I tried to use a for inside the for, for a range (0,7), as the code 1 has 7 if, zero to seven, but didn't work, as you can see in the print 4.

In code 2, the for is putting the last value of the array instead of the respective value of the logical code.

Someone know how can I fix this? Thanks

Setup code:

import numpy as np

frete=600
estocagem=300

#Criar os vetores de Demanda e de Frequencia

vetordemanda=np.array([0,1000,2000,3000,4000,5000,6000,7000])
vetorfrequencia=np.array([0.01,0.05,0.1,0.14,0.26,0.3,0.1,0.04])

#Vetor de frequencia acumulada (Cumulative sum)
vetorfreqacumulada=np.cumsum(vetorfrequencia)

vetoraleatorio=np.random.rand(100)

vetordemandasim=np.zeros(100)

Code 1:

for t in range(0,100):
    if vetoraleatorio[t]<=vetorfreqacumulada[0]:
        vetordemandasim[t]=vetordemanda[0]
    elif vetoraleatorio[t]<=vetorfreqacumulada[1]:
        vetordemandasim[t]=vetordemanda[1]
    elif vetoraleatorio[t]<=vetorfreqacumulada[2]:
        vetordemandasim[t]=vetordemanda[2]
    elif vetoraleatorio[t]<=vetorfreqacumulada[3]:
        vetordemandasim[t]=vetordemanda[3]
    elif vetoraleatorio[t]<=vetorfreqacumulada[4]:
        vetordemandasim[t]=vetordemanda[4]
    elif vetoraleatorio[t]<=vetorfreqacumulada[5]:
        vetordemandasim[t]=vetordemanda[5]
    elif vetoraleatorio[t]<=vetorfreqacumulada[6]:
        vetordemandasim[t]=vetordemanda[6]
    else:
        vetordemandasim[t]=vetordemanda[7]

Code 2 (Not working):

for t in range(0,100):
    for i in range(0,7):
        if vetoraleatorio[t]<=vetorfreqacumulada[i]:
            vetordemandasim[t]=vetordemanda[i]

Result of code 1:

0 - 4000
1 - 5000
2 - 4000
3 - 5000
5 - 1000
6 - 6000
7 - 4000
8 - 5000
...

Result of code 2:

0 - 7000
1 - 7000
2 - 7000
3 - 7000
5 - 7000
6 - 7000
7 - 7000
8 - 7000
...

CodePudding user response:

This doesn't work because with if and elif it will not try to evaluate every other condition in the chain once one evaluates to true. In your code it will evaluate every condition regardless. If you would like to keep using your method you need to break out of the inner loop that handles the checking after finding one evaluates to true.

You are also missing a base case that is covered by the first example's else.

if vetoraleatorio[t] <= vetorfreqacumulada[i]:
    vetordemandasim[t] = vetordemanda[i]
    break
# If we get here no condition was True
if i == 6:
    vetordemandasim[t] = vetordemanda[7]
  • Related