Pentru pct. 5:
Cod:
def minimumSteps(self, palindromes):
assert len(palindromes) > 0
minSteps = min(palindromes.values())
maxPalindromes = []
for palindrome, step in palindromes.iteritems():
if step == minSteps:
maxPalindromes.append(int(palindrome))
print 'Max palindrome divisible by', self.data['divizor'], 'in minimum number of steps('+str(minSteps)+'):', max(maxPalindromes)
self.stepsToReachNumber(str(max(maxPalindromes)), True)
Si pentru pct. 6 o combinatie intre determinarea pasilor si printarea lor:
Cod:
def stepsToReachNumber(self, number, printPath = False):
fromNumber = str(self.data['N'])
count = 0
if printPath:
print fromNumber
while fromNumber != number:
for i, n in enumerate(fromNumber):
if n != str(number)[i]:
index = self.path[self.locate(int(n))]
while n != str(number)[i]:
where = index.index(int(n))
if where+1 == len(index):
fromNumber = fromNumber[0:i] + str(index[0]) + fromNumber[i+1:]
n = str(index[0])
count += 1
else:
fromNumber = fromNumber[0:i] + str(index[where+1]) + fromNumber[i+1:]
n = str(index[where+1])
count += 1
if printPath:
print fromNumber
break
return count
Punand totul cap la cap si apeland:
Cod:
a = main()
a.readFileAndExtractNeededValues()
a.buildPathsInWhichNCanChange()
a.maxN();
a.determineMaxPalindromeDivisibleByK()
obtinem ca output pentru exemplu:
Cod:
transform path = [[0], [1, 4], [2, 6, 7, 8, 9, 3, 5]]
Maximum palindrome reachable: 4994
1234
4234
4634
4734
4834
4934
4954
4924
4964
4974
4984
4994
Max palindrome divisible by 3 in minimum number of steps(3): 4224
1234
4234
4254
4224
Stiu ca in execitiu trebuia pus in palindrome.out but ... I can't be bothered to. Se poate modifica sa construiasca palindrome.out in loc de print.
assert self.hasMaxN verfica daca are solutie (am scris mai sus cand nu ar avea solutie), si "assert len(palindromes)" > 0 verifica daca exista nr divizibil cu K (pentru ca e posibil sa nu aiba).
Cam atat.