+ 1
Write a program to,calculate the number of 4-digit numbers without repetition obtained from the combination of given input tuple
Sample Example. Input type: tuple with each element in range 0 to 9. Length of tuple= 4 Input: (2,0,6,4), Output type: list Output: [2046,2064,2406, 2460,2604,2640, 4026, 4062, 4206, 4260, 4602, 4620, 6024, 6042, 6204, 6240, 6402,6420] Explanation: From the given input, we cannot. create a four-digit integer with 0 as the starting digit. Hence, the output values should be a combination without 0 as starting digit.
1 Réponse
+ 1
You can use the 'permutations' function from python's itertools module. To avoid repeating 4-digit numbers, use a set to collect the numbers before converting to the list output. It is also helpful to first define a function that converts digits to a number. Assuming the input is already a tuple type, this is my solution:
from itertools import permutations
def digits_to_number(digits):
'''Return a number from a sequence of digits'''
N = len(digits)
number = 0
for i, d in enumerate(digits):
number += d * 10**(N - 1 - i)
return number
my_digits = (2, 0, 6, 4) # input tuple
four_digit_numbers = set()
for digits in permutations(my_digits):
n = digits_to_number(digits)
if n > 999 and n < 10000:
four_digit_numbers.add(n) # no duplicates
result = list(four_digit_numbers)
print(sorted(result)) # same as sample output