【问题标题】:Comparing digits in an integer in Python在Python中比较整数中的数字
【发布时间】:2018-04-25 01:07:25
【问题描述】:

这里真的需要一些帮助。超级早学 Python。

目标是取一个数字,看看数字是否按升序排列。 到目前为止我所拥有的是:

a = int(input("Enter a 4-digit number: "))

b = [int(i) for i in str(a)]

if b[0] > b[1]:
    print "Not ascending"
elif b[1] > b[2]:
    print "Not ascending"
elif b[2] > b[3]:
    print "Not ascending"
else:
    print "Ascending!"

我的问题是,我怎样才能使输入的位数没有限制?因此,如果有人输入一个 7 位数字,它会执行相同的过程直到最后一位。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

第一步对所有输入进行排序

b = [int(i) for i in str(a)]

第二步,比较origin input和sorted-list,list的所有元素都可以用一个字符串(digit-string)concat,所以只能比较一次。

c = sorted(b)

''.join([str(i) for i in b]) > ''.join([str(i) for i in c]):

   print "Not ascending"
else:
   print "Ascending!"

或者使用标准库,按照你的方式检查每个元素和下一个元素:

every_check = [b[i] <= b[i+1] for i in xrange(len(b)-1)]

[真、真、假、假]

并使用all()检查是否所有True

if all(every_check):
    print "Ascending!"
else:
    print "Not ascending"

【讨论】:

    【解决方案2】:

    你需要一个循环。

    例如:

    a = int(input("Enter a 4-digit number: "))
    
    b = [int(i) for i in str(a)]
    
    
    def isAscending(b):
      #loop for as many digits in the array
      for x in range(0, len(b) - 1):
        # if the next number is less than the previous return false
        if b[x] > b[x+1]:
          return False
      #  did not fail so return true
      return True
    
    if isAscending(b):
      print ("the number is in ascending order")
    else:
      print ("the number is not in ascending order")
    

    【讨论】:

      【解决方案3】:

      如果您使用的数字如此之少,只需按升序创建一个包含元素的新列表。幸运的是,Python 有一个函数可以做到这一点,内置函数sorted

      def is_ascending(lst):
          return sorted(lst) == lst
      

      【讨论】:

        猜你喜欢
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-14
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        相关资源
        最近更新 更多