Tuesday, April 23, 2024
HomeSoftware EngineeringMost Digits from Checklist in Python

Most Digits from Checklist in Python

The problem

Discover the quantity with essentially the most digits.

If two numbers within the argument array have the identical variety of digits, return the primary one within the array.

The answer in Python code

Choice 1:

def find_longest(xs):
    return max(xs, key=lambda x: len(str(x)))

Choice 2:

def find_longest(arr):
    return arr[0]

Choice 3:

def find_longest(arr):
    max_lenght = 0
    max_index = 0
    for cur_num in arr:
        lenght = len(str(cur_num))
        if lenght > max_lenght:
            max_lenght = lenght
            max_index = arr.index(cur_num)
    return arr[max_index]

Check circumstances to validate our resolution

import take a look at
from resolution import find_longest

@take a look at.describe("Mounted Exams")
def fixed_tests():
    @take a look at.it('Primary Check Instances')
    def basic_test_cases():
        take a look at.assert_equals(find_longest([1, 10, 100]), 100)
        take a look at.assert_equals(find_longest([9000, 8, 800]), 9000)
        take a look at.assert_equals(find_longest([8, 900, 500]), 900)
        take a look at.assert_equals(find_longest([3, 40000, 100]), 40000)
        take a look at.assert_equals(find_longest([1, 200, 100000]), 100000)

@take a look at.describe("Random exams")
def random_tests():
    from random import randint
    from functools import cut back
    sol=lambda arr: cut back(lambda a,b: b if len(str(a))<len(str(b)) else a,arr)
    for _ in vary(40):
        arr=[randint(1,10**randint(1,20)) for q in range(randint(1,50))]
        anticipated = sol(arr)
        @take a look at.it(f"Testing for find_longest({arr})")
        def _():
            take a look at.assert_equals(find_longest(arr[:]),anticipated)


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments