4 回答

TA貢獻1883條經(jīng)驗 獲得超3個贊
假設結果有六位數(shù)的 NumPy 方法(它不能有更多,因為 999 2是 998001):
import numpy as np
v = np.arange(100, 1000) # the range of three-digit numbers
a = np.outer(v, v) # all the products
print(a[(a // 100000 == a % 10) & # first digit == sixth digit
(a // 10000 % 10 == a // 10 % 10) &
(a // 1000 % 10 == a // 100 % 10)].max())
版畫906609。
使用純 Python 進行雙重檢查:
>>> max(x*y
for x in range(100, 1000)
for y in range(100, 1000)
if str(x*y) == str(x*y)[::-1])
906609

TA貢獻1839條經(jīng)驗 獲得超15個贊
另一個真正的 NumPy 解決方案,使用您的方式反轉數(shù)字(主要是按照.any()錯誤消息中的建議修復它,您固執(zhí)地拒絕嘗試)。
v = np.arange(100, 1000)
a = np.outer(v, v)
num = a.copy()
rev = num * 0
while (m := num > 0).any():
rev[m] = rev[m] * 10 + num[m] % 10
num[m] //= 10
print(a[rev == a].max())
沒有面具m你會得到相同的結果 (906609),但它更安全。否則五位數(shù)的乘積不能正確反轉,比如 101*102=10302 變成 203010 而不是 20301。

TA貢獻1864條經(jīng)驗 獲得超6個贊
為什么它必須使用 numpy?
# test if palindrome based on str
def is_palindrome(number: int):
converted_to_string = str(number)
return converted_to_string == converted_to_string[::-1]
# product of two three-digit numbers
you_right = []
values = []
for x in range(999, 99, -1):
for y in range(999, 99, -1):
product = x*y
if is_palindrome(product):
values.append((x, y))
you_right.append(product)
winner = you_right.index(max(you_right))
print(values[winner])
# output
(993, 913)

TA貢獻1845條經(jīng)驗 獲得超8個贊
您的問題源于您的行,包括zip. 我下面的代碼并不漂亮,但嘗試松散地遵循您的方法。
import numpy as np
def void():
list1 = np.array(range(100,1000)) # you want to include '999'
list2 = np.array(range(100,1000))
k = []
for i,j in zip(list1,list2):
k.append(np.multiply(list1,j))
b = []
for r, row in enumerate(k):
for c, cell in enumerate(row):
if reverseNum(cell)==cell:
b.append(cell)
print(b)
print(max(b))
def reverseNum(num):
rev = 0
while(num>0):
rem = num % 10
rev = (rev*10) +rem
num = num // 10
return rev
void()
添加回答
舉報