Title: A better way of doing this evaluation in Python
Tags: python;list;evaluation
Question: I have function that delivers a List with a single element of the form ax+b where a and b are (multi)digit characters and there is exactly one 'x'.
I then swap the x for a number and use eval on the result.
For example with the single element [64/243*x - 283/243] I apply
new_word=words.replace('x','7')
to get [64/243*7 - 283/243]
which I then evaluate
z=eval(new_word)
What I want to achieve is a loop where  I put various numbers in for 'x', with different List elements.
Before I do that, is there a better/slicker/faster way of evaluating something like  [64/243*x - 283/243] for different values of 'x' other than  using eval?
Or point me to the Old Question that you think is an answer to my question.
Comment: is there any reason to keep it as a list? seems much easier if it's just an expression. then you can evaluate it in a list comprehension for various values of `x`: `[64/243*x - 283/243 for x in (7,8)]`

Comment: No, how do I convert it to an expression?

Here is the accepted answer: You could generate a class that can display and evaluate a linear expression:
from fractions import Fraction
from random import randint
class Linear:
def __init__(self):
self.a = Fraction(randint(0, 10), randint(1, 10))
self.b = Fraction(randint(0, 10), randint(1, 10))
self.func = lambda x: self.a*x + self.b
def __repr__(self):
return f'Linear(a={self.a}, b={self.b})'
def __str__(self):
return f'{self.a}*x+{self.b}'
def __call__(self,x):
return self.func(x)
eq = Linear()
print(repr(eq))
for x in range(1,6):
print(f'{eq} where x={x} =&gt; {eq(x)}')
Output:
Linear(a=3/5, b=4/5)
3/5*x+4/5 where x=1 =&gt; 7/5
3/5*x+4/5 where x=2 =&gt; 2
3/5*x+4/5 where x=3 =&gt; 13/5
3/5*x+4/5 where x=4 =&gt; 16/5
3/5*x+4/5 where x=5 =&gt; 19/5
Comment for this answer: I will give that a go.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:02/07/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><list><evaluation>', 'Title': 'A better way of doing this evaluation in Python', 'ViewCount': 54, 'id': 71015358, 'user_AboutMe': '<p>Just starting out on the Stanford Uni IOs course.\nI have slowly worked my way through. </p>\n\n<p>I really recommend the companion text by Daniel Steinberg. It is excellent.\nHe explains things clearly and shows both simple and sophisticated examples of how to do thing.</p>\n\n<p>For example enumerating an array he shows a way that is straightforward loop, then fast enumeration and finally using blocks. (The recommended way).</p>\n\n<p>Far too often C, C++ &amp; objective C programmers couch their answer in deeply embedded single line solutions that are horrible for readers to unpick.</p>\n', 'user_AccountId': 1734416.0, 'user_DisplayName': 'nerak99', 'user_Reputation': 630.0, 'user_Views': 95.0, 'user_id': 1587308.0}}