Reputation: 33
d_num = []
d_num.append(input("Enter a figure to verify if is a Disarium number: "))
With the above code, an input of 135
and print(d_num)
, would return '135' opposed to '1, 3, 5'.
A quick-fix would be, prompt the user to include whitespace or other characters between digits and use the split command. However, that poses a problem because the output calculation is based upon the index of the digit.
For example:
input: 135 output: true, 135 == Disarium number as 1^1 + 3^2 + 5^3 = 135
Is there an easier way to convert user input, despite type
, into a list?
Upvotes: 2
Views: 487
Reputation: 171
You wanted to know a way to automatically store each digit of the user input as a list item right? Below is the easiest way I can think of:
user_input = input("Enter a figure to verify if is a Disarium number: ")
d_num = [digit for digit in user_input]
The d_num list will have each digit stored separately and then you can convert it into an integer/float and perform the calculation to identify if its a Disarium number or not.
As @Jérôme suggested in the comment, a much simpler solution would be to simply convert the user input to a list and python handles the work of adding individual characters as a list item.
d_num = [digit for digit in user_input]
can be written as d_num = list(user_input)
Hope that helps
Upvotes: 1
Reputation: 311123
Calling list(d_num)
will give you a list of the individual characters that make up the number. From there, you can just go over them, convert them to integers and raise them to the appropriate power:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(list(d_num)))):
print("%s is a Disarium number" % d_num)
EDIT:
As Jean-François Fabre commented, you don't actually need the list
call - you could enumerate the string's characters directly:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(d_num))):
print("%s is a Disarium number" % d_num)
Upvotes: 1