使用Python,我试图解决问题#4的项目欧拉问题.有人可以告诉我我做错了什么吗?问题是找到由两个3位数字的乘积制成的最大回文.这是我到目前为止所拥有的.
import math def main(): for z in range(100, 1000): for y in range(100, 1000): for x in range(1, 1000000): x = str(x) if x == x[::-1] and x == z*y: print x if __name__ == '__main__': main()
Gregg Lind.. 10
一些效率问题:
从顶部开始(因为我们可以在跳过大量计算时使用它)
不要重复计算
def is_palindrome(n): s = str(n) return s == s[::-1] def biggest(): big_x, big_y, max_seen = 0,0, 0 for x in xrange(999,99,-1): for y in xrange(x, 99,-1): # so we don't double count if x*y < max_seen: continue # since we're decreasing, # nothing else in the row can be bigger if is_palindrome(x*y): big_x, big_y, max_seen = x,y, x*y return big_x,big_y,max_seen biggest() # (993, 913, 906609)
David Z.. 9
尝试从z和y的乘积计算x,而不是检查从1到100的每个数字.想一想:如果你被要求计算500*240,哪个更有效 - 乘以它们,或从1开始计算直到你找到正确的答案?
一些效率问题:
从顶部开始(因为我们可以在跳过大量计算时使用它)
不要重复计算
def is_palindrome(n): s = str(n) return s == s[::-1] def biggest(): big_x, big_y, max_seen = 0,0, 0 for x in xrange(999,99,-1): for y in xrange(x, 99,-1): # so we don't double count if x*y < max_seen: continue # since we're decreasing, # nothing else in the row can be bigger if is_palindrome(x*y): big_x, big_y, max_seen = x,y, x*y return big_x,big_y,max_seen biggest() # (993, 913, 906609)
尝试从z和y的乘积计算x,而不是检查从1到100的每个数字.想一想:如果你被要求计算500*240,哪个更有效 - 乘以它们,或从1开始计算直到你找到正确的答案?