5

I am trying to convert

a = "546"

to

a = 546

without using any library functions.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Dennis M.
  • 107
  • 1
  • 2
  • 7
  • 6
    Presumably "library functions" includes builtin functions like `int`, right? Considering that this is homework, we'd like to see what you've thought about/found/tried so far, and what you got stuck with. – Izaak van Dongen Sep 25 '17 at 13:10
  • 2
    Maybe you should ask what google terms your teacher thought you'd find useful and share what you did search for so we know what you've looked at that isn't helpful? Apart from that - what's your understanding of what a "library functions" is? – Jon Clements Sep 25 '17 at 13:10
  • 3
    Looking at the final version of technically correct answer, and that it took 2-3 iterations to root away all the builtin functions, I must say this is a pretty sadistic task. – luk32 Sep 25 '17 at 13:33

8 Answers8

21

The "purest" I can think of:

>>> a = "546"
>>> result = 0
>>> for digit in a:
        result *= 10
        for d in '0123456789':
            result += digit > d

>>> result
546

Or using @Ajax1234's dictionary idea if that's allowed:

>>> a = "546"
>>> value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
>>> result = 0
>>> for digit in a:
        result = 10 * result + value[digit]

>>> result
546
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • Why multiplying by the result by 10 though ? because i don't see any effect given that the original value of the result variable is zero – E-WAVE Aug 09 '21 at 15:16
4

You can keep a dictionary that stores the string and integer values of a numeric key, and then iterate over the string. While iterating over the string, you can use enumerate to keep track of the index and then raise 10 to that power minus 1 and then multiply by the corresponding key from the dictionary:

a = "546"
length = 0
for i in a:
   length += 1
d = {'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
count = 0
counter = 0
for i in a:
   count += (10**(length-counter-1)*d[i])
   counter += 1
print(count)

Output:

546
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 1
    and `enumerate` :) – dabadaba Sep 25 '17 at 13:24
  • I completely forgot about the OP's requirement barring all builtin functions, not just `int` :) Please see my recent edit. – Ajax1234 Sep 25 '17 at 13:25
  • 2
    `range` and `len` are also built-in functions aren't they? you can just do `for i in a` – dabadaba Sep 25 '17 at 13:26
  • 1
    You might be able to avoid using `range` or `len` by first slicing with `[::-1]` and then incrementing the power manually. However, I think that the builtin functions thing is probably more of a problem with the question's phrasing than this answer - where does a function stop? Isn't a list indexing a call to `list.__getitem__`? – Izaak van Dongen Sep 25 '17 at 13:27
  • I mean, I think we're all probably overkilling it. I guess the teacher was trying to disuade students from using `int()`, but I'd think using any other common built-in function like `range` or `len` is fine. – dabadaba Sep 25 '17 at 13:33
  • @dabadaba I agree, but I think it also makes sense to cover every angle of the problem and how it can be interpreted. – Ajax1234 Sep 25 '17 at 13:33
  • @IzaakvanDongen And isn't `a + b` really a call to `a.__add__(b)`? :-). So yeah, I don't think we can get **anywhere** if we don't allow such stuff that at least doesn't "look like" function calls. That said, I did go a bit further in mine. – Stefan Pochmann Sep 25 '17 at 13:58
3

The trick is that 546 = 500 + 40 + 6, or 5*10^2 + 4*10^1 + 6*10^0.

Note how the exponent is just the index (in reverse). Using that, you can generalize this approach into a function:

def strToInt(number):
    total = 0                             # this is where we accumulate the result
    pwr = len(number) - 1                 # start the exponent off as 2
    for digit in number:                  # digit is the str "5", "4", and "6"
        digitVal = ord(digit) - ord('0')  # using the ascii table, digitVal is the int value of 5,4, and 6.
        total += digitVal * (10 ** pwr)   # add 500, then 40, then 6
        pwr -= 1                          # make sure to drop the exponent down by one each time
    return total

And you can use it like so:

>>> strToInt("546")
546
Nate Jenson
  • 2,664
  • 1
  • 25
  • 34
1
def stringToInt(s):
    result = 0
    value = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    for digit in s:
        result = 10 * result + value[digit]

    return result
Shyambeer Singh
  • 318
  • 2
  • 9
0
def int(a):
ty = a.__class__.__name__
out = 0
di = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
      '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
if ty not in ("str", "int", "float", "bytes"):
    raise TypeError("unsupported format")
if a.__class__ == float:
    return a.__floor__()
elif a.__class__ == int:
    return a
else:
    ind = 0
    for val in a[::-1]:
        if val not in di:
            raise ValueError("invalid input")
        out += di[val]*(10**ind)
        ind += 1
        #print(out, di[val])
    return out
print(int("55"))
55
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
-1

You can loop through the string and perform the operation on each character using ord.

example:

a="546"
num=0
for i in a:
     num = num * 10 + ord(i) - ord('0')
faizan baig
  • 1,283
  • 15
  • 21
-1
astr = "1234"
num = 0
for index,val in enumerate(astr[::-1]):
    res = (ord(val) - ord('0')) * (10 ** index)
    num += (res)
Deep
  • 1
-1
a=input()
r=0
for i in a:
  r=r*10+(ord(i)-ord("0"))
print(r)
print(type(r))
AlexK
  • 2,855
  • 9
  • 16
  • 27
Kirti
  • 1