We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This times out whenever difference is 1.
(Ignore the main)
frommathimport*# Returns a congruence class of a specified modulus and residue,# constrained in [lower, upper]defcongruence_class(residue,modulus,lower,upper,order='asc'):residue=residue%modulusstrict_lower=(lower//modulus)*modulus + residueifstrict_lower<lower:strict_lower+=modulusstrict_upper=(upper//modulus)*modulus + residueifstrict_upper>upper:strict_upper-=modulusiforder=='asc':returnrange(strict_lower,strict_upper+1,modulus)eliforder=='desc':returnrange(strict_upper,strict_lower-1,-modulus)# Returns true if any consecutive sequence of numbers# in the desc sorted array adds up to targetdefis_consecutive_sum(desc_array,start,end,target):#print("desc_array [{0}:{1}] = {2}".format(start, end, desc_array[start:end]))if(end-start)<=1:returnFalseresult=sum(desc_array[start:end])ifresult==target:returnTrueelifresult>target:return\
is_consecutive_sum(desc_array,start,end-1,target)\
or\
is_consecutive_sum(desc_array,start+1,end,target)else:returnFalse# Checks every congruence class defis_palindrome_sum_of_squares(number,difference):limit=int(sqrt(number))#Thelimitcanbeoptimized?foriinrange(0,difference):AP=congruence_class(i,difference,1,limit,'desc')squaredAP=list(map(lambdax:x*x,AP))ifis_consecutive_sum(squaredAP,0,len(squaredAP),number):returnTrue# Generator to yield palindromes defgenerate_palindromes(start,stop,step=1):forxinrange(start,stop,step):ifstr(x)==str(x)[::-1]:yieldx# What the problem actually requiresdefsum_of_desired_palindromes(number,difference):palindrome_sums=0foriingenerate_palindromes(1,number+1):ifis_palindrome_sum_of_squares(i,difference):palindrome_sums+=ireturnpalindrome_sumsif__name__=="__main__":print(sum_of_desired_palindromes(10,1))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #125: Palindromic sums
You are viewing a single comment's thread. Return to all comments →
This times out whenever difference is 1. (Ignore the main)