Most Digits from List in Python

The challenge

Find the number with the most digits.

If two numbers in the argument array have the same number of digits, return the first one in the array.

The solution in Python code

Option 1:

def find_longest(xs): return max(xs, key=lambda x: len(str(x)))
Code language: Python (python)

Option 2:

def find_longest(arr): arr.sort(reverse=True) return arr[0]
Code language: Python (python)

Option 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]
Code language: Python (python)

Test cases to validate our solution

import test from solution import find_longest @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(find_longest([1, 10, 100]), 100) test.assert_equals(find_longest([9000, 8, 800]), 9000) test.assert_equals(find_longest([8, 900, 500]), 900) test.assert_equals(find_longest([3, 40000, 100]), 40000) test.assert_equals(find_longest([1, 200, 100000]), 100000) @test.describe("Random tests") def random_tests(): from random import randint from functools import reduce sol=lambda arr: reduce(lambda a,b: b if len(str(a))<len(str(b)) else a,arr) for _ in range(40): arr=[randint(1,10**randint(1,20)) for q in range(randint(1,50))] expected = sol(arr) @test.it(f"Testing for find_longest({arr})") def _(): test.assert_equals(find_longest(arr[:]),expected)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments