Awesome answer, Pierre! I have one doubt though. Wouldn't it be better to first convert nb into a string, and then just pass the string to the list comprehension, instead of doing str(nb) for every iteration? That is,
nb
str(nb)
str_nb = str(nb) return nb == sum(int(c)**len(str_nb) for c in str_nb)
This might be a little more efficient. Also, we can remove the list comprehension inside and replace it with a generator.
Yeah you're right! Thank you, that's clever!
This is fun! Here is a Python 3.5 one-liner with only one calculation of the length of nb per nb :
print([nb for nb in range(10000) if nb == sum(int(c)**l for l in [len(str(nb))] for c in str(nb))])
And now with also one conversion of str(nb) per nb:
print([nb for nb in range(10000) if nb == sum(int(c)**l for str_nb in [str(nb)] for l in [len(str_nb)] for c in str_nb)])
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Awesome answer, Pierre!
I have one doubt though. Wouldn't it be better to first convert
nb
into a string, and then just pass the string to the list comprehension, instead of doingstr(nb)
for every iteration? That is,This might be a little more efficient. Also, we can remove the list comprehension inside and replace it with a generator.
Yeah you're right! Thank you, that's clever!
This is fun! Here is a Python 3.5 one-liner with only one calculation of the length of nb per nb :
print([nb for nb in range(10000) if nb == sum(int(c)**l for l in [len(str(nb))] for c in str(nb))])
And now with also one conversion of str(nb) per nb:
print([nb for nb in range(10000) if nb == sum(int(c)**l for str_nb in [str(nb)] for l in [len(str_nb)] for c in str_nb)])