[Python] Given a string of numbers, return the largest possible bitonic number as an integer...

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I am looking at this code challenge:


    Given a function largest_bitonic_at_most(n), find the largest positive bitonic integer that is not greater than n, and return it.

    Here is the definition of bitonic in this problem:

    1. If the digits of n are in non-decreasing order only, it is bitonic (e.g. 123456, 15687)
    2. If its digits are in non-increasing order only, it is bitonic (e.g. 964441, 7521)
    3. If its digits are first non-decreasing, and then non-increasing until the end, it is bitonic (e.g. 12368862, 2952)
    4. Repeating digits will still count, as long as it follows the first 3 conditions (e.g. 77777, 12222521 are bitonic)

    Return the number if it is bitonic. If the number is not bitonic, return the largest positive integer less than that number, that is still bitonic.

    Example call 1:


    largest_bitonic_at_most(227942) == 227942

    Example call 2:


    largest_bitonic_at_most(28052) == 28000

    Example call 3:


    largest_bitonic_at_most(268472) == 68444​

    I can only use basic Python commands for now (e.g. if else, recursion, assignments)

    Here is the code I have so far.

    def largest_bitonic_at_most(n):
    def helper(n):
    n = str(n)
    length = len(n)
    if length > 2:
    if n[0] <= n[1]:
    return n[0] + helper(n[1:])
    elif n[0] > n[1]:
    if n[1] >= n[2]:
    return n[0] + helper(n[1:])
    else:
    return n[0] + (n[1] * (length - 1))
    else:
    return n[0]
    elif length <= 2 and length > 0:
    if n[0] >= n[1]:
    return n[0] * 2
    else:
    return n

    x = helper(n)
    return int(x)


    Here are some of the sample simulations and results.

    print(largest_bitonic_at_most(11118)) #11118
    print(largest_bitonic_at_most(211144)) #211144 should be 211111
    print(largest_bitonic_at_most(1204)) #1200
    print(largest_bitonic_at_most(789123)) #789111

    Continue reading...

Compartilhe esta Página