Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Digits increasing
#6
It looks like the recursive approach is wrong:
# the next integer whose digits are increasing.
def increasing(n):
    asastring = str(n)
    length = len(asastring)
    if asastring == "9"*length:
        return "1"*(length+1)
    if length == 1:
        return int(n)+1

    if length >= 2:
        firstcharacter = asastring[0]
        secondcharacter = asastring[1]
        if int(firstcharacter) > int(secondcharacter):
            return int(str(firstcharacter)*length)
        if firstcharacter == secondcharacter:
             return firstcharacter+str(increasing(int(asastring[1:])))
        if int(firstcharacter) < int(secondcharacter):
            if secondcharacter == "9":
                return str(int(firstcharacter)+1) * len(str(n))
            return firstcharacter+str(increasing(int(asastring[1:])))


def decreasing(n):
    asastring = str(n)
    length = len(asastring)
# First the case where we need to add a digit.
    if asastring == "9"*length:
        return "1"+"0"*length
# Now we know that the next integer has the same number of digits as the original number.
    if length == 1:
        return int(n)+1
    if length >= 2:
        firstcharacter = asastring[0]
        secondcharacter = asastring[1]
        if int(firstcharacter) > int(secondcharacter):
            return str(firstcharacter) + str(decreasing(asastring[1:]))
        if int(firstcharacter) == int(secondcharacter):
            return decreasing(firstcharacter+str(decreasing(asastring[1:])))
        if int(firstcharacter) < int(secondcharacter):
            return str(int(firstcharacter)+1)+'0'*(length-1)

i = 1
found = False
for k in range(4000):
    i = min(int(increasing(i)), int(decreasing(i)))

print(i)
outputs RecursionError: maximum recursion depth exceeded while getting the str of an object
Reply


Messages In This Thread
Digits increasing - by meknowsnothing - Feb-16-2019, 06:09 PM
RE: Digits increasing - by ichabod801 - Feb-16-2019, 07:39 PM
RE: Digits increasing - by meknowsnothing - Feb-16-2019, 08:28 PM
RE: Digits increasing - by scidam - Feb-17-2019, 07:26 AM
RE: Digits increasing - by meknowsnothing - Feb-17-2019, 08:39 AM
RE: Digits increasing - by meknowsnothing - Feb-17-2019, 10:19 AM
RE: Digits increasing - by scidam - Feb-17-2019, 11:22 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Increasing difficulty of a maths game Maxxy_Gray 1 3,205 Apr-04-2018, 03:00 PM
Last Post: sparkz_alot
  Increasing depth in python malling 19 14,164 Oct-20-2016, 10:43 PM
Last Post: malling

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020