Python Forum

Full Version: Multiplying between two values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need an equation in Python that gives me the values ​​that can be multiplied, since they must be less than 10. Only they must have one decimal place before, like 0.1. That's what I'm having a problem for coding.

For example: T = x . y

x = [1,2,3,4,5] and y = [10,5,3.33,2.5,2]
I don't understand what you're asking for. Can you demonstrate what the answer would be for your example?
And almost noneof your products are less than 10, most are equal to 10
a=x
b=y
T=a.b
Do x . y but T < 10 and show one list for x values and other list for y values. Both x and y can have one decimal place. I'm sorry for my explanation.
>>> [(xitem, yitem) for xitem in x for yitem in y if xitem * yitem < 10]
[(1, 5), (1, 3.33), (1, 2.5), (1, 2), (2, 3.33), (2, 2.5), (2, 2), (3, 3.33), (3, 2.5), (3, 2), (4, 2)]
Or if you didn't want to roll the loop yourself, you could use product and operator modules...

>>> from itertools import product
>>> from operator import mul
>>> [p for p in product(x,y) if mul(*p) < 10]
[(1, 5), (1, 3.33), (1, 2.5), (1, 2), (2, 3.33), (2, 2.5), (2, 2), (3, 3.33), (3, 2.5), (3, 2), (4, 2)]
There are so few numbers that brute force is still pretty efficient. Since you cannot iterate with floats I just multiply everything times 10 and test every number from 1 (0.1x10) to 100 (10x10) to see if it is a factor of 100.
factors = [x/10 for x in range(1, 101) if (100 / x) % 1 == 0]
print(factors)
For a larger range you can speed thing up by only testing numbers from 0.1 to the square root of the value and using these to compute the "upper" factors.
Quote:I need an equation in Python that gives me the values ​​that can be multiplied, since they must be less than 10.

List comprehension with a conditional which uses the named assignment expression:
x_values = [1,2,3,4,5]
y_values = [10,5,3.33,2.5,2]

xy_values = [value / 10 for x, y in zip(x_values, y_values) if (value := x * y) < 10]
To understand the list comprehension a bit better, here the multiline version:

xy_values = [
    value / 10 for x, y
    in zip(x_values, y_values)
    if (value := x * y) < 10
]
Of course, you can use a naive for-loop to solve it and you don't have always the latest Python version available (walrus operator).

xy_values = []
for x, y in zip(x_values, y_values):
    xy = x * y
    if xy < 10:
        xy_values.append(xy / 10)
The walrus operator was used in the if-statement:

xy_values = []
for x, y in zip(x_values, y_values):
    if (xy := x * y) < 10:
        xy_values.append(xy / 10)
If you play with the factor, you can get more values. I get only one float as result.
Output:
[0.999]
I am very grateful to everyone who helped me. All the answers are of great value for me to solve my problem with the code!