Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

python - How to improve my slow nested for loops with itertools?

My Code for a Codewars Problem is just way too slow, after some research it seems I have to use itertools product BUT I can't figure out a way how

Right now this is my code, which does work but as said way too slow.

def list_squared(m, n):
  results = []
  for i in range (m, n):
     sum = 0
     for j in range (1, i+1):
         if i % j == 0:
             sum += j**2
     if int(sum**(1/2))**2 == sum: #checking if number is a perfect square number
             results.append([i, sum])
  return results

How do I use the prodcut function from itertools here in this case ?

EDIT: Some Examples:

list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]

list_squared(42, 250) --> [[42, 2500], [246, 84100]]

I should get a list like that. Given my input of two integers m, n (1 <= m <= n) I want to find all integers between m and n whose sum of squared divisors is itself a square.

For Example: Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

question from:https://stackoverflow.com/questions/65947902/how-to-improve-my-slow-nested-for-loops-with-itertools

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If "sum**(1/2)" means "square root of sum", it is probably being translated automagically into something like exp((1/2)*log(sum)), which is going to eat you alive. For breakfast. Without salt.

The modulo operation i % j is probably not helping, but that's most certainly a few mosquito bites after the wolves get finished with you.

This is one of those times where you have to take a long, hard look at your algorithm.

Start by observing that the set of perfect squares <= n, for all non-trivial, is very much smaller than the set of integers <= n.

(HINT: 1, 4, 9, 16, 25, 36, 49, 64, ... as opposed to 1, 2, 3, ..., 64, ...)

I'd also look at the way I was generating the j values. Those appear at first glance to be factors of the i values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...