Python练习题答案: 比较大国【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

比较大国【难度:2级】:

答案1:

from math import log
def compare_powers(n1, n2):
    return cmp(log(n2[0])*n2[1], log(n1[0])*n1[1])

答案2:

def compare_powers((x, a), (y, b)):
    return cmp(b*log(y), a*log(x))

答案3:

from math import log
def compare_powers(n1, n2):
    (x, a), (y, b) = n1, n2
    return cmp(b*log(y), a*log(x))

答案4:

def compare_powers(n1,n2):
  from math import log
  return -cmp(n1[1]*log(n1[0]), n2[1]*log(n2[0]))

答案5:

from math import log

def compare_powers((x, a), (y, b)):
    return cmp(b*log(y), a*log(x))

答案6:

from math import log
def compare_powers(n1, n2):
  val = n2[1] * log(n2[0]) - n1[1] * log(n1[0])
  return -1 if val < 0 else 1 if val > 0 else 0

答案7:

from math import log

def compare(x, y):
    if x == y:
        return 0
    if x < y:
        return 1
    if x > y:
        return -1
        
def compare_powers(x, y):
    a, c = x
    b, d = y
    x = (c * log(a)) / log(2)
    y = (d * log(b)) / log(2)
    return compare(x, y)

答案8:

from math import log
def compare_powers((n1, p1), (n2, p2)):
    return cmp(p2 * log(n2), p1 * log(n1))

答案9:

from math import log
def compare_powers(n1,n2):
    if   n2[1]*log(n2[0]) > n1[1]*log(n1[0]):  return  1
    elif n2[1]*log(n2[0]) < n1[1]*log(n1[0]):  return -1
    else:                                      return  0

答案10:

from math import log

def compare_powers(n1,n2):
    return cmp(n2[0],1) if n1[0] == 1 else cmp(log(n2[0],n1[0])*n2[1],n1[1])

答案11:

import math

def cmp(a, b):
    return (a < b) - (a > b)

def compare_powers(n1,n2):
    x_base, x_power = n1
    y_base, y_power = n2

    if x_power > y_power:
        y_power = y_power / (x_power/2)
        x_power = 2
    else:
        x_power = x_power / (y_power/2)
        y_power = 2

    return cmp(x_base ** x_power, y_base ** y_power)

答案12:

import math
def compare_powers(n1,n2):
    res1 = n1[1] * math.log(n1[0])
    res2 = n2[1] * math.log(n2[0])
    
    return -1 if res1 > res2 else 0 if res1 == res2 else 1



Python基础训练营景越Python基础训练营QQ群

Python练习题答案: 比较大国【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战_第1张图片
欢迎各位同学加群讨论,一起学习,共同成长!

你可能感兴趣的:(python面试题库和答案,python编程练习,算法,优化,Python编程初级练习题)