How to calculate average from webelement list? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 14 days ago.
The community is reviewing whether to reopen this question as of 14 days ago.
Improve this question
I chose the price list from WebElements. How can I calculate the price average?
I try use len() and sum() but it's not working.
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
value = i.text
print(value)
output:
€4.44
€3.32
€3.93
€3.78
€4.06
Edit.
I find WebElement list using a CSS selector:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
This element list have 5 prices:
€4.44
€3.32
€3.93
€3.78
€4.06
I want to calculate average prices but I can't because this is WebElement List. I tried to extract this number without € by decimals:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
value_price = i.text
value = Decimal(sub(r'[^\d.]', '', value_price))
print(value)
Output:
4.44
3.32
3.93
3.78
4.06
And now I want to calculate average this numbers:
price = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
for i in price:
value_price = i.text
value = Decimal(sub(r'[^\d.]', '', value_price))
print(value)
avg = sum(value)/len(value)
print(avg)
Output:
Traceback (most recent call last):
File "C:\Users\sokal\PycharmProjects\pythonProject1\login_sorare.py", line 56, in <module>
avg = sum(value)/len(value)
^^^^^^^^^^
TypeError: 'decimal.Decimal' object is not iterable
I'm not sure what's wrong because I can't use sum()/len().

sum() and len() are expecting a list but you are passing in just one value. That's why you are getting the object is not iterable error. There are a number of ways you can do this. One way is to take your existing code, add each .text value to an array, and then use sum() and len() to calculate the average.
price_elements = browser.find_elements(by=By.CSS_SELECTOR, value="p.sc-gKPRtg.sc-cTVMo.gFSBHP.dJSocd")
text_prices = [price_element.text for price_element in price_elements]
prices = [float(text_price.replace('€', '')) for text_price in text_prices]
average = sum(prices)/len(prices)
print(average)
...and it prints
3.9059999999999997

Related

How to convert list of strings into floats? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the list of data:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
I need to convert it into float in order to calculate the average and etc.
I've tried:
list(map(float, rfd_per_neihborhood_15))
list(np.float_(rfd_per_neihborhood_15))
for item in list:
float(item)
a = rfd_per_neihborhood_15
floats = []
for element in a:
floats.append(float(element))
print(floats)
Nothing is working, it's throwing ValueError: could not convert string to float: '-'
The problem could be that there is an element in your list which has a - (hyphen). To tackle that, you can use try-except in the following manner:
rfd_per_neihborhood_15 = ['75.8','108.5','76.6','96.4','104.8','95.8','165.8','128.9','4-4']
def safe_float(x):
try:
return float(x)
except:
print(f"Cannot convert {x}")
#Returning a 0 in case of an error. You can change this based on your usecase
return 0
list(map(safe_float, rfd_per_neihborhood_15))
Output:
Cannot convert 4-4
[75.8, 108.5, 76.6, 96.4, 104.8, 95.8, 165.8, 128.9, 0]
As you can see, my code gracefully handled the exception and returned a 0 in place of the last element '4-4'. Alternatively, you could also return a NaN.
You could try this:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
# shortening the name to r_pn15
r_pn15 = rfd_per_neihborhood_15
floated_list = []
for item in r_pn15:
r_pn15.append(float(item))
print(floated_list)

Calculate the percentage growth from two values in a txt/csv file (Python) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a file "Dow.txt" formated as follows: name, symbol, exchange, industry, value0, value1, value2, value3 for each of the 30 stocks in the Dow Jones Industrial Average.
How can I determine the best and worst-performing stocks in 2013 with regards to percentage growth? The possible outcome as shown below:
Best performing stock: stock name, percentage of growth
Worst performing stock: stock name, percentage of growth
I don't know how to tell the program to know which is the start price and which is the end price, so I don't know how to begin with the calculation.
So the tasks are:
read file
get values of the columns
calculate percentage difference
output the result
the file link as below:
https://drive.google.com/file/d/107pPSYgSrjEVdqR7QZW1W2l6QP8n-18g/view?usp=sharing
Here's one possible solution without using any imports:
def lines(file: str):
with open(file) as f:
for line in f:
yield line
def parse(lines):
for line in lines:
yield line.split(",")
def get_percentage_growth(path):
line = lines(path)
best = {"name": None, "percentage": float('-inf')}
worst = {"name": None, "percentage": float('inf')}
for row in parse(line):
first, second = float(row[4]), float(row[5])
percentage = (second-first)/first * 100
if percentage > best["percentage"]:
best["name"] = row[0]
best["percentage"] = percentage
if percentage < worst["percentage"]:
worst["name"] = row[0]
worst["percentage"] = percentage
return best, worst
if __name__ == '__main__':
f = "data.txt"
b, w = get_percentage_growth(f)
print(f'Best performing stock: {b["name"]}, {b["percentage"]}')
print(f'Worst performing stock: {w["name"]}, {w["percentage"]}')
assuming that the python file is located in the same directory as the data.txt file, this hsould work. The benefit is that this method is able to deal with files of TB due to the generators.

How could I print the highest score and name of student grades using python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using python I'm creating a code that receives a list of lists as parameter. This list of lists contains names and grades of students. The function also must print the name of the student with the best grade and its best grade. When I created the code and try to run it nothing occurs is there a way to improve my code? My desired output would be "The best student is: Caroline with a 9.6"
students=[["steve", 9.0], ["ben", 9.5], ["Caroline",9.6],["Tim", 9.1]]
highest_grade=[]
lowest_grade=[]
def best():
i = 1
max = min = students[0]
# first, calculate the max and min.
while i < len(students): # (possible improvement: replace this with a for loop)
if students[i] > max:
max = students[i] # replace max with the new max
if students[i] < min:
min = students[i] # replace min with the new min
i += 1
highest_grade.append(max)
lowest_grade.append(min)
print("The best student is:",best())
There are a few things you could do to improve it. You find the min score but don't use it, so I'm not sure if you need it. If you do need it, you could add it to your return statement. Here's a suggested way to do it that should be easy to follow:
students = [["steve", 9.0], ["ben", 9.5], ["Caroline", 9.6], ["Tim", 9.1]]
def best(students):
highest_grade_name = None
lowest_grade_name = None
my_max_score = -float("inf")
my_min_score = float("inf")
for name, score in students:
if score > my_max_score:
my_max_score = score
highest_grade_name = name
if score < my_min_score:
my_min_score = score
lowest_grade_name = name
return my_max_score, highest_grade_name
best_name, best_score = best(students)
print(f"The best student is {best_name} with a score of {best_score}")
max(students,key=lambda x:x[1])
I think would work
There could be quite a few improvements to this piece of code. Firstly, it would be far better if the students array was a dict, but it's understandable if it absolutely has to be an array of arrays.
Secondly, you're right, you should do this with a for loop:
def best_student_grade():
highest_grade = 0 # "max" is a terrible name for a variable
for student, grade in student:
if grade > highest_grade:
grade = highest_grade
best_student = student
return highest_grade, best_student
bstudent, bgrade = best_student_grade()
print(f"The best student is: {bstudent} with a {bgrade}")
You could even do this with a list comprehension, but I will leave that as an exercise to the reader.
In all honesty, I think it would benefit you in a lot of ways to read some introductory python or programming books.

struggling with python homework [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I got a .txt file with some lines in it:
325255, Jan Jansen
334343, Erik Materus
235434, Ali Ahson
645345, Eva Versteeg
534545, Jan de Wilde
345355, Henk de Vries
Write a program that starts with opening the file kaartnummers.txt
Determine the number of lines and the largest card number in the file. Then print these data.
my code isnt finished yet but i tried atleast!:
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
print(len(content))
for i in content:
print(i.split())
kaartinfo()
I know that my program opens the file and counts the number of lines in it.. all after that is wrong <3
I can't figure out how to get the max number in the list.. Please if you got an answer use simple readable Python Language.
I'm not good at python, and there are probably much more elegant solutions, but this is how I would do it. Some may say this is like C++/Java in python, which many tend to avoid.
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
for i in content:
value = i.split(',')
value[0] = int(value[0])
lst.append(value)
return lst
Use the kaartinfo() function to retrieve a list
my_list = kaartinfo()
Assume first value is the maximum
maximumValue = my_list[0][0]
Go through every value in the list, check if they are greater than the current maximum
# if they are, set them as the new current maximum
for ele in my_list:
if ele[0] > maximumValue:
maximumValue = ele[0]
when the above loop finishes, maximum value will be the largest value in the list.
#Convert the integer back to a string, and print the result
print(str(maximumValue) + ' is the maximum value in the file!')
This should be enough to do the job:
with open('kaartnummers.txt', 'r') as f:
data = f.readlines()
print('There are %d lines in the file.' % len(data))
print('Max value is %s.' % max(line.split(',')[0] for line in data))
Given the input file you provided, the output would be:
There are 6 lines in the file.
Max value is 645345.
Of course, you can put it in a function if you like.

Python, have an error message i keep receiving [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In my code:
def get_drink_price (drink):
int 0.75 == "Coke"
if get_drink_price("Coke"):
return Coke
# This is just to see what prints
print get_drink_price("Coke")
I keep getting this error message:
File "<stdin>", line 2
int 0.75 == "Coke"
^
SyntaxError: invalid syntax
What's that?
...because that isn't valid Python syntax. You have the following problems:
You should use int(n) to turn n into an integer. int on its own isn't valid (hence the SyntaxError) - you could define a variable called int, (e.g. int = 1) but that uses a single equals sign and should never be done, as you shadow the built-in int();
0.75 == "Coke" is a boolean comparison, not any kind of assignment (and will never be True);
You keep recursively calling get_drink_price with no way to return; and
Coke is never defined, so return Coke would cause a NameError anyway.
It is completely unclear what you are trying to achieve with that function, but maybe:
def get_drink_price(drink):
drinks = {'Coke': 0.75, 'Orange': 0.6} # dictionary maps drink to price
return drinks[drink] # return appropriate price
Now
>>> get_drink_price("Coke")
0.75
Perhaps closer to what you were trying to do:
def get_drink_price(drink):
Coke = 0.75 # define price for Coke
if drink == "Coke": # test whether input was 'Coke'
return Coke # return Coke price
but you should be able to see that the dictionary-based implementation is better.
I have a feeling that the code you are looking to create should be done something more like this:
def get_drink_price(drink):
prices = { "Coke":0.75, "Pepsi":0.85}
return prices[drink]
print get_drink_price("Coke")
The prices object in the function is just a dictionary, which is a standard python object. You can look up more information about dictionaries here: http://docs.python.org/2/tutorial/datastructures.html#dictionaries, but if what you're looking to do is find the price of a drink from its name, this is a simple, straightforward approach.

Categories

Resources