fork download
  1. #from sympy import*
  2. import re
  3.  
  4. def isprime(n):
  5. return all(n%i for i in range(2,int(n**.5)+1))
  6.  
  7. def tree(n,hs=(0,)):
  8. if isprime(n):return str(n)
  9. A=max(z for z in range(1,int(n**.5)+1)if n%z<1)
  10. B=n//A
  11.  
  12. x=tree(A)
  13. y=tree(B)
  14. xs=[i for i in range(len(x))if re.match('^[0-9 ]+$',x[i])]
  15. ys=[j for j in range(len(y))if re.match('^[0-9 ]+$',y[j])]
  16. ht=max(xs,ys)
  17. hv=hs[1:]or[k[1]-k[0]for k in zip(ht[:-1],ht[1:])]
  18. x=tree(A,hv)
  19. y=tree(B,hv)
  20.  
  21. p=x[0][::-1].index(str(A)[-1])+1-(len(str(A))>1)
  22. q=y[0].index(str(B)[0])+1-(len(str(B))>1)
  23. h = hs[0]or 2-(p+q-len(str(n)))%2
  24.  
  25. # while spacing is too small
  26. incorrect_spacing = True
  27. while incorrect_spacing:
  28. h+=2
  29. R=[]
  30. z=[]
  31. for i in range(ht[-1]+1):
  32. a=i<len(x)and x[i]or" "*len(x[0])
  33. b=i<len(y)and y[i]or" "*len(y[0])
  34. R+=a+" "*h+b,
  35. if i in ht:z+=a+" "*h+b,
  36. incorrect_spacing=not all(re.match('(\d| +)*$',s)for s in z)
  37.  
  38. # until spacing is too small
  39. correct_spacing = True
  40. while correct_spacing and h>-1:
  41. h-=2
  42. R=[]
  43. z=[]
  44. for i in range(ht[-1]+1):
  45. a=i<len(x)and x[i]or" "*len(x[0])
  46. b=i<len(y)and y[i]or" "*len(y[0])
  47. R+=a+" "*h+b,
  48. if i in ht:z+=a+" "*h+b,
  49. correct_spacing=all(re.match('(\d| +)*$',s)for s in z)
  50. h+=2 # correct it again after the spacing gets too small
  51.  
  52. # and now to put the root down
  53. R=[]
  54. total = len(x[0])+h+len(y[0])
  55. for i in range(ht[-1]+1):
  56. a=i<len(x)and x[i]or" "*len(x[0])
  57. b=i<len(y)and y[i]or" "*len(y[0])
  58. R+=a+" "*h+b,
  59. v = p+q+h-len(str(n))-(len(str(A))>1)-(len(str(B))>1)
  60. for i in range(v//2):
  61. R=[" "*(len(x[0])-p+i)+"/"+" "*(p+q+h-2*i-2)+"\\"+" "*(len(y[0])-q+i)]+R
  62. R=[" "*(len(x[0])-p+v//2)+str(n)+" "*(len(y[0])-q+v//2)]+R
  63. return R
  64.  
  65. for i in tree(16):
  66. print(i)
Success #stdin #stdout 0s 9992KB
stdin
Standard input is empty
stdout
    16    
   /  \   
  /    \  
  4    4  
 / \  / \ 
/   \/   \
2   22   2