1

Here is the problem:

number = 1101
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#The number above represents a binary number. It will always
#be up to eight digits, and all eight digits will always be
#either 1 or 0.
#
#The string gives the binary representation of a number. In
#binary, each digit of that string corresponds to a power of
#2. The far left digit represents 128, then 64, then 32, then
#16, then 8, then 4, then 2, and then finally 1 at the far right.
#
#So, to convert the number to a decimal number, you want to (for
#example) add 128 to the total if the first digit is 1, 64 if the
#second digit is 1, 32 if the third digit is 1, etc.
#
#For example, 00001101 is the number 13: there is a 0 in the 128s
#place, 64s place, 32s place, 16s place, and 2s place. There are
#1s in the 8s, 4s, and 1s place. 8 + 4 + 1 = 13.
#
#Note that although we use 'if' a lot to describe this problem,
#this can be done entirely boolean logic and numerical comparisons.
#
#Print the number that results from this conversion.

Here is my code

##Add your code here!

number_str = str(number) # "1101"
first_num = int(number_str[-1]) * 1
#print("first num:", first_num)
second_num = int(number_str[-2]) * 2
#print("second num:", second_num) 
third_num = int(number_str[-3]) * 4
#print("Third num:", third_num)
fourth_num = int(number_str[-4]) * 8
#print("fourth num:", fourth_num)
fifth_num = int(number_str[-5]) * 16
sixt_num = int(number_str[-6]) * 32
seventh_num = int(number_str[-7]) * 64
decimal = first_num + second_num + third_num + fourth_num + fifth_num + sixt_num + seventh_num
print(decimal)

The error I got was: We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left: We tested your code with number = 1010111. We expected your code to print this: 87 However, it printed this: 7


I understand that I hard-coded this problem to accommodate 4 digits. I would like this to work for any given numbers without throwing an IndexError: string index out of range.

I appreciate your help.

2
  • Your problem statement suggests using "numerical comparisons", which you do not do. If you use numerical operations to isolate digits, your "string index" problem goes away. Commented Feb 5, 2024 at 18:43
  • All you need is a loop, to pull off the digits one by one. Commented Feb 5, 2024 at 18:52

2 Answers 2

3

I don't like doing people's homework for them, but in this case I think the example says more than an explanation.

You do this conversion one character at a time, from left to right. At each step, you shift the result left by one, and if the digit is '1', you add it in.

number = 1011
decimal = 0
for c in str(number):
    decimal = decimal * 2 + (c=='1')
print(decimal)

If that's too clever, replace (c=='1') with int(c).

FOLLOWUP

This is what I've been trying to tell you. The code you have will actually do the correct conversion, but it only works if you have exactly 7 digits. All you need to do is change the code so you CHECK the number of digits before you try one:

number = 1010111

num = str(number)
result = int(num[-1]) * 1
if len(num) > 1:
    result += int(num[-2]) * 2
if len(num) > 2:
    result += int(num[-3]) * 4
if len(num) > 3:
    result += int(num[-4]) * 8
if len(num) > 4:
    result += int(num[-5]) * 16
if len(num) > 5:
    result += int(num[-6]) * 32
if len(num) > 6:
    result += int(num[-7]) * 64
if len(num) > 7:
    result += int(num[-8]) * 128

print(result)
Sign up to request clarification or add additional context in comments.

10 Comments

Hi Tim, Thanks for your reply. I am not allowed to use loops. How do I implement the same with numerical comparison?
You CANNOT handle an arbitrary number of digits without using a loop. it's impossible. Your second code snippet could be made to work by using if len(number_str) > 4 before you try to access number_str[-4], but that's not a good design.
That is the challenge I am facing. This problem is part of Georgia Tech's Intro to Programming first module. So far it covers just numerical expression and boolean logic. The next chapter is about control structure and functions, and so on. so, this problem should be solved by numerical comparisons.
The following is a problem where I converted number to binary: number = 215 bin_128 = int(number >= 128) bin_64 = int(number % 128 >= 64) bin_32 = int(number % 64 >= 32) bin_16 = int(number % 32 >= 16) bin_8 = int(number % 16 >= 8) bin_4 = int(number % 8 >= 4) bin_2 = int(number % 4 >= 2) bin_1 = int(number % 2 >= 1) print(str(bin_128) + str(bin_64) + str(bin_32) + str(bin_16) + str(bin_8) + str(bin_4) + str(bin_2) + str(bin_1)) Now, I need to revise the process but my understanding is so limited.
Did you read what I wrote? The code you have is fine, as long as you CHECK the length so you don't try to read digit [-7] when there aren't seven digits. The output you show ("it printed this: 7") could not have been caused by the code you show. That code would have produced the correct answer for 1010111, but would have failed with 1101 because of an index out of range error.
|
0

Don't over-think it with how many powers of 2 you need :


 1  function ____(__, ___, _) {

 1      split(__, ___, _ = "")

 7      for (__ in ___)
 7          _ += ___[__] + _

 1      return _
    }

1010111 87

You don't need to know how long the input is (as long as precision allows), and the values of powers of 2. In fact, you don't even need to perform a single multiplication or left-shift at all in order to convert binary strings to decimal.

This code does nothing except repeatedly adding a full copy of its accumulator value as well as the next bit, allowing one to perform the conversion using a total of just 3 variables (inclusive of the one required for accepting function input) -

___ : The iterator array

 __ : First as the input string, 

      then also as index of iterator

  _ : First as the empty string regex for splitting the input 
      into iterator array (so each digit occupies its own cell),
      
      then also as the accumulator for the iterator

* It matters not what language this function is in as presented, because it's generic enough it's easily portable to any language of choice. It can just as easily convert this 53-bit binary string back into a 16-(decimal)-digits prime :

 1  function ____(__, ___, _) {

 1      split(__, ___, _ = "")

53      for (__ in ___)
53          _ += ___[__] + _

 1      return _
    }

11111001011110101011110100110010111001001110001110001 8777777777777777

The same approach can just as easily be adapted for conversion of other bases, such as octals :

function _8_to_10_(__, ___, _) {

    split(__, ___, _ = "")

    for (__ in ___)
        _ += ___[__] + (_ += _ += _)

    return _
}

371365364627116161 8 8777777777777777

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.