Reputation: 138
This block of code gives the correct output however the expression to generate the replacements for numbers is inefficient as it repeats the same expression twice. Is there a way to make this more concise by not repeating the phrase?
Code:
numphrase = {3: "three", 5: "five"}
result = [''.join([numphrase.get(key) for key in numphrase if not num % key])
if ''.join([numphrase.get(key) for key in numphrase if not num % key]) else
num for num in range(101)]
print(*result, sep="\n")
Output:
threefive
1
2
three
4
five
...
Upvotes: 0
Views: 109
Reputation: 59146
There's an easier way to write x if x else y
in Python, and that's x or y
.
So you can write your comprehension as
result = [''.join([numphrase.get(key) for key in numphrase if not num % key]) or num
for num in range(101)]
Upvotes: 3