Hi, I'm new to programming in Python, & I need help. I am trying to read from a text file, which contains:

1 4 5 3
1 0 2 4 18
5 2 0 0 9

I am suppose to implement a Simplex algorithm that can hopefully solve these numbers. So far, I am able to make the program print out the numbers as a 2d array. I have each line of the text file saved as an array. For example, array[0] = [1, 4, 5, 3]. I know the trick to the simplex method is to convert the equation into linear equations, thus using arrays would be the wisiest choice. However I'm stuck in making the initial matrix (sometimes called the "tableau"). Can anyone help me? I'd appreciate it

Here's my code:

import sys
import string
import array
import os
import array

#initialize empty lists
#objective = []  #1st line of text file, the objective 
#constraint1 = []
#constraint2 = []
inputfile = "input file.txt"  #input file

#read the data in the file:
def readinputfile(inputfile):

f = open(inputfile, "r")  #read from file
data = f.read()  #read the entire file
return data  #return the data

#Simplex algorithm
def simplex(inputfile):
    f = file(inputfile, "r")  #read from file
    array = [line.split() for line in f]  #save data in a 2d array

    #show data BEFORE simplex algorithm
    print "Data in file, before performing simplex method:"
    print "\t", array[0]  #print arrays
    print "\t", array[1]  #array[1] & array[2] are the initial matrices
    print "\t", array[2]

    #now, solve with simplex method
    for array in range(f):
        if array == 4:
            print array

f.close()  #close the file

Recommended Answers

All 3 Replies

Dont use array,in python we call it list.
import array is only for very specialized task.

Your indentation is wrong and you read in file more than once.
Take a look at this,and you should read a basic tutorial about list in python.

numb_list = []    
with open('numb.txt') as f:
    for item in f:
        numb_list.append([int(i) for i in item.split()])

print numb_list
print numb_list[0]  #print list
print 'A number in list 0: %d' % numb_list[0][2]

[[1, 4, 5, 3], [1, 0, 2, 4, 18], [5, 2, 0, 0, 9]]
[1, 4, 5, 3]
A number in list 0: 5

Fix your indention. What is this two reads for reading the file 18-19, 25-26? You are not using any of imported modules, why you import them?

You also have to convert from strings in the file, to integers. A read and convert example

test_data="""1 4 5 3
 1 0 2 4 18
 5 2 0 0 9"""
##f = open(inputfile, "r")
f = test_data.split("\n")
output_list = []
for rec in f:
    numbers_as_strings = rec.split()
    print numbers_as_strings     ## while testing
    inner_list = []
    for num in numbers_as_strings:
print "\noutput_list =", output_list
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.