有关以逗号分隔的数字列表,请找到最大的单个数字并打印出来。如果输入不包含任何单个数字,则打印“未找到单个数字”。如果输入无效,请打印“无效输入”。
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
答案 0 :(得分:1)
答案 1 :(得分:1)
主要思想是专注于-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
答案 2 :(得分:0)
怎么样:
import re
input = "1,2,3,44,5,6,-7,-10"
nums = [int(el) for el in input.split(",") if re.match("^-?\d$", el) is not None]
if len(nums) == 0:
print("No single digit numbers found")
print(max(nums))