1

Noob question because I am new to Python but I am working on a side project where each of these voltages (0.3, 0.32, etc) are used as an input, and then that input generates a probability in an output file.

This is the output I'm looking for:

Input: 0.3 Probability = 7.509

Input 0.32 Probability = 1.399

Input 0.34 Probability = 2.773

Input 0.36 Probability = 0.127

...

This is the output I'm getting:

0.3

Probability = 7.509

0.3

Probability = 1.399

0.3

Probability = 2.773

0.3

Probability = 0.127

I'm having trouble putting the print(str(voltage)) statement in the right location to get the output that I want... As you can see, it is repeating the voltage over and over.

Here's the code, thank you for your time I appreciate you:

prob=[]

voltages = [0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42, 0.44, 0.46, 0.48, 0.5]
for voltage in voltages:
    update_code(voltage)
    os.system("hspice pbit.sp >output.txt")
    def search():
        with open('output.txt') as f:
            datafile = f.readlines()
        for line in datafile:
            if 'probability' in line:
                prob.append(line)
                return True
        return False
    if search():
        for voltage in voltages:
            for items in prob:
                print(str(voltage))
                print(items)
        else:
            print('False')
Jac Mills
  • 15
  • 1
  • 6
  • I think the issue might be that you defined the function within the loop, and you are looping over voltages within a loop of voltages itself. – JLi Apr 25 '20 at 16:19
  • Aside from the marked duplicate, you have a separate issue in that `search` can only `return` once, and thus will only ever `.append` one item to `prob`. Instead of having `search` return a boolean, just check whether there are any items in `prob` after calling it. Better yet, instead of using a global for `prob`, make `search` return it. – Karl Knechtel Apr 25 '20 at 16:49
  • I also don't understand what the outermost loop is for. It would help to explain in more detail what the *actual overall problem you are trying to solve* is. – Karl Knechtel Apr 25 '20 at 16:50

1 Answers1

2

What you need is a zip function so that you can print both the voltage and the probability side by side. Please note that both lists should have the same size to avoid any bugs.

for voltage, item in zip(voltages, prob):
    line = "Input: " + str(voltage) + " Probability: " + item
    print(line)
Ahmed Hammad
  • 2,798
  • 4
  • 18
  • 35