Python Forum
list digit into number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list digit into number
#1
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 result
Now 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
Reply
#2
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]))
Output:
21121
Reply
#3
Play the part of the computer to see why your program doesn't work
Output:
digits = [1, 2, 12, 123] e1 result result*10 result*10+e1 1 0 0 1 2 1 10 12 12 12 120 132 123 132 1320 1443
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).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Displaying list correspond to the column number danlopek14q 9 3,975 Aug-27-2021, 04:32 AM
Last Post: naughtyCat
  How to convert every even number in a list to odd? Bruizeh 4 3,761 Aug-27-2021, 03:04 AM
Last Post: naughtyCat
  Get the biggest number from a two dimensional list rs74 13 4,069 Aug-09-2020, 04:02 PM
Last Post: deanhystad
  Frequency in first digit from csv file, NO IMPORT bryan0901 6 2,838 May-28-2020, 09:50 AM
Last Post: bryan0901
  How can I print the number of unique elements in a list? AnOddGirl 5 3,296 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  integer representing a 10-digit phone number critter70 5 27,544 May-17-2019, 09:29 AM
Last Post: saravanatn
  Four-digit number text translation. soz 3 2,691 May-13-2019, 03:02 PM
Last Post: buran
  create three digit numbers Krszt 4 4,488 Dec-09-2018, 03:12 PM
Last Post: ThePhi
  Sum of digit in a string MEH012 1 9,478 Apr-20-2018, 02:13 AM
Last Post: Larz60+
  Multiplying number in a list in an order pythoneer 12 6,612 Mar-23-2018, 08:21 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020