Find the number of 6 digit numbers such that each digit appears atleast twice
I tried the below code but it doesn't work:
count = 0
for n in range(10**5,(10**6)-1):
n = str(n).split()
for i in range(len(n)):
n[i] = int(n[i])
if n.count(i) >= 2:
count =1
print(count)
The original question is of Permutation and Combinations but I want to solve this using python...
CodePudding user response:
Here are some of the mistakes in your code -
- The range needs to be
range(10**5, 10**6)to cover all 6 digit numbers str(n).split()won't split theninto a list of characters since there is no delimiter between the string representation of the number. You can use[letter for letter in str(n)]instead.- You want to run the second loop for each of the numbers in the first loop, so the second loop needs to be inside the first loop.
- Within the second loop, you are increasing the
countif one of the digits occurs more than twice in the number, so you might end up increasing the count multiple times for a single number. e.g. for112233you would end up increasing thecountby 3 instead of just 1.
here's a simplified code which does what you want in a similar format -
count = 0
for n in range(10**5, 10**6):
n = [letter for letter in str(n)]
count = 1
for letter in n:
if n.count(letter) < 2:
count -= 1
break
print(count)
outputs -
11754
You can use all() function along with list comprehension to simplify the code -
count = 0
for n in range(10**5, 10**6):
n = [letter for letter in str(n)]
count = all(n.count(letter) >= 2 for letter in n)
CodePudding user response:
answers = []
count = 0
my_dict = {}
digits = '0123456789'
for n in range(10**5, (10**6)-1):
my_dict = {}
ns = str(n)
for m in ns:
if m in digits:
my_dict[m] = ns.count(m)
if my_dict[min(my_dict, key=my_dict.get)] > 1:
count = 1
answers.append(ns)
print(count)
Here is an alternative way. It gets the correct number.
