I have a list of octal numbers that I want to be converted to decimal. Here's my class with what I've done so far:
class Octal:
#Reads in the file into numberList, converting each line into an int.
def __init__(self):
list = []
file = open("Number Lists/random_numbers3.txt")
for line in file:
list.append(int(line))
self.numberList = list
file.close()
#Convert numberList to decimal
def dec_convert(self):
decimal = 0
decimalList = []
for line in self.numberList:
temp = str(line)
i = 0
while i < len(temp):
digit = int(temp[i])
item = (digit * (8 ** (len(temp) - i)))
decimal = decimal + item
i += 1
decimalList.append(decimal)
return decimalList
def get_list(self):
return self.numberList
I read in the numbers from a file, that works fine. But I don't think that my dec_convert() function actually works. It just keeps running and doesn't finish.
It looks completely terrible and hard to read, so I was wondering if there was a simpler way of converting each octal number in the list to a decimal number?
Here is an easy solution that uses the built-in int()
constructor rather your dec_convert()
function.
class Octal:
def __init__(self):
with open("Number Lists/random_numbers3.txt") as fp:
self.numberList = map(lambda x:int(x,8), fp)
def get_list(self):
return self.numberList
if __name__=="__main__":
o = Octal()
print(o.get_list())