Mint
Mint

Reputation: 1059

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?

This is what I've got so far. the function takes in a list. (updated)

arr = [[1,20],[1,10]]

for i in arr:
    l = list(range(i[0],i[1]))
    for num in l:
        if num < 11: continue
        for c in str(num):
            if str(num).count(c) > 1:
                # dont know why code is popping off 12 and 13
                print(l.pop(num))

Upvotes: 2

Views: 15745

Answers (5)

Siddhant Tiwari
Siddhant Tiwari

Reputation: 1

Here is my solution, its simple and works for 2 digit numbers.

nums = list(input().rstrip().split())


def has_doubles(nums):
    for number in nums:
        if number[0] == number[1]:
            print(number)
        else:
            continue


has_doubles(nums)

Upvotes: 0

Mint
Mint

Reputation: 1059

Solved this! I didn't know pop executes based on position not value! remove is a better fit here.

arr = [[1,40],[1,10]]

for i in arr:
    l = list(range(i[0],i[1]))
    for num in l:
        if num < 11: continue
        for char in str(num):
            if str(num).count(char) < 2: continue
            l.remove(num)
            break
    print(l)

Upvotes: 0

sachgits
sachgits

Reputation: 345

looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops

def countNumber(foundDigits,number):
    next_number = int(number/10);
    reminder = number % 10;
    if(next_number < 1):
        for num in foundDigits:
            if(num == number or num == reminder):
                return True
        return False;
    foundDigits.append(reminder);
    return countNumber(foundDigits,next_number)

example in interpreter could be

digitsFound = list()
countNumber(digitsFound, 435229)

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

The best way I can think about is converting the number to a string and doing a Counter on it

from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
    print "The number has repeating digits"

@Two-BitAlchemist thanks for the suggestion

Upvotes: 3

kardaj
kardaj

Reputation: 1935

If your ultimate goal is simply detecting if there's a double, this function may help:

def has_doubles(n):
    return len(set(str(n))) < len(str(n))

Upvotes: 13

Related Questions