Python-具有相同数字的下一个更大数字-Codewars Kata-如何改进它

克里斯蒂·塔努尔(Christi Tanul)

所以这个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 
久保MD

这里!
感谢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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Vasya - 文员 ----- codewars kata

如何使用Python查找具有相同ID的下一个日期?

递归计数器在 codewars kata 中不起作用

如何使用WebDriverWait()访问Selenium Python中具有相同类名称的下一个元素的值

FInd下一个相同数字的最小数字Python

CSV:如何在列表(python)中找到下一个更大的值?

MySQL:如何选择具有下一个更大ID的行?

如何找出文件中一个数字和下一个相同数字之间的行数?

Clojure中的罗马数字kata

Python返回下一个单词/数字

如何递增到下一个数字

Python Multiprocessing:如何从具有列表下一个元素的一组进程再次运行一个进程?

给定一个数字,找到下一个更大的数字,该数字与原始数字具有完全相同的数字集

如何查找下一个较小的整数(具有相同的1s)

如果Python中没有时间,如何跳到下一个输入

优化(CodeWars整数:休闲一)

如何仅将列表中的数字与下一个数字(邻居)进行比较?

优化Python函数以在Codewars上提交

不同数字年份 -Codewars Challenge-

Codewars问题“快乐数字”我如何才能对我的代码进行一些更改以使其起作用?

执行超时如何优化这个 kata 以运行得更快?

当添加具有相同启发式值的节点时,A* 搜索如何选择下一个节点?

python风险游戏,我无法让它只比较最后一个的所有数字

如何在字符串中找到一个字符并替换它和python中的以下一个

给定一个数字,找到下一个更大的数字,该数字具有唯一数字,但0和2

如何从Python中的上一个值中减去下一个值?

Codewars挑战-JavaScript-查找数组中的第一个非连续数字

如何删除具有相同整体的数字并保留列表中的第一个出现的数字?

如何知道聚合组具有上一个/下一个值?