![]() |
list digit into number - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: list digit into number (/thread-37695.html) |
list digit into number - Voldyy - Jul-10-2022 Hi, how can i change this code to work for two-digit numbers or three-digit number? For now only work for single digit numbers, tried to change algorthm but didnt work. def to_number(digits): result=digits[0] for el in digits[1:]: result=result*10 result=result + el return resultNow the ouput is 2221 - i think is because of this line result=result + el It has to output this: input: [ 21, 12, 1] output: 21121 RE: list digit into number - BashBedlam - Jul-10-2022 This is how I would go about it: def to_number (digits) : string_result = '' for number in digits : string_result += str (number) return int (string_result) print (to_number ([21, 12, 1]))
RE: list digit into number - deanhystad - Jul-10-2022 Play the part of the computer to see why your program doesn't work For two and 3 digit numbers you are not "shifting" result enough. If e1 has 2 digits you need to multiply result by 100. If e3 has 3 digits you need to multiply result by 1000.This assumes that the problem must be solved mathematically instead of just converting everything to str and concatenating (and maybe converting the result tack to an int). |