pythonarraysfunctionlogicnumber-systems

Why am i getting typeerror for running a simple function in a loop?


i am writing a function to take an ip address, convert each of its parts(separated by '.') into an 8 - bit binary digit. then i want to combine all the binary numbers and get one big 32 bit number, and i want to convert it to decimal. my convert function works correctly when tested as a standalone, but when it is run in a loop, it gives me the TypeError: 'str' object cannot be interpreted as an integer error.

this is the question: (from codewars - IPv4 to int32)

Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).

1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 4th octet 1 has the binary representation: 00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001

Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.

Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number.

ip_to_int32("128.32.10.1") => 2149583361

def convert(x):
    return int(bin(x).replace("0b", ''))

def ip_to_int32(ip):
    data = ip.split('.')
    converted = []
    for i in range(len(data)):
        converted.append(convert(data[i]))
    str = ''
    for i in converted:
        str += i
    num = int(str)
    return dec(num).replace('0d', '')

This is the error i get:

Traceback (most recent call last):
  File "tests.py", line 4, in <module>
    test.expect(ip_to_int32("128.114.17.104") == 2154959208, "wrong integer for ip: 128.114.17.104")
  File "/workspace/default/solution.py", line 8, in ip_to_int32
    converted.append(convert(data[i]))
  File "/workspace/default/solution.py", line 2, in convert
    return int(bin(x).replace("0b", ''))
TypeError: 'str' object cannot be interpreted as an integer

and this is the test file:

test.describe("Basic Tests")
test.expect(ip_to_int32("128.114.17.104") == 2154959208, "wrong integer for ip: 128.114.17.104")
test.expect(ip_to_int32("0.0.0.0") == 0, "wrong integer for ip: 0.0.0.0")
test.expect(ip_to_int32("128.32.10.1") == 2149583361, "wrong integer for ip: 128.32.10.1")

thanks for the help!


Solution

  • The problem is that the x argument to convert() is a string. You can't use that as an argument to bin().

    Since x is already a string representation of an integer, converting it to binary then back to decimal is unnecessary. You can just return int(x) (and it doesn't really need to be a separate function).

    There are a number of other ways to improve your code, but as this is a Codewars challenge, I'll leave that to you.