Home > Enterprise >  Printing out adjacent numbers in a list that have at least one common digit between them
Printing out adjacent numbers in a list that have at least one common digit between them

Time:12-21

I have a list of natural numbers and I need to print out every two adjacent integers that have at least one digit in common. So far I've written:

for i in range(len(my_list) - 1):
    first, second = my_list[i], my_list[i 1]
    if first==second and first>0 and second>0:
        print(first, second)
    else:
        print("nothing")

but, as you can see, it's missing the integer part. I've thought about dividing integers and working with results, but I'm certain that's not going to work.

CodePudding user response:

This is one place where strings can be quite effective. You can convert the string representation of an integer into a set, which can then be compared to another set. If the intersection is non-empty, they share a digit:

if set(str(first)) & set(str(second)):
    # first and second share a digit

CodePudding user response:

Try using enumerate() for slightly cleaner loop semantics.

Once you have this_n and next_n, decompose the integers into strings to get the digits as chars. Then, use a set to distinctly count the individual digits of each string, and use its intersection() method to see if two the sets have common elements:

numbers = [1,2,3,4,5,6,7,8,9,10,11,12]

for i, this_n in enumerate(numbers[:-1]):
    next_n = numbers[i 1]
    these_chars = set(str(this_n))
    next_chars = set(str(next_n))
    if these_chars.intersection(next_chars):
        print(this_n, next_n)

When I run that, I get:

10 11
11 12

CodePudding user response:

you can use zip to pair items with their successors in a list comprehension. Then select the pairs for which there is an intersection between the sets of digits of the two numbers. You can use set(str(n)) to get the set of digits of a number:

numbers = [1,234,325,987,108,999]

print([ (a,b) for a,b in zip(numbers,numbers[1:]) if set(str(a))&set(str(b)) ])

[(234, 325), (987, 108)]
  • Related