0

I'm currently having a problem in python, what I am trying to do is go through 6 arrays checking if there is a negative number or not and then adding one to the corresponding variable.

I've tried various things to fix this however there is no real documentation that I can find online that will help me

BusA = ["-1","1","-1","1"]
BusB = ["-1","1","-1","1"]
BusC = ["-1","1","-1","1"]
BusD = ["-1","1","-1","1"]
BusE = ["-1","1","-1","1"]
BusF = ["-1","1","-1","1"]

Buses = "ABCDEF"

BusALate, BusBLate, BusCLate, BusDLate, BusELate, BusFLate = 0, 0, 0, 0, 0, 0

for c in Buses:
  Array = eval("Bus" + str(c))
  for i in Array:
    if(int(i) < 0):
      eval("Bus"+c+"Late") += 1

print(BusALate, BusBLate, BusCLate, BusDLate, BusELate, BusFLate)

If possible I just need a way to format the variable in the if so that it can progressively go through changing it to BusALate, BusBLate etc... and adding when it has found the negative number.

1
  • 6
    You should really use a dict: busses = {"A": [-1, 1, -1, 1], B: [....], ...} and integers, if your values are meant to be numbers. So, you would also have busses_late = {A: 0, ...} Commented Feb 15, 2019 at 9:25

3 Answers 3

1

Building upon Thierry Lathuille's suggestion, here is how using dictionnaries can simplify your code :

bus_schedules= {
    "A" : ["-1","1","-1","1"],
    "B" : ["-1","1","-1","1"],
    "C" : ["-1","1","-1","1"],
    "D" : ["-1","1","-1","1"],
    "E" : ["-1","1","-1","1"],
    "F" : ["-1","1","-1","1"]
}

bus_late = {"A" : 0, "B" : 0, "C" : 0, "D" : 0, "E" : 0, "F" : 0}

for (bus_name, bus_times) in bus_schedules.items():
    for i in bus_times :
        if (int(i) < 0):
            bus_late[bus_name]+=1

print(bus_late)
Sign up to request clarification or add additional context in comments.

Comments

0
import numpy as np

buses =  np.array([[-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1],
                   [-1,1,-1,1]])

print(np.sum(buses<0, axis=1))

Comments

0

String conversion and dict comprehension in one step:

busses = {'A':["-1","1","-1","1"],
          'B': ["-1","1","-1","1"],
          'C': ["-1","1","-1","1"],
          'D': ["-1","1","-1","1"],
          'E': ["-1","1","-1","1"],
          'F': ["-1","1","-1","1"]}

busses = {key: [(value + 1) if value < 0 else value
                for x in lst
                for value in [int(x)]]
          for key, lst in busses.items()}
print(busses)

This yields

{'A': [0, 1, 0, 1], 
 'B': [0, 1, 0, 1], 
 'C': [0, 1, 0, 1], 
 'D': [0, 1, 0, 1], 
 'E': [0, 1, 0, 1], 
 'F': [0, 1, 0, 1]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.