gpt4 book ai didi

Python 负数的数字比较

转载 作者:行者123 更新时间:2023-12-01 02:35:27 24 4
gpt4 key购买 nike

对于以逗号分隔的数字列表,找到最大的个位数并打印它。如果输入不包含任何单位数字,则打印“未找到单位数字”。如果输入无效,则打印“无效输入”。

chars=input()
a=([int(x.strip()) for x in chars.split(',')])
b=len(a)
print(a)
max=0
for i in range(b-1):
for j in range(i,b):
if a[i]<10 and a[j]<10:

if a[i]>a[j]:
#print(a[i])
max=a[i]
else:
max=a[j]

if (max!=0):
print(max)
else:
print('No single digit numbers found')

如果我给出上面的代码,程序对于正数工作正常,但如果我使用负数,我会得到错误的输出

OUTPUT positive number works fine
1,2,3
[1, 2, 3]
3

输出负数(错误输出)

  -9,+3,0,20,-10,-11,11
[-9, 3, 0, 20, -10, -11, 11]
-11

最佳答案

主要思想是专注于 -10 < i < 10 范围内的数字。
我提出了一个不同的解决方案,比你的更简单:

$ cat /tmp/tmp.py
from __future__ import print_function
import random

def max_single_digit(N):
cur_max = -10
for i in N:
if (i > cur_max) and (-10 < i < 10):
cur_max = i
if cur_max > -10:
return cur_max
else:
return "No single digit numbers found"


_range = 20

negatives = tuple([random.randint(-100,0) for x in range(_range)])
positives = tuple([random.randint(0,100) for x in range(_range)])
numbers = tuple([random.randint(-100,100) for x in range(_range)])

for nums in (negatives, positives, numbers):
print("For", nums, "the result is:", max_single_digit(nums),"\n")

这给出:

$ python /tmp/tmp.py
For (0, -31, -87, -80, -47, -21, -21, -14, -37, -43, -71, -61, -47, -4, -36, -72, -78, -83, -14, -70) the result is: 0

For (17, 83, 80, 50, 35, 43, 9, 75, 23, 38, 45, 55, 46, 99, 80, 93, 36, 97, 88, 30) the result is: 9

For (-1, 30, -20, -68, 13, -66, -71, 92, 77, 85, -100, 8, 32, 92, -6, 97, 40, 21, 13, -48) the result is: 8


$ python /tmp/tmp.py
For (-94, -94, -28, -37, -50, -5, -29, -51, -6, -24, -18, -46, -32, -20, -89, -49, -55, -39, -50, -30) the result is: -5

For (91, 4, 16, 68, 6, 100, 61, 92, 81, 65, 63, 87, 67, 67, 97, 89, 98, 53, 40, 89) the result is: 6

For (11, 49, 63, -17, 71, 50, 28, 5, 31, -100, -35, -5, -8, 77, -87, 77, 3, 8, -39, -97) the result is: 8

$ python /tmp/tmp.py
For (-55, -48, -52, -75, -1, -89, -53, -66, -48, -17, -9, -96, -16, -40, -52, 0, -90, -97, -40, -85) the result is: 0

For (52, 19, 82, 45, 54, 47, 94, 54, 46, 8, 66, 22, 100, 25, 0, 81, 79, 39, 5, 20) the result is: 8

For (-43, -32, 92, -59, -91, 63, -95, 100, -85, -21, 35, -88, -38, 43, -25, 85, 76, 67, -82, 87) the result is: No single digit numbers found

关于Python 负数的数字比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com