Reputation: 13
I have a simple problem, for which I have to find how many numbers in a specified interval where the digits of one number are all different. I wrote the code to find these numbers but can't count how many outputs? for example, 244 is not acceptable as two digits are similar, 243 is acceptable because all digits are different. I just want to count how many outputs I have.
list = []
for i in range(234,567):
list.append (i)
for n in list:
x=[int(a) for a in str(n)]
if x[0] != x[1] !=x[2] and x[0]!= x[2]:
strings = [str(number) for number in x]
a_string="".join (strings)
finalrz=int(a_string)
print (finalrz)
Upvotes: 1
Views: 204
Reputation: 655
It seem you like unnecessary complexity.
Primo:
In line 2 of your code, you put integers in the list.
In line 5, you convert the integer to string to separate letters. Then you convert each letter to integer and put them in list.
In line 7, you convert the digit to letter and build a list of letters.
In line 8, you concatenate all letters from the list.
That's too 'convoluted'.
Secundo:
In line 6, you use 3 compare (for 3 digit numbers).
If you had to do the same program for 8 digit numbers, how many compare would you need?
hint:((8**2)-8)/2)
That's 28 comparisons. We can say that your method is 'non-scalable'.
Here's is an example of a better algorithm:
counter = 0
for i in range( 234, 567):
letters = str(i) # convert integer to letters
seen = [] # list of previously seen letters
for letter in letters:
if letter in seen: break # check if already seen
seen.append( letter) # update list of seen letters
else:
#print( letters)
counter += 1
print( counter, "numbers without duplicate digits.")
Note that this program will work with numbers of any width.
Upvotes: 0
Reputation: 26
You could create an int variable and after the output is printed +1 to the variable. Make sure the variable isn't in the for loop because it will reset the variable every iteration.
#NEW CODE
count = 0
#END OF NEW CODE
list = []
for i in range(234,567):
list.append (i)
for n in list:
x=[int(a) for a in str(n)]
if x[0] != x[1] !=x[2] and x[0]!= x[2]:
strings = [str(number) for number in x]
a_string="".join (strings)
finalrz=int(a_string)
print (finalrz)
#NEW CODE
count = count + 1
print(count, "outputs")
Upvotes: 1