Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coverting strings to decimal with a radix

Tags:

python-3.x

I'm just getting into Empire of Code and I've come across a problem that I don't understand at all. Could someone do an ELI5 for this? I'm not sure even where to start with making the function. This is the problem:

You are given a positive number as a string along with the radix for it. Your function should convert it into decimal form. The radix is less than 37 and greater than 1. The task uses digits and the letters A-Z for the strings.

Watch out for cases when the number cannot be converted. For example: "1A" cannot be converted with radix 9. For these cases your function should return -1.

Input: Two arguments. A number as string and a radix as an integer.

Output: The converted number as an integer.

Example:

convert("AF", 16) == 175
convert("101", 2) == 5
convert("101", 5) == 26
convert("Z", 36) == 35
convert("AB", 10) == -1

What exactly is it asking? I don't know enough about number bases to have even the slightest grip on this.

like image 487
acollection_ Avatar asked Oct 19 '22 14:10

acollection_


1 Answers

Our number system is base 10. There are 10 possible digits you can use to represent numbers, 0-9. Once you get to 9, you need an extra digit to represent a larger number (10).

Other systems are, of course, possible. Some famous ones:

  • Base 2 ("binary"): Only digits are 0 and 1. Once you get to 2 you need more digits (10).
  • Base 8 ("octal"): Only digits are 0-7. Once you get to 8 you need more digits (10).

There are also bases higher than 10. Because we don't have numbers for these normally we pull in letters to substitute. The most common one here is base 16 (aka "hexadecimal"), which uses 0-9 followed by A-F, where A=10, B=11, and so on out to F=15. Once you get to 16, you need more digits (10).

When we say "Base N", the "N" there is the radix (technical term from mathematics). You need the radix for cases where there is ambiguity. For example, I just showed you four different numbers that '10' can represent, depending on the base you're working in. (In fact, you may have noticed that if you follow the normal conventions as I have here, '10' always represents the number corresponding to the base you're working in: 2 in binary, 8 in octal, 16 in hex, etc.)

You can also make some inferences based on having too many digits. For example, "2" is not a valid number in base 2 (binary), because the only valid digits are 0 and 1. Likewise, "1A" cannot be represented in base 9 because necessarily the only valid digits there would be 0-8. The "A" doesn't become necessary until you hit at least base 11.

Hope that helps.

like image 85
Two-Bit Alchemist Avatar answered Jan 04 '23 06:01

Two-Bit Alchemist