@Ves6/

MultiplePalindromesAgain

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def main():

    d = 4 # length defined as d*2+1
    b = 2 # starting base 
    checkForThirdConsecutiveBase = False # check for triples?

    while True:
        # acquire palindromes in base b
        for palindrome in palgen(b,d,True):

            # converting to decimal and then to base b+2
            decimal_value = listToInt(palindrome[0], b)
            second_base_value = numberToBase(decimal_value, b+2)
            
            if isPalindrome(second_base_value):

                # optional check for base b+1 (when searching for palindromic triples)
                if checkForThirdConsecutiveBase and isPalindrome(numberToBase(decimal_value, b+1)):
                    print(getTime(),b,palindrome,decimal_value,'X')
                    
                else:
                    
                    # print but mark not-equal-sized-ones with "*"
                    if len(second_base_value) == d*2+1:
                        print(getTime(),b,palindrome,decimal_value)
                    else:
                        print(getTime(),b,palindrome,decimal_value,'*')
        print()
        b += 1
        # next number base
        


# convert to any base in list form (integers in list represent digits)
def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

# converts list representation of number in base 'base' to decimal
def listToInt(digitList, base):
    value = 0
    for val in digitList:
        value = value * base + val
    return value

# returns a tuple ('palindrome in list form','index of palindrome')
def palgen(b, d, odd):
    i = b**d
    r = range(i, (b * i))
    for j in r:
        s = numberToBase(j, b)
        if (odd):
            yield (s + s[-2::-1],j-i)
        else:
            yield s + s[::-1]  

def isPalindrome(n):
    return n == n[::-1]

from time import gmtime, strftime
def getTime():
    return strftime("# ( %D %H:%M:%S )", gmtime())

main()