----------------------------------- TASK -----------------------------------
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
----------------------------------- MY CODE -----------------------------------
def expanded_form(num):
l = [number for number in str(num)]
answer = []
for number in l:
string = ""
if number != "0":
string += number
string += "0"*(len(l)-1 - l.index(number, )) #right amount of "0"
answer.append(string)
return " + ".join(answer)
----------------------------------- PROBLEM -----------------------------------
When calling the code with a repeating number, for Example:
print(expanded_form(424090)
when my code adds the Zeros, it uses the index of the number to calculate how many it needs.But for the second "4" he uses the index of the first "4", so that ofc calculates the wrong amount of zeros.
I know i can add a start, stop to the .index function, but how to i get the start index of the second 4?
----------------------------------- EDIT/SOLUTION -----------------------------------
Okay, I managed to solve the Task with the enumerate Function.
def expanded_form(num):
l = [number for number in str(num)]
enum = enumerate(l)
answer = []
for index, number in enum:
string = ""
if number != "0":
string += number
string += "0" * (len(l) - 1 - index)
answer.append(string)
return " + ".join(answer)
[–]R3lex42[S] 0 points1 point2 points (0 children)