Python Forum
New with Python. Help with a code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New with Python. Help with a code
#11
Ok I have got it. I solved the second question.....it depends on the indentation where I put the code.
What about the first question? Is it possible to put all the result in a text file?
Reply
#12
(Apr-23-2023, 04:08 PM)Gribouillis Wrote:
(Apr-23-2023, 03:43 PM)jasonkeller1970 Wrote: There is a way to get all the results in a text file?
This code will write all the results in a comma-separated values file named 'output.csv' that you can open with a spreadsheet application.
import csv
import itertools as itt

def generate_results():
    for a, b, c, d, e, f, g, h, l in itt.product(
        range(1, 4), range(1, 6), range(5, 8), range(1, 5), range(5, 8),
        range(5, 8), range(1, 10), range(1, 3), range(1, 4)):
        result = ((c**2+a*f+d**2+b*g)*(d**2+a*h+e**2+b*l)
                -(c*d+a*g+d*e+b*h)**2)
        yield [a, b, c, d, e, f, g, h, l, result]


with open('output.csv', 'w') as csvfile:
    fieldnames = 'a b c d e f g h l r'.split()
    writer = csv.writer(csvfile)
    writer.writerow(fieldnames)
    for item in generate_results():
        writer.writerow(item)
The value -233 is in the output file.

Everything is perfect now! Thank you!
Reply
#13
Good morning,
The code I have got is helping me a lot. I would like to know if it can help me in the next phase. Is it possible with the instruction input that I can write a variable string that is added to the expression and then evaluated?
I tried it but obviously It doesn't work because my input is a string with letters and the code use it in a mathematical expression. Maybe I was not so clear to explain the problem, so I copy the code (that doesn't work) to make it clearer

x = input('Insert the binomial: ')
for a in range(1, 4):
    for b in range(1, 6):
        for c in range(5, 8):
            for d in range(1, 5):
                for e in range(5, 8):
                    S = (a**2-2*a*b+2*b**2-2*b*d+c**2-2*c*e+d**2+e**2)
                    T = S - x**2
                    if T<0:
                        print("a =", a, "b =", b, "c =", c, "d =", d, "e =", e, "x =", x, "S =", S, "T =", T)
When the code is launched I would like to write the input, for instance a-b and get the eventual negative results of T after evaluation. Is it possible?
Reply
#14
(May-03-2023, 06:25 AM)jasonkeller1970 Wrote: Is it possible?
Yes it is. Try something like this
import itertools as itt

def multirange(*args):
    return itt.product(*(range(*v) for v in args))

expr = input('Insert the binomial: ').strip()
expr_func = eval(f'lambda a, b, c, d, e: {expr}')


for a, b, c, d, e in multirange((1, 4), (1, 6), (5, 8), (1, 5), (5, 8)):
    x = expr_func(a, b, c, d, e)
    print(a, b, c, d, e, x)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020