palindromes.py 898 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. # Author: estelendur
  2. # Given a base b and a number of digits n, how many palindromic integers?
  3. # What proportion of possible integers are palindromes?
  4. # Can we learn anything interesting from this?
  5. from math import *
  6. def half(x):
  7. return ceil(float(x)/2)
  8. def pals(n, b):
  9. return (b-1)*(b**(half(n-1)))
  10. def num(n, b):
  11. return (b-1)*(b**(n-1))
  12. def prop (n, b):
  13. return pals(n, b)/num(n, b)
  14. def testex(nm, bm):
  15. if (nm==2 & bm==1):
  16. return ""
  17. elif (bm==1):
  18. return ""
  19. elif(nm==2):
  20. return ""
  21. else:
  22. return (str(nm)+" digits in base "+str(bm)+" gives "+
  23. str(floor(prop(nm,bm)*100))+" percent palindromes. "+
  24. test(nm-1,bm)+test(nm,bm-1))
  25. def test(nm, b):
  26. if(nm==2):
  27. return ""
  28. else:
  29. return(str(nm)+" digits: "+str(prop(nm,b)*100)+" percent palindromes. "
  30. +test(nm-1,b))