代码优化->将两个功能合并为一个功能

时间:2020-05-25 19:09:03

标签: python-3.x

为我编程还很早,并希望通过此简单代码获得一些帮助:

@Throws(IOException::class)
fun decompress(str: String?): String? {
    if (str == null || str.length == 0) {
        return str
    }
    println("Input String length : " + str.length)
    val gis = GZIPInputStream(ByteArrayInputStream(Base64.decode(str, Base64.DEFAULT)))
    val outStr = ""
    val out = ByteArrayOutputStream()
    val buffer = ByteArray(256)
    var n: Int
    while (gis.read(buffer).also { n = it } >= 0) {
        out.write(buffer, 0, n)
    }
    println("Output String lenght : " + outStr.length)
    return String(out.toByteArray())
}

这两个功能之间的唯一区别是同时用于循环和分配临时键。所以想将两者都合并到我的类中的一个函数中。我尝试在循环后为部分代码创建一个函数,然后在循环中调用它,但是没有用。

1 个答案:

答案 0 :(得分:0)

您尝试过吗:

attempts_counter = 1

def process(tempKey, sock):
  attempts_counter += 1
  request = UDS()/UDS_SA(securityAccessType=[0x02], securityKey = tempKey)
  response = sock.sr1(request, timeout=0.3, verbose=False)
  print(request, response)

def force():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            while progress_time < penetration_time:
                tempKey = test.random_key(8)
                process(tempKey, sock)
            progress_time  = int(time.time() - start_time)

def Memory():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            for tempKey in range (0x0F):
                process(tempKey, sock)
            progress_time  = int(time.time() - start_time)