You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求更优雅的数字重排求差方案以验证Kaprekar常数

优化Kaprekar常数验证代码的优雅方案

我正在寻找一种更优雅的解决方案,用于将数字的各位按降序和升序排列,并计算两个重排后数字的差值。当前我的代码采用暴力法,想替换成更简洁的实现。以下是我用于验证Kaprekar常数(6174)的现有代码:

import copy, random
n = input("type a four digit number. At least one digit must be different from rest")
while int(n) != 6174:
    nlist = []
    for i in n:
        nlist.append(int(i))
    nlist.sort()
    nasc = copy.copy(nlist)
    nlist.sort(reverse = True)
    ndsc = copy.copy(nlist)
    ndscInt = (ndsc[0]*1000 + ndsc[1]*100 + ndsc[2]*10 + ndsc[3]) 
    nascInt = (nasc[0]*1000 + nasc[1]*100 + nasc[2]*10 + nasc[3]) 
    ndiff = ndscInt - nascInt
    print(ndscInt, '-',nascInt, '=',ndiff )
    if ndiff == 6174:
        print('Kaprekar number reached')
        break
    n = str(ndiff)
    input("press Enter to continue")

优化后的优雅实现

通过利用Python字符串和排序的特性,可以大幅简化代码逻辑,去掉冗余操作:

# 验证Kaprekar常数6174的优雅实现
def kaprekar_step(num_str):
    # 确保数字为四位格式,自动补前导零
    num_str = num_str.zfill(4)
    # 升序排列后转整数
    asc_num = int(''.join(sorted(num_str)))
    # 降序排列后转整数
    desc_num = int(''.join(sorted(num_str, reverse=True)))
    return desc_num - asc_num

# 主执行逻辑
n = input("请输入一个四位数,且至少有一位数字与其他不同:")
while int(n) != 6174:
    diff = kaprekar_step(n)
    # 生成用于输出的降序和升序数字
    normalized_num = n.zfill(4)
    desc_display = int(''.join(sorted(normalized_num, reverse=True)))
    asc_display = int(''.join(sorted(normalized_num)))
    print(f"{desc_display} - {asc_display} = {diff}")
    if diff == 6174:
        print("已到达Kaprekar常数6174")
        break
    n = str(diff)
    input("按回车键继续下一步")

优化说明

  • 简化排序与转换:直接对数字字符串进行排序,拼接后转整数,替代手动遍历转列表、计算位权的暴力写法
  • 移除冗余操作:去掉不必要的copy调用,sorted()会返回新的排序后列表,不会修改原数据
  • 格式统一处理:用zfill(4)确保所有数字始终为四位格式,避免差值为三位数时的格式问题
  • 代码模块化:将核心的Kaprekar步骤提取为独立函数,提升代码可读性和复用性
  • 输出优化:使用f-string简化输出格式,代码更简洁直观

内容的提问来源于stack exchange,提问作者ArNY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:55:17