Reputation: 37
I'm writing program to find unique digits in a number and got this solution but I want to know how this works?
print(next(len(set(list(x))) if 1<=int(x)<=25000 else "Number should be >=1 and <=25000" for x in [input()]))
Upvotes: 2
Views: 90
Reputation: 1004
If you want to "find unique digits in a number" meaning that you want to see which digits are unique then you can use this code:
x = input()
print((list(set(x))) if 1<=int(x)<=25000 else "Number should be >=1 and <=25000")
Upvotes: 1
Reputation: 15364
Let's rewrite the solution in another way and comment it:
# Read the number (as a string, for example '3455')
x = input()
# Convert the string to an int ('3455' --> 3455) and check if the condition holds
if 1 <= int(x) <= 25000:
# Create a list of digits ('3455' --> ['3', '4', '5', '5'])
lst = list(x)
# Find unique digits (['3', '4', '5', '5'] --> {'3', '4', '5'})
s = set(lst)
# Count the number of unique digits
c = len(s)
# Print the result
print(c)
else:
# If the condition 1 <= x <= 25000 does not hold then print an error message
print("Number should be >=1 and <=25000")
You one line solution does exactly the same thing. I would say that it's not very "clear", still it works (as long as you input a number, and not something else, such as "3455g").
Upvotes: 2