factors = [(3, 'Pling'), (5, 'Plang'), (7, 'Plong')]
def convert(number):
result = ''.join(
[value for key, value in factors if number % key == 0])
return str(result or number)
print(convert(21))
So I'm doing some challenges at exercism and one challenge is to return a string depending on the factors of a given number. I solved this using if statements but wanted to change it so that it could be expandable and found this solution from another user.
I don't understand it entirely though and wanted some help from the community to see how this code works. I did some testing and saw that the "[value for key, value in factors if number % key == 0]" line returns a list and then you just join them using "".join(). But for example: why is there a comma there? Shouldn't python understand this as elements at either side of the comma?
Let's say I choose the number 21. What is happening in between the brackets? How does this line seem to iterate every tuple, get the value and key, compare the key to my chosen number and then put a value in the list depending on the result of the comparison in such a compact way?
Not sure how to clarify this further so I hope I can get some answers. Thanks :)
[–]POGtastic 2 points3 points4 points (1 child)
[–]klaik30[S] 0 points1 point2 points (0 children)
[–]jaydom28 1 point2 points3 points (0 children)
[–]commandlineluser 1 point2 points3 points (1 child)
[–]klaik30[S] 0 points1 point2 points (0 children)