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?
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:
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
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]
)
Your "if" logic is backwards, it should be price<lowest_pre.
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))
Related
im trying to iterate this and cant figureout how. Theres .csv file.
QUESTION: so i finds LOW_num's data[0], and got to get TOP_num for TOP_num's data[0] < LOW_num's data[0] What the formula could be? The example:
for line in file:
data = line.split(sep)
A line looks like this:
2022-04-05T08:34:39+02:00, 1.2024, 1.2024, 1.2024, 1.2024, 1.2185, 1.2059028833000065, 1.2024784243912705, 1.2004400559932131, 1.198116316019428
So data[0] means Column A, data[1] is Column B, data[2] is Column C, (...)
memory["high"] = {}
memory["low"] = {}
for line in file:
data = line.split(sep)
if data[5] < data[9]:
memory["high"][float(data[2])] = str(data[0])
memory["low"][float(data[3])] = str(data[0])
# those are collecing data[2] and data[3] only between events when
# values changes from column F > J, to F < J, in that .csv file
then in the same "for line in file:", but different if:
LOW_num = min(memory["low"]) # it gets lowest number of all collected data[3] (Column D)
TOP_num = max(memory["high"]) # it gets biggest number of all collected data[2] (Column C)
#so TOP_num is for example: "1.555"
#but that TOP_num got day, month, and year attached to it as well:
#ex: memory["high"]["1.555"]["2022-04-05T08:34:39+02:00"]
TOP_data0 = str(memory["high"][TOP_num])
LOW_data0 = str(memory["low"][LOW_num])
i tried some things but, cant get it righ, example:
for i in memory["high"][i][j]:
if memory["high"][i][memory["high"][TOP_num][TOP_data0] < memory["low"][LOW_num]LOW_data0]:
print(memory["high"][i][TOP_num])
The .csv file represents some coin's price data ex: ADAUSDT frome exchange,
(time, open, high, low, close, somthing, somthing, somthing, somthing, somthing)
I finds Lowest price of given time period (Low_num), starting from some start price earlier.
And must find the biggest price between those start point and Low_num point.
That biggets price is the Stop loss numer had to be set, in order to achive the Lowest point for this example, it was a short.
figured out!
memory["SL"] = {}
for number in memory["high"]:
if number > LOW_num: # so its only numbers higher than Lowest obviously
x = number
if memory["high"][x] < LOW_data0: # and among them, with date only earlier than LOW_date0
memory["SL"][x] = str(memory["high"][x]) # and saving it to new memory set for later max() or min() upon it
Wow python can compare dates!
I'm working on trying to calculate the greatest increase/decrease in a change to profits/losses over time from a CSV.
The data set in csv is as follows (extract only):
Date,Profit/Losses
Jan-2010,867884
Feb-2010,984655
Mar-2010,322013
Apr-2010,-69417
So far, i've imported the csv file and added the items to a dictionary. Calculated total months, total profit/loss, calculated the change in profit/loss from month to month but now need to find the greatest and smallest change in the month and have the code return both the month and the change figure.
The output when trying to print the greatest increase/decrease returns only the final month on the list and all change values (instead of just the biggest change value and it's corresponding month)
Here is the code. Would appreciate any perspective:
budget = {}
total_months = 0
total_pnl = 0
date = 0
pnl = 0
monthly_change = []
previous_pnl = 0
greatest_increase = ["Date",[0]]
greatest_decrease = ["Date",[100000000000000]]
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
for row in csvreader:
date = 0
pnl = 1
budget[row[date]] = int(row[pnl])
for date, pnl in budget.items():
total_months = total_months + 1
total_pnl = total_pnl + pnl
pnlchange = pnl - previous_pnl
if total_months > 1:
monthly_change.append(pnlchange)
previous_pnl = pnl
if (monthly_change > greatest_increase[1]):
greatest_increase[1] = monthly_change
greatest_increase[0] = row[0]
if (monthly_change < greatest_decrease[1]):
greatest_decrease[1] = monthly_change
greatest_decrease[0] = row[0]
print(greatest_increase)
The primary problem is the final part of the code (the if statement). When I print 'greatest_increase' this currently returns the final value in the list rather than the highest value of change.
current output is:
[['Feb-2017', '671099'], [116771, -662642, -391430, 379920, 212354, 510239, -428211, -821271, 693918, 416278, -974163, 860159, -1115009, 1033048, 95318, -308093, 99052, -521393, 605450, 231727, -65187, -702716, 177975, -1065544, 1926159, -917805, 898730, -334262, -246499, -64055, -1529236, 1497596, 304914, -635801, 398319, -183161, -37864, -253689, 403655, 94168, 306877, -83000, 210462, -2196167, 1465222, -956983, 1838447, -468003, -64602, 206242, -242155, -449079, 315198, 241099, 111540, 365942, -219310, -368665, 409837, 151210, -110244, -341938, -1212159, 683246, -70825, 335594, 417334, -272194, -236462, 657432, -211262, -128237, -1750387, 925441, 932089, -311434, 267252, -1876758, 1733696, 198551, -665765, 693229, -734926, 77242, 532869]]
What i am trying to get is the bold value being the highest value (along with the relevant month)
Apologies if this isn't clear, I'm still fairly new (3rd week learning!)
I have a code that reads CSV file which has 3 columns: Zone, Number, and ARPU and I try to write a recommendation system that finds the best match for each value of ARPU from the list provided in the code (creates column "Suggested Plan"). Also, it finds the next greater value (creates column "Potential updated plan") and next lower value("Potential downgrade plan"):
tp_usp15 = 1500
tp_usp23 = 2300
tp_usp27 = 2700
list_usp = [tp_usp15,tp_usp23, tp_usp27]
tp_bsnspls_s = 600
tp_bsnspls_steel = 1300
tp_bsnspls_chrome = 1800
list_bsnspls = [tp_bsnspls_s,tp_bsnspls_steel,tp_bsnspls_chrome]
tp_bsnsrshn10 = 1000
tp_bsnsrshn15 = 1500
tp_bsnsrshn20 = 2000
list_bsnsrshn = [tp_bsnsrshn10,tp_bsnsrshn15,tp_bsnsrshn20]
#Common list#
common_list = list_usp + list_bsnspls + list_bsnsrshn
import pandas as pd
def get_plans(p):
best = min(common_list, key=lambda x : abs(x - p['ARPU']))
best_index = common_list.index(best) # get location of best in common_list
if best_index < len(common_list) - 1:
next_greater = common_list[best_index + 1]
else:
next_greater = best # already highest
if best_index > 0:
next_lower = common_list[best_index - 1]
else:
next_lower = best # already lowest
return best, next_greater, next_lower
`common_list = list_usp + list_bsnspls + list_bsnsrshn
common_list = sorted(common_list) # ensure it is sorted
df = pd.read_csv('root/test.csv')
df[['Suggested plan', 'Potential updated plan', 'Potential downgraded plan']] = df.apply(get_plans, axis=1, result_type="expand")
df.to_csv('Recommendation System.csv') `
It creates 3 additional columns and does the corresponding task (best match or closes value, next greater value, and next smaller value).The code works perfectly but as you can see each numeric value has its name
How to change the code to create additional columns with name next to new columns with numeric values?
For example, right now code produces:
Zone, Number, ARPU, Suggested plan, Potential Updated Plan, and Potential downgrade plan
!BUT! I need to create:
Zone, Number, ARPU, Suggested plan (numeric), Suggested plan (name), Potential Updated Plan(numeric), Potential Updated Plan(name), Potential downgrade plan (numeric),Potential downgrade plan(name)
Where columns with (name) will show the corresponding name to the value used in (numeric) columns. Thanks in advance, guys!
Photo examples:
Here is the starting CSV file.
Then, after executing the code I have this:
And I want to create additional columns with corresponding names of valuables. Example columns in in yellow
Here is my code:
with open('life-expectancy.csv') as file:
for row in file:
row = row.strip() #trim
parts = row.split(',')
value = float(parts[3])
max_value = float(-1.0)
if value > max_value:
max_value = value
min_value = float(100.0)
if value < min_value:
min_value = value
# print(sum(value))
print(max_value)
print(min_value)
The life expectancy file contains rows that are all like this:
Afghanistan,AFG,1981,43.923
With different countries, years, etcetera. My goal is to find the highest and lowest life expectancy with the corresponding country and year, but my code is just giving me the life expectancy of the last item in the list (I haven't attempted to add the country and year yet obviously).
What am I missing?
Move the max_value = float(-1.0) and min_value = float(100.0) above the with statement. This way you reset it on each line.
import os
myFilePath = os.getcwd()
print(myFilePath)
calls = open('/Users/fake/Desktop/fakefolder/calls.txt')
mondayCalls = []
for adding in calls.readlines():
mondayCalls.append(adding.strip())
calls.close()
print(mondayCalls)
Here is the list that I generated from a txt file, I just want to add the total for all mondays, tuesdays etc. I would want to print
Monday = 29
Tuesday = 16 etc
The list is longer but here is an example of the list that I have.
['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
Try this (explanation in code comments):
list = ['Monday:21', 'Tuesday:6', 'Wednesday:8', 'Thursday:18', 'Friday:16', 'Saturday:4', 'Sunday:10', 'Monday:8']
# create a dictionary variable
days_dict = {}
# for every entry in the list
for entry in list:
# split entry by ":" and take the first part of the entry
day = entry.split(":")[0]
# split entry by ":" and take the second part of the entry and convert it to an integer
count = int(entry.split(":")[1])
print (day)
print (count)
# if the day key is in the dictionary add to its count else create the key
if day in days_dict:
days_dict[day] += count
else:
days_dict[day] = count
print (days_dict)
# print Monday's count
print ('Monday Count = ' + str(days_dict['Monday']))
It is possible with splitting and then recording values in a dictionary. You can iterate through the list and store the values in a dictionary where the key of the dictionary is the day. Pseudo code below:
record = {}
for entry in list:
day = get_day(entry)
val = get_val(entry)
if day in record:
record[day] += val
else:
record[day] = val
Then your final record_dict will contain the values you want for each day.