首页 > 解决方案 > 那段代码的时间复杂度是多少?

问题描述

这段代码的时间复杂度是多少?如何改进此代码?

import random

n=input('choose one h/t? ')
v=random.randint(0,1)

if n=='h':
    if v==0:
        print('Hurrah!!! You win. Result is Head.')
    else:
        print('alas!!! You lose. Result is Tell.')
elif n=='t':
    if v==1:
        print('hurrah!!! You win. Result is Tell.')
    else:
        print('alas!!! You lose. Result is Head.')

标签: python-3.xtime-complexitycoding-style

解决方案


我建议你:

  • 要么合并 h 和 v if 得到一个 if only
  • 要么首先确定它是 ah 还是 t 案例,在其他 if 之外。然后,使用一个函数来测试其他部分。

实际上,只需重构以使用函数,因为您正在重复自己。


推荐阅读