G
G
g1shy \(#_#)/2021-03-17 21:44:59
Python
g1shy \(#_#)/, 2021-03-17 21:44:59

Problem with replacing list item?

Given the conditions of the problem:

The algorithm receives a natural number N > 1 as input and builds a new number R from it as follows:
1. A binary representation of the number N is constructed.
2. Instead of the last (rightmost) binary digit, the second digit of the binary representation from the left is written twice.
3. The result is converted to decimal.
Example. The number N = 19 is given. The algorithm works as follows:
1. Binary notation of the number N: 10011.
2. The second digit from the left is 0, the unit at the end of the entry is replaced by two zeros, the new entry is 100100.
3. The result of the algorithm is R = 36.

With What is the smallest number N that will result in R > 76 as a result of the algorithm? Write your answer in decimal notation.


Here is how I tried to solve it:

for n in range(1, 1000):
    r = [str(bin(n))]
    r[-1] = r[3] * 2
    while int(r, 2) > 76:
        n += 1
print(int(r, 2))


Pycharm swears and produces such errors:

60524de1ddeac955924903.png

60524defa839f616461511.png

I would be very grateful if you can help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-03-17
@SoreMix

Well,

  1. bin() returns a string anyway, so there is no need to convert string to string.
  2. bin() returns a string prefixed with "0b", so it needs to be truncated.
  3. why add the result of bin() to the list?.
  4. There is no element at index 3, because there is only one element - the result of bin()
  5. Even if you do not add bin() to the list, but work with it right away, there will be an error, because element with index 3 will only appear if n > 7
  6. while is not needed
  7. the second digit from the left has an index not 3, but 1
  8. an element in a string cannot be replaced via an index
  9. no response is output, the loop is not interrupted
  10. print() doesn't make sense

A
Andrey Dugin, 2021-03-17
@adugin

binary = bin(19)
int(binary[:-1] + binary[3] * 2, 2)  # 36

And you can also do this (maybe there is an error - check):
N = 19
L = N.bit_length() - 2
(N >> 1 << 2) | 0b11 * ((N & 1 << L) >> L)  # 36

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question