Reputation: 11
I have a text file consisting of some stocks and their prices and what not, I am trying to print out the stock which has the lowest value along with the name of the company here is my code.
stocks = open("P:\COM661\stocks.txt")
name_lowest = ""
price_lowest = 0
for line in stocks:
rows = line.split("\t")
price = float(rows[2])
if price>price_lowest:
price_lowest = price
name_lowest = rows[1]
print(name_lowest + "\t" + str(price_lowest))
I'm trying to go through the file and compare each numeric value to the one before it to see if it is higher or lower and then at the end it should have saved the lowest price and print it along with the name of the company. Instead it prints the value of the last company in the file along with its name.
How can I fix this?
Upvotes: 2
Views: 117
Reputation: 4606
Just make a little adjustment start your price_lowest
at None
then set it to your first encounter and compare from there on
stocks = open("P:\COM661\stocks.txt")
name_lowest = ""
price_lowest = None
for line in stocks:
rows = line.split("\t")
price = float(rows[2])
if price_lowest = None:
price = price_lowest
name_lowest = rows[1]
elif price < price_lowest:
price_lowest = price
name_lowest = rows[1]
print(name_lowest + "\t" + str(price_lowest))
Upvotes: 0
Reputation: 368
Your "if" logic is backwards, it should be price<lowest_pre
.
Upvotes: 0
Reputation: 95978
Others already suggested a solution that fixes your current code. However, using Python you can have a shorter solution:
with open('file') as f:
print min(
[(i.split('\t')[0], float(i.split('\t')[1])) for i in f.readlines()],
key=lambda t: t[1]
)
Upvotes: 1
Reputation: 5733
You made 2 mistakes. First is initialised the initial value to 0 You should initialise the initial value to the max available number in python float.
import sys
price_lowest = sys.float_info.max
Or else you could initialise it to the first element
Second your should if statement should be
if price<price_lowest:
Upvotes: 2
Reputation: 419
Initialize:
price_lowest = 999999 # start with absurdly high value, or take first one
Plus your if
check is the opposite.
Should be:
if price < price_lowest
Upvotes: 1