|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 三与七之间 于 2018-4-25 17:36 编辑
我是在做小甲鱼零基础入门学习python第44降动手00的时候编的如下代码,背景:编写计时器,大致思路就是程序开始运行时以及结束运行时都可以生成一个有6个元素的列表(分别为【年,月,日,时,分,秒】),然后把两个列表按个儿相减就可以得到程序运行多久,但是如果开始计时的时间是2022年2月22日16:30:30,停止的时间是2025年1月23日15:30:30的话,就会出现负数,为了解决这个问题编以下代码:
#trans(L)这个函数的大致思路就是先判断是否为负数,是的话,看其是月日天时分秒里的那个数,然后让他的前个元素减1,他自己呢做减法
#t(L)这个函数里我放了一个递归,因为也许转化一次之后列表里还是有负数,所以需要再进行转化,所以就编了下边几句,可是运行结果却很悲惨,栈溢出了。。。。瞅了半天没想通 哪出错了,感觉不应该啊。。。。
- L2 = []
- def trans(L):
- for index in range(6):
- if L[index] >= 0:
- L2.append(L[index])
- else:
- if index == 1:
- L2[index - 1] -= 1
- L2.append((12 + L[index]))
- elif index == 2:
- L2[index - 1] -= 1
- L2.append((30 + L[index]))
- elif index == 3:
- L2[index - 1] -= 1
- L2.append((24 + L[index]))
- elif index == 4:
- L2[index - 1] -= 1
- L2.append((60 + L[index]))
- elif index == 5:
- L2[index - 1] -= 1
- L2.append((60 + L[index]))
- return L2
- def t(L):
- k = 0
- for each in L:
- if each < 0:
- k += 1
- else:
- continue
- if k == 0:
- return L
- else:
- L_new = trans(L)
- return t(L_new)
- L = [1, -2, 0, -1, 10, 10]
- print(t(L))
复制代码
- def trans(L):
- # 做减法的时候,应该从末位开始算起,这样才方便退位
- L2 = L[:]
- for index in range(5, 0, -1):
- if L[index] < 0:
- if index == 1:
- L2[index - 1] -= 1
- L2[index] = 12 + L[index]
- elif index == 2:
- L2[index - 1] -= 1
- L2[index] = 30 + L[index]
- elif index == 3:
- L2[index - 1] -= 1
- L2[index] = 24 + L[index]
- elif index == 4:
- L2[index - 1] -= 1
- L2[index] = 60 + L[index]
- elif index == 5:
- L2[index - 1] -= 1
- L2[index] = 60 + L[index]
- return L2
- def t(L):
- for each in L:
- if each < 0:
- L_new = trans(L)
- return t(L_new)
- return L
- L = [1, -2, 0, -1, 10, 10]
- print(t(L))
复制代码
|
|