ramailo sathi
ramailo sathi

Reputation: 355

Join a list of integers

The problem : Design an algorithm to convert a string to an integer:

My approach:

string = '1221'
dictionary = {'1':1,'2':2}

string2 = [dictionary[w] for w in string] 

print "".join(string2)

This code won't work because (apparently) join() is a string function. How do I join the elements of the list if they are all integers? (Can't use str() and int())

Upvotes: 0

Views: 790

Answers (3)

memebrain
memebrain

Reputation: 403

the int function will convert a string to integers if each character is a numeric character

int('1221')

Upvotes: 0

TsReaper
TsReaper

Reputation: 855

We can use addition and multiplication to achieve this.

s = '1234'
ans = 0

for c in s:
    ans = ans*10 + ord(c)-ord('0')

print(ans)

This method will work because 1234 = ((1 * 10 + 2) * 10 + 3) * 10 + 4.

As '0' ~ '9' are consecutive in ascii, so we can use ord(c)-ord('0') to get the value of the digit.

EDIT

It's the same if you want to get the int from string2

string = '1221'
dictionary = {'1': 1, '2': 2}
string2 = [dictionary[w] for w in string]
ans = 0

for x in string2:
    ans = ans*10 + x

print(ans)

Upvotes: 2

DYZ
DYZ

Reputation: 57085

def atoi(s): # ASCII to Integer, a "traditional" name for such function
    return sum(10**(len(s)-p-1) * (ord(x) - ord('0')) for p,x in enumerate(s))

atoi("123")
#123

Upvotes: 1

Related Questions