fille
fille

Reputation: 11

Python: Create a list of all four digits numbers with all different digits within it

I was wondering if there is any easier way to achieve what this code is achieving. Now the code creates all 4-digits number in a list (if the number starts with a 0 is doesn't count as a 4-digit, for example 0123) and no digit is repeated within the number. So for example 1231 is not in the list. Preferable I want a code that does what this one is doing but a depending on what argument N is given to the function upon calling it creates this kind of list with all numbers with N digits. I hope this wasn't impossible to understand since Im new to programing.

def guessables():
   '''creates a list of all 4 digit numbers wherest every
    element has no repeating digits inside of that number+
    it doesn't count as a 4 digit number if it starts with a 0'''
     guesses=[]
     for a in range(1,10):
          for b in range(0,10):
               if a!=b:
                  for c in range(0,10):
                      if b!=c and a!=c:
                          for d in range(0,10):
                               if c!=d and d!=b and d!=a:
                                   guesses.append(str(a)+str(b)+str(c)+str(d))
    return guesses

Upvotes: 0

Views: 10102

Answers (12)

Maximilien
Maximilien

Reputation: 1

You could write :

digits = []

for digit in range(10000, 11001):
      digits.append(str(digit)[1:])

print(digits)

Upvotes: 0

Erdem Ekinci
Erdem Ekinci

Reputation: 21

d = int(input("How many digits ?: "))
s = [k for k in range(10 ** (d - 1), 10 ** d) if len(str(k)) == len(set(str(k)))]

For example: 1123

str(1123): It makes 1123 as '1123' and you can use len command here

len(str(1123): Returns 4

set(str(1123)): It makes set {'3', '2', '1'} , remember no repat in sets

len(set(str(1123)): Returns 3.

4 != 3 makes if condition false.

So if condition is not met, 1123 not added to list

Short form of lists

s = [i for i in range(10)] : Is equal [0,1,2,3,4,5,6,7,8,9]

s = [k for k in range(100, 1000) if k % 2 == 0] : Is equal [100,102,..,998]

looking in range and condition at the same time.

One line code: If you know how many digits (for example 4) we have and wanna see the list

print([k for k in range(10 ** 3, 10 ** 4) if len(str(k)) == len(set(str(k)))])

Function form:

def guessables(d):
    return [k for k in range(10 ** (d - 1), 10 ** d) if len(str(k)) == len(set(str(k)))]

Upvotes: 0

Test1234
Test1234

Reputation: 1

How about this?

def check_count(num):
    if isinstance(num, str) == False:
        num = str(num) # Convert to str
    if len(num) == 1: # If total length number is single, return False
        return False
    return any(num.count(x) > 1 for x in num) # Check here

Return False if numbers all different, else return True

Usage:

# Get all numbers has all different. (1000-9999)

[x for x in range(1000, 10000) if check_count(x) == False]

UPDATE 2023:

I fixed this code, so the function return True for number that each digit unique, else False

def check_number_is_unique(num) -> bool:
    """Check each digits in number are unique"""
    num_str = str(num)
    if len(num_str) == 1: # Single number return True
        return True
    # For each check the occurrences digit is greater than 1
    # if any() returns True, then return False
    # if any() returns False, then return True
    return not any(num_str.count(x) > 1 for x in num_str)

New usage:

list(filter(check_number_is_unique, range(1000, 10000)))

Upvotes: 0

ubuntu kali
ubuntu kali

Reputation: 1

This would sovlve the problem, without repeating digits:

from itertools import permutations
myperm = permutations([0,1,2,3,4,5,6,7,8,9],4)
for digits in list(myperm):
    print(digits)

Upvotes: 0

Erdem Ekinci
Erdem Ekinci

Reputation: 21

I try to write it clear for absolute beginers ^^ Ofcourse it is possible to make it faster and shorter if you use combianations and advance array methods.

def f(n)
    s = list(range(10**(n-1), 10**n))
    number_list = []
    for ss in s:
        test_list = []
        a = ss
        while ss:
            if ss % 10 in test_list:
                break
            test_list.append(ss % 10)
            ss = ss // 10
            if len(test_list) == n:
                number_list.append(a)
    return number_list


print(f(4))

Upvotes: 0

Furkan Doğru
Furkan Doğru

Reputation: 1

numPool = []

for i in range(0, 10):
    for j in range(0, 10):
        for k in range(0,10):
            for l in range(0,10):
                if i != j and i != k and i != l and j != k and j != l and k != l :
                    numPool.append(str(i) + str(j) + str(k) + str(l))

This works, but keep in mind that this will also add "0123" or "0234" to the list as well. If you do not want the numbers that are starting with zero, you might want to add "i != 0" to the if query. Hope it helps.

Upvotes: 0

Anonta
Anonta

Reputation: 2540

These types of problems are easily solved with recursion.

def gen(num, n, saveto):
    if len(num) == 1 and num[0] == '0':
        return 
    if len(num) == n:
        saveto.append(int(''.join(num)))
        return 

    for i in range(0, 10):
        i= str(i)
        if i not in num:
            gen(num+[i], n, saveto)

saveto= []
# generate 4 digit numbers
gen([], 4, saveto)

print(saveto)

Here I'm using the list num to construct the numbers by placing one digit at each call. When there are four digits added, it stores the number to the saveto list.

Edit: Here's a version of the above function that returns the list of numbers instead of appending them to a list.

def gen(num, n):
    if len(num) == 1 and num[0] == '0':
        return []
    if len(num) == n:
        return [int(''.join(num))]

    ans = []

    for i in range(0, 10):
        i= str(i)
        if i not in num:
            ans.extend(gen(num+[i], n))

    return ans

saveto= gen([], 4)

print(saveto)

Upvotes: 0

akp
akp

Reputation: 637

c=list(range(10))
print c
def fun(n,k,i,getnum):       # function , result in getnum
    if n==0:
        if k not in getnum and len(set(list(k)))==len(k) and k[0]!='0':
            getnum.append(k)
        return
    if i>=len(c):
        return
    fun(n-1,k+str(c[i]),0,getnum)
    fun(n,k,i+1,getnum)

getnum=[]
d=fun(4,"",0,getnum)

print getnum

Upvotes: 0

Adirio
Adirio

Reputation: 5286

Try the following:

def guessables(n):
    ''' Returns an array with the combination of different digits of size "n" '''
    if n > 10:
        raise ValueError("The maximum number of different digits is 10.")
    elif n < 1:
        raise ValueError("The minimum number of digits is 1.")
    else:
        results = []
        for i in range(1, 10):
            _recursiveDigit([i], n, results)
        return results

def _formatDigit(l):
    ''' Return a formated number from a list of its digits. '''
    return "".join(map(str, l))

def _recursiveDigit(l, n, results):
    ''' Recursive function to calculate the following digit. '''
    if len(l) < n:
        for i in range(0, 10):
            if i not in l:
                _recursiveDigit(l + [i], n, results)
    else:
        results.append(_formatDigit(l))

The functions that are prefixed with an underscore(_) should not be called from outside of this script. If you prefer to have the result as something different than an array of strings, such as an array of ints for example, you can change the _formatDigit() function as follows:

def _formatDigit(l):
    ''' Return a formated number from a list of its digits. '''
    return int("".join(map(str, l)))

Upvotes: 0

Megabeets
Megabeets

Reputation: 1408

I'd use itertools for this which is in my opinion the simplest generic answer:

import itertools

def guessables(num):
    guesses = []
    for p in itertools.permutations(xrange(10),num):
        if p[0] != 0:
            guesses.append(''.join(map(str, p))) 
    return guesses

Simply call this function with guessables(4) and get a list with all the numbers you want.

Upvotes: 2

Ronan Klyne
Ronan Klyne

Reputation: 74

This can be expressed more easily.

def all_digits_unique(number):
    # `set` will only record unique elements.
    # We convert to a string and check if the unique
    # elements are the same number as the original elements.
    return len(str(number)) == len(set(str(number)))

Edit:

def guesses(N):
    return filter(all_digits_unique, range(10**(N-1), 10**N))

print guesses(4)

Upvotes: 2

user8099934
user8099934

Reputation:

You can do in one line:

print([str(a)+str(b)+str(c)+str(d) for a in range(1,10) for b in range(0,10) if a!=b for c in range(0,10) if b!=c and a!=c for d in range(0,10) if c!=d and d!=b and d!=a])

Upvotes: 0

Related Questions