How to write a function to calculate the proportion for a different combination of numbers (using python 3+)

I am trying to find a suitable value for p and q to decode the hidden text of a BMP image file. The corresponding code is as follows:

def est_extract():

    image_byte_array = est_get_bytes_containing_message()

    header_len = 54

# CODE TO FIND THE CORRECT VALUES OF p and q


# ********************************************************

   message_bit_array = est_extract_bits_from_image(
    image_byte_array, header_len, p, q )

    message_byte_array = est_convert_bits_to_bytes( message_bit_array )

    est_write_message_text( message_byte_array )

if __name__ == '__main__':

    est_extract()

I struggle with the code to find the corresponding p and q value. And I need to do this by following these steps:

  • I need to write a function called est_bit_proportionthat takes a Python array as an argument and calculates the fraction of units in it. And I'm going to apply this to the existing one message_bit_arrayfor a specific choice of values ​​for pand q.

  • , p q, p = 1, 2, 3 q = 1, 2, 3. , , .

  • p q est_bit_proportion, .

  • 1 0,5, . p q .

for a in range(1, 4, 1):

        for b in range(1, 4, 1):
           bp = a/b
           print( "p =", a, "q =", b, "bp =", "%6.3f" % bp)

           if (bp > .5 and bp < 1):
            p = a
            q = b
            print( "The answer is:", "p =", p, "q =", q)

. :

p = 1 q = 1 bp =  1.000
p = 1 q = 2 bp =  0.500
p = 1 q = 3 bp =  0.333
p = 2 q = 1 bp =  2.000
p = 2 q = 2 bp =  1.000
p = 2 q = 3 bp =  0.667
The answer is: p = 2 q = 3
p = 3 q = 1 bp =  3.000
p = 3 q = 2 bp =  1.500
p = 3 q = 3 bp =  1.000

:

p = 1 q = 1 bp =  1.000
p = 1 q = 2 bp =  0.500
p = 1 q = 3 bp =  0.333
p = 2 q = 1 bp =  2.000
p = 2 q = 2 bp =  1.000
p = 2 q = 3 bp =  0.667
p = 3 q = 1 bp =  3.000
p = 3 q = 2 bp =  1.500
p = 3 q = 3 bp =  1.000
The answer is: p = 2 q = 3

python . , - , 1 4.

+4
1

, . itertools.product()

In [50]: [{'p':i, 'q': j} for i, j in product(range(1, 4), range(1, 4)) if 0.5< i/j <1]
Out[50]: [{'p': 2, 'q': 3}]

, :

def est_bit_proportion(arr1, arr2):
    all_results = []
    answers = []
    for i, j in product(arr1, arr2):
        bp = round(i/j, 2)
        if 0.5< i/j <1:
            answers.append({'p':i, 'q': j, 'bp': bp})
        all_results.append({'p':i, 'q': j, 'bp': bp})
    return {'all_results': all_results, 'answers': answers}

:

In [65]: est_bit_proportion(range(1, 4), range(1, 4))
Out[65]: 
{'all_results': [{'p': 1, 'q': 1, 'bp': 1.0},
  {'p': 1, 'q': 2, 'bp': 0.5},
  {'p': 1, 'q': 3, 'bp': 0.33},
  {'p': 2, 'q': 1, 'bp': 2.0},
  {'p': 2, 'q': 2, 'bp': 1.0},
  {'p': 2, 'q': 3, 'bp': 0.67},
  {'p': 3, 'q': 1, 'bp': 3.0},
  {'p': 3, 'q': 2, 'bp': 1.5},
  {'p': 3, 'q': 3, 'bp': 1.0}],
 'answers': [{'p': 2, 'q': 3, 'bp': 0.67}]}
0

Source: https://habr.com/ru/post/1693465/


All Articles