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.
importitertoolsN,S=map(int,input().split())# N, S = 3, 9defformat_solution(outers,inners):s=''foriinrange(len(outers)):s+=str(outers[i])+str(inners[i])+str(inners[(i+1)%len(outers)])returnsdefcheck_solution(outers,inners,S):returnall(map(lambdaa,b,c:a+b+c==S,outers,inners,inners[1:]+inners[0:1]))defgenerate_solutions(N,S):outer_candidates=[set(combo)forcomboinitertools.combinations(range(1,2*N+1),N)ifsum(combo)==N*(4*N+2-S)]solutions=[]defcomplete(sol_outers,sol_inners,outers,inners):fornew_outerinouters:new_sol_outers=sol_outers+[new_outer]new_outers=outers-set([new_outer])new_inner=S-new_outer-sol_inners[-1]ifnew_innerininners:new_sol_inners=sol_inners+[new_inner]new_inners=inners-set([new_inner])ifnew_inners==set([]):new_sol_outers.append(list(new_outers)[0])ifcheck_solution(new_sol_outers,new_sol_inners,S):solutions.append(format_solution(new_sol_outers,new_sol_inners))returncomplete(new_sol_outers,new_sol_inners,new_outers,new_inners)foroutersinouter_candidates:inners=set(range(1,2*N+1))-outersa=min(outers)outers.remove(a)forbininners:new_inners=inners.copy()new_inners.remove(b)c=S-a-bifcinnew_inners:new_inners.remove(c)complete([a],[b,c],outers,new_inners)returnsorted(solutions)solutions=generate_solutions(N,S)forsolutioninsolutions:print(solution)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #68: Magic N-gon ring
You are viewing a single comment's thread. Return to all comments →
python 100%