user2788201
user2788201

Reputation: 13

how to compare 2 or more elements in a list with integers of more than 2 digits

i have user input for list elements. any number of elements user can be entered.

if the user enters 3 elements in the list and if the user entered the elements as follows

123456789 123467890 123489012

how to find the how many digits are matched from starting using python?

output will be : 4 ( because all elements 4 digits are same (1234))

if the user enters 4 elements in the list and if the user entered the elements as follows

123456789 123467890 123489012 123589000

how to find the how many digits are matched from starting using python?

output will be : 3 ( because all elements 3 digits are same (123))

Upvotes: 1

Views: 48

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22418

Perhaps you can use a for loop:

import locale
from collections.abc import Sequence

def _get_decimal_separator() -> str:
  """Returns the locale-specific decimal separator."""
  locale.setlocale(locale.LC_ALL, '')
  conv = locale.localeconv()
  return str(conv['decimal_point']) if conv['decimal_point'] else '.'

def _normalize_number(num: str, decimal_seperator: str) -> str:
  """Normalizes a number string to remove minus sign and decimal separator."""
  return num.lstrip('-').replace(decimal_seperator, '')

def common_prefix_length(numbers: Sequence[str]) -> int:
  """Finds number of matching starting digits across all elements in sequence.
  
  Args:
    numbers: A sequence of string representations of numbers.

  Returns:
    The count of matching digits from the beginning across all elements.
  """
  if not numbers:
    return 0
  decimal_separator = _get_decimal_separator()
  numbers = [_normalize_number(num, decimal_separator) for num in numbers]
  reference = numbers[0]
  for i in range(len(reference)):
    for number in numbers[1:]:
      if i >= len(number) or number[i] != reference[i]:
        return i
  return len(reference)

def main() -> None:
  user_input = input('Enter numbers separated by spaces: ').split()
  if len(user_input) == 0:
    print('No numbers provided.')
    return
  print(f'{common_prefix_length(user_input) = }')

if __name__ == '__main__':
  main()

Example Usage 1:

Enter numbers separated by spaces: 123456789 123467890 123489012
common_prefix_length(user_input) = 4

Example Usage 2:

Enter numbers separated by spaces: 123456789 123467890 123489012 123589000
common_prefix_length(user_input) = 3

Example Usage 3:

Enter numbers separated by spaces: 12.3 -12.3 123 -123
common_prefix_length(user_input) = 3

Example Usage 4:

Enter numbers separated by spaces: 3 2 4
common_prefix_length(user_input) = 0

Example Usage 5:

Enter numbers separated by spaces: 1 12 123
common_prefix_length(user_input) = 1

Upvotes: 0

Related Questions