Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

Tôi đã tự hỏi nếu có bất kỳ cách nào dễ dàng hơn để đạt được những gì mã này đang đạt được. Bây giờ mã tạo tất cả số 4 chữ số trong danh sách (nếu số bắt đầu bằng 0 không được tính là 4 chữ số, ví dụ 0123) và không có chữ số nào được lặp lại trong số. Vì vậy, ví dụ 1231 không có trong danh sách. Tốt hơn tôi muốn một mã thực hiện những gì cái này đang làm nhưng tùy thuộc vào đối số n được đưa ra cho hàm khi gọi nó tạo ra loại danh sách này với tất cả các số có chữ N. Tôi hy vọng điều này không thể hiểu được vì tôi mới lập trình.

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

Đã hỏi ngày 5 tháng 10 năm 2017 lúc 10:09Oct 5, 2017 at 10:09

Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

1

Điều này có thể được thể hiện dễ dàng hơn.

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)

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:17Oct 5, 2017 at 10:17

7

Tôi sẽ sử dụng

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)))
5 cho điều này theo ý kiến ​​của tôi là câu trả lời chung đơn giản nhất:

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

Chỉ cần gọi chức năng này với

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)))
6 và nhận danh sách với tất cả các số bạn muốn.

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:35Oct 5, 2017 at 10:35

Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

MegabeetsmegabeetsMegabeets

1.33810 Huy hiệu bạc19 Huy hiệu đồng10 silver badges19 bronze badges

1

Bạn có thể làm trong một dòng:

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])

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:21Oct 5, 2017 at 10:21

Hãy thử những điều sau:

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))

Không nên gọi các chức năng được đặt trước với dấu gạch dưới (____ 17) không nên được gọi từ bên ngoài tập lệnh này. Nếu bạn thích có kết quả là một cái gì đó khác với một mảng các chuỗi, chẳng hạn như một mảng ints chẳng hạn, bạn có thể thay đổi hàm

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)))
8 như sau:

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

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:40Oct 5, 2017 at 10:40

AdirioadirioAdirio

4,8901 Huy hiệu vàng14 Huy hiệu bạc25 Huy hiệu đồng1 gold badge14 silver badges25 bronze badges

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

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:44Oct 5, 2017 at 10:44

AKPAKPakp

6094 Huy hiệu bạc12 Huy hiệu Đồng4 silver badges12 bronze badges

Những loại vấn đề này dễ dàng được giải quyết với đệ quy.

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)

Ở đây tôi đang sử dụng danh sách

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)))
9 để xây dựng các số bằng cách đặt một chữ số ở mỗi cuộc gọi. Khi có bốn chữ số được thêm vào, nó sẽ lưu trữ số vào danh sách
def guesses(N):
    return filter(all_digits_unique, range(10**(N-1), 10**N))

print guesses(4)
0.

Chỉnh sửa: Đây là phiên bản của hàm trên trả về danh sách các số thay vì nối chúng vào danh sách.

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)

Đã trả lời ngày 5 tháng 10 năm 2017 lúc 10:30Oct 5, 2017 at 10:30

Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

AnontaanontaAnonta

2.4802 Huy hiệu vàng14 Huy hiệu bạc24 Huy hiệu đồng2 gold badges14 silver badges24 bronze badges

5

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)))
0

Điều này hoạt động, nhưng hãy nhớ rằng điều này cũng sẽ thêm "0123" hoặc "0234" vào danh sách. Nếu bạn không muốn các số bắt đầu bằng 0, bạn có thể muốn thêm "I! = 0" vào truy vấn if. Hy vọng nó giúp.

Đã trả lời ngày 31 tháng 1 năm 2019 lúc 11:26Jan 31, 2019 at 11:26

Tôi cố gắng viết nó rõ ràng cho những người mới bắt đầu tuyệt đối ^^ OFCOURSE Có thể làm cho nó nhanh hơn và ngắn hơn nếu bạn sử dụng các phương pháp kết hợp và tiến trước.

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)))
1

Đã trả lời ngày 25 tháng 6 năm 2020 lúc 21:54Jun 25, 2020 at 21:54

Điều này sẽ phát triển vấn đề, mà không cần lặp lại các chữ số:

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)))
2

Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

SHR

7.6809 Huy hiệu vàng38 Huy hiệu bạc57 Huy hiệu đồng9 gold badges38 silver badges57 bronze badges

Đã trả lời ngày 17 tháng 8 năm 2020 lúc 11:55Aug 17, 2020 at 11:55

Hướng dẫn python generate all 4 digit numbers - python tạo tất cả các số có 4 chữ số

Còn cái này thì sao?

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)))
3

Trả về sai số nếu tất cả các số khác nhau, nếu không trả về true

Usage:

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)))
4

Đã trả lời ngày 14 tháng 5 lúc 6:20May 14 at 6:20

2