44.3k views
4 votes
In convert.py, define a function decimalToRep that returns the representation of an integer in a given base.

The two arguments should be the integer and the base.
The function should return a string.
It should use a lookup table that associates integers with digits.
A main function that tests the conversion function with numbers in several bases has been provided.

An example of main and correct output is shown below:

User Alonp
by
7.8k points

1 Answer

6 votes

Answer:

def decimalToRep(integer, base):

# Define a lookup table of digits

digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# Handle the special case of 0

if integer == 0:

return "0"

# Initialize an empty list to hold the digits in the new base

new_digits = []

# Convert the integer to the new base

while integer > 0:

remainder = integer % base

integer = integer // base

new_digits.append(digits[remainder])

# Reverse the list of new digits and join them into a string

new_digits.reverse()

new_string = "".join(new_digits)

return new_string

def main():

integer = int(input("Enter an integer to convert: "))

base = int(input("Enter the base to convert to: "))

print(decimalToRep(integer, base))

if __name__ == "__main__":

main()

Step-by-step explanation:

This code prompts the user to enter an integer to convert and a base to convert it to using the input() function. It then calls the decimalToRep function with the input values and prints the resulting output. The if __name__ == "__main__" line at the bottom of the code ensures that the main function is only called when the script is run directly, not when it is imported as a module.

Here's an example input/output:

Enter an integer to convert: 123

Enter the base to convert to: 16

7B

User Tiamo Idzenga
by
8.5k points