所以这个kata说:
您必须创建一个函数,该函数采用正整数,并返回由相同数字组成的下一个更大的数字:
12 ==> 21 513 ==> 531 2017 ==> 2071
如果不能使用这些数字组成更大的数字,则返回-1:
9 ==> -1 111 ==> -1 531 ==> -1
尽管练习很简单,但经过了很多次失败,我还是为此编写了代码。我想知道是否有什么方法可以改善我的代码,如果有,请指出,我只是想了解如何更好地思考。
def next_bigger(num):
# First I checked it returns -1 if numbers already have descending digits and there's no bigger number
if int("".join(sorted(str(num), reverse=True))) == num:
return -1
# Then I converted the number num into a list of strings
num_list= list(str(num))
# Iterated through the num list. starting from the last number and going backwards
for i in range(len(num_list) -1, 0, -1):
# If one digit is bigger than it's predecessor:
if num_list[i] > num_list[i-1]:
A=num_list[:i] # Slices num_list into 2 lists, A
B=num_list[i:] # And B
break
# I think there's a better way to do this next part, but nothing else came into my mind
# So I made a clone of the second list and sorted it ascendantly
# for the smallest number to be in the first place([0])
B_list_for_min_num=sorted(list(B))
# And deleted every minimum number (from the copied B list) that
#was smaller than the last digit in list A through a While loop
while B_list_for_min_num[0] <= A[-1]:
del B_list_for_min_num[0]
# Then swapped the last digit from list A and the minimum digit from the copied B list, but with the digit from the original B list
B[B.index(min(B_list_for_min_num))], A[-1] = A[-1], B[B.index(min(B_list_for_min_num))]
# Then sorted the changed B list ascendently to make sure it will result exactly the next bigger number
B = sorted(B)
# Then joined the lists together
finish = A + B
# And turned them into an integer
result = int(''.join(map(str, finish)))
# Aaaand returned the result
return result
这里!
感谢Tom Ron进行此编辑:由于设置为,排序的完整性丢失了set
。该代码有效,因为列表转换是在排序之前而不是之后完成的!
def main():
someInt = 124
num = str(someInt)
listOfNums = set([int(''.join(nums)) for nums in itertools.permutations(num, len(num))])
listOfNums = sorted(list(listOfNums))
try:
print(listOfNums[listOfNums.index(someInt)+1])
except Exception:
print(-1)
main()
someInt = 111
output = -1
someInt: 12451251125
Output: 12451251152
Itertools为您完成大部分工作。您创建排列,这是数字的每个组合的列表。然后,确保它们是整数,然后排序!由于已排序,因此列表中原始字母之后的数字必然是第二高的数字。如果原始数字后没有数字,请返回-1!我们将列表转换为集合,然后再次返回,因为我们要消除重复项。
如果答案太明显,我们也可以过早退出。转换为字符串后,我们可以添加:
if num == num[0] * len(num):
print(-1)
(尽管您希望在CodeWars中return
代替打印)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句