Python: How To Multiply Each Value In A List Against All The Values In Another List
Solution 1:
You need to use nested loop
x = []
y = []
products = []
palindromes = []
for i in range(10, 100):
x.append(i)
# print(x)
for i in range(10, 100):
y.append(i)
# print(y)
for i in range(len(y)):
for j in range(len(x)):
products.append(x[j] * y[i])
for i in range((len(products)-1)):
a = str(products[i])
b = tuple(a)
c = b[::-1]
if b == c:
print('palindrome found!', a)
print('b value:', b)
print('c value:', c)
palindromes.append(a)
solutions = list(map(int, palindromes))
solutions.sort()
print(solutions)
This is called the nested loop. Variable i is iterating for length of y minus 1 and variable j is iterating for length of x minus 1.
Solution 2:
There's no need to do
for i in range(10, 100):
x.append(i)
You can make a list from a range
object like this:
x = list(range(10, 100))
However, there's no need to make those x
and y
lists. You can create a list of the products by iterating directly over the ranges. For example:
products = []
for x in range(10, 100):
for y in range(10, 100):
products.append(x * y)
To make a list just containing the palindromes:
defis_palindrome(n):
s = str(n)
return s == s[::-1]
products = []
for x inrange(10, 100):
for y inrange(10, 100):
n = x * y
if is_palindrome(n):
products.append(n)
You can then do max(products)
to find the highest palindrome that is the product of two two-digit numbers.
Here's a more compact way, using a generator expression, so it doesn't need to build a list:
r = range(10, 100)
print(max(filter(is_palindrome, (x * y for x in r for y in r))))
Solution 3:
Your for loop is equivalent to this:
products=[i*j for i in x[:-1] for j in y]
Solution 4:
You can use Kaushal Kumar Singh's solution, or here are two other solutions. However, in programming there is no universal solution, a lot of solutions can co-exist.
Code 1:
products = [i * j for i, j in zip(x, y)]
Code 2:
from operator import mul
products = list(map(mul, x, y))
Post a Comment for "Python: How To Multiply Each Value In A List Against All The Values In Another List"