簡體   English   中英

使用 numpy 找到由兩個 3 位數的乘積組成的最大回文

[英]Find the largest palindrome made from the product of two 3-digit numbers using numpy

當我嘗試使用 numpy package 解決這個問題時,我陷入了這個問題。我的想法是,我將乘以並保留我對 100 到 999 之間的 3 位數字所做的所有計算的列表,然后檢查列表以查看哪些是回文並保存它們。 最后,我將對列表進行排序並獲得最大的回文。 下面的代碼顯示了我試圖做的事情。

import numpy as np

def void():
    list1 = np.array(range(100,999))
    list2 = np.array(range(100,999))
    k = []
    
    for i,j in zip(list1,list2):
        k.append(np.multiply(list1,list2))
        
    b = []
    
    for x in range(0,len(k)):
        if(reverseNum(k[x])==k[x]):
            b.append(k[x])
            
    print(b)
    print(b[-1])
    
def reverseNum(num):
    rev = 0
    
    while(num>0):
        rem = num % 10
        rev = (rev*10) +rem
        num = num // 10
        
    return rev  
    
void()

但是,當我嘗試檢查列表中的數字是否為回文時,出現以下錯誤:

Traceback (most recent call last):                                                                                    
  File "main.py", line 40, in <module>                                                                                
    void()                                                                                                            
  File "main.py", line 22, in void                                                                                    
    if(reverseNum(k[x]),k[x]):                                                                                        
  File "main.py", line 31, in reverseNum                                                                              
    while(num>0):                                                                                                     
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()  

這是否意味着無法使用 numpy 作為解決此問題的方法? 如果是,我哪里錯了?

編輯:到目前為止我已經嘗試過的(因為它被問到):根據錯誤消息,我嘗試使用np.equalnp.greater而不是檢查if(reverseNum(k[x])==k[x])num>0但它給出了相同的錯誤。

假設結果有六位數字的 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

您的問題源於您的線路,包括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()

為什么它必須使用 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)

另一個真正的 NumPy 解決方案,使用您的方式反轉數字(主要通過使用錯誤消息中建議的.any()修復它,您固執地拒絕嘗試)。

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),但它更安全。 否則五位數的乘積不能正確反轉,比如 101*102=10302 變成 203010 而不是 20301。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM