假设元素(值在 1 到 256 之间)以这种方式堆叠 -:
c1----------c2----------c3----------c4
f1----------f2----------f3 (f: first level distance)
s1-----------s2 (s: second level distance)
t1 (t: third level distance)
我们的目标是使用 c1、c2、c4 和 t1 找到 c3 的值。 使用前一个距离级别中的 2 个距离值计算不同级别的距离。
例如-:
f1 = Distance_Calculation(Variable, No_In_1_Group, c1, c2) or
s2 = Distance_Calculation(Variable, No_In_1_Group, f2, f3) or
t1 = Distance_Calculation(Variable, No_In_1_Group, s1, s2)
考虑
Variable = 2 & No_In_1_Group = 8
进行上述计算。附件是例子。
Comb_1 和 Comb_2 的 Direct_Distance 使用以下方法计算 -:
Comb_1------------------------------Comb_2
Direct_Distance
def Distance_Calculation(Variable, No_In_1_Group, Comb_1, Comb_2):
"""This function gives the value of "*Direct_Distance*" if Comb_1 & Comb_2 are known."""
if (Comb_2 >= Comb_1):
return Comb_2 - Comb_1 + 1
else:
return pow(Variable, No_In_1_Group) - Comb_1 + Comb_2 + 1
"""If Comb_1 & Direct_Distance are known, then Comb_2 will be calculated using this function"""
def Reverse_Distance_Calculation(Variable, No_In_1_Group, Comb_1, Direct_Distance):
if (Comb_1+Direct_Distance-pow(Variable, No_In_1_Group)-1 <= 0 and Direct_Distance-1 >= 0):
return Comb_1 + Direct_Distance - 1
else:
return Comb_1 + Direct_Distance - pow(Variable, No_In_1_Group) - 1
以类似的方式,计算所有
f,s & t
值。
注意:所有值都将以黑白显示
1 to Variable**No_In_1_Group
*
现在,如果我说,我有
c1, c2, c4 & t1
值,我必须计算 c3
的值,这样所有的值都可以符合上面的排列(树形图),谁能帮我写一个高效的 Python这个的代码?
我的尝试 -:
def get_unknown_element(c1, c2, c4_final, t1_final):
c4 = c4_final
base_reminder_index = Variable**No_In_1_Group
for i in range(1,base_reminder_index+1):
c3 = i
f1 = Distance_Calculation(Variable, No_In_1_Group, c1, c2)
f2 = Distance_Calculation(Variable, No_In_1_Group, c2, c3)
f3 = Distance_Calculation(Variable, No_In_1_Group, c3, c4)
s1 = Distance_Calculation(Variable, No_In_1_Group, fld1, fld2)
s2 = Distance_Calculation(Variable, No_In_1_Group, fld2, fld3)
t1 = Distance_Calculation(Variable, No_In_1_Group, sld1, sld2)
if (t1 == t1_final):
return i
return -1
但是这种方法不是很有效,因为它在每次运行中最多需要 256 次迭代,并且我已经运行此代码超过 1000 次以获得我想要的结果。如果有人可以建议任何可以大大减少迭代的有效方法,那就太好了。
例如-如果
c1 = 49, c2 = 52, c4 = 201 & t1 = 91
,则c3 will be 158
。检查下面的例子。
我会首先考虑
Variable
和No_In_1_Group
作为一个输入m
,就像你的例子中的m=256
。
计算可以从上到下展开如下,始终考虑到表达式要考虑模256:
c1 c2 c3 c4
\ / \ / \ /
(c2-c1+1) (c3-c2+1) (c4-c3+1)
\ / \ /
(c3-2c2+c1) (c4-2c3+c2)
\ /
(c4-3c3+3c2-c1+1)
底部表达式必须等于 t1(mod 256),因此要根据 c3(未知数)重写它:
3c3 = c4 + 3c2 - c1 - t1 + 1 (mod m)
因为左边的系数 3,我们实际上有 3 个候选解这个方程:
c3 = [c4 + 3c2 - c1 - t1 + 1 (mod m)] / 3
or [c4 + 3c2 - c1 - t1 + 1 (mod m) + m] / 3
or [c4 + 3c2 - c1 - t1 + 1 (mod m) + 2m] / 3
用 Python 重写:
def solve (c1, c2, c4, t1, m):
triple_c3 = (c4 + 3*c2 - c1 - t1 + 1) % m
if triple_c3 % 3:
triple_c3 += m
if triple_c3 % 3:
triple_c3 += m
if triple_c3 % 3:
return None # No solution
return triple_c3 // 3
c3 = solve(49, 52, 201, 91, 256)
print(c3) # 158