我对python很陌生,我有一个任务要编写一个程序,它提示用户输入一组空格分隔的正整数0、1、.、−1。
那么,您的程序应该使用以下规则来计数将每个数减少到0的步骤:·如果数字是偶数,除以2。如果数字是奇数,则将其减为1。
例如,为了减少数字10:
到目前为止,在代码中,我可以输入一个条目,但我需要用空格分隔的多个条目。
stringInput = input("Enter integers: ")
try:
for e in stringInput:
listOfintegers = []
stepsCount = 0
integerInput = int(stringInput)
integerToTest = integerInput
while integerToTest > 0:
if integerToTest % 2 == 0:
integerToTest /= 2
else:
integerToTest -= 1
stepsCount += 1
listOfintegers.append((integerInput, stepsCount))
except:
print("a string was entered")
exit(1)
print(listOfintegers)应该是这样:请输入一组空格分隔的正整数:3 45 st 59 16 32 89
产出:
(3,3),(45,9),(59,10),(16,5),(32,6),(89,10)
你能帮帮我吗?
发布于 2021-03-14 21:47:13
您只需要使用split()命令(例如,split(" ") )将输入拆分为空格。
我修改了你的代码
#stringInput = "3 45 st 59 16 32 89"
stringInput = input("Enter integers: ")
stringInput=stringInput.split(" ")
listOfintegers = []
for e in stringInput:
stepsCount = 0
if(e.isdigit()):
integerInput = int(e)
else:
continue
integerToTest = integerInput
while integerToTest > 0:
if integerToTest % 2 == 0:
integerToTest /= 2
else:
integerToTest -= 1
stepsCount += 1
listOfintegers.append((integerInput, stepsCount))
print(listOfintegers)发布于 2021-03-14 21:34:49
我认为循环的开始是一个问题,因为for e in stringInput:实际上正在遍历输入字符串中的每个字符。你可能想要的是,检查每一个空格分隔的条目。有一个很好的功能,split()。
split()是一个字符串函数,它将一个字符串“拆分”成一个列表,其中列表中的每个项都由您提供的参数分隔。例如,
# x1 is ["1", "2", "3", "4", "5"]
x1 = "1,2,3,4,5".split(",")
# x2 is ["a", "23a", "4a5", "7"]
x2 = "a-23a-4a5-7".split("-")如果您想按空格分隔输入字符串,您可能会编写类似的内容
stringInput = input("Enter integers: ")
# Splits up input string by spaces
inputList = stringInput.split(" ")
for e in inputList:
listOfintegers = []
stepsCount = 0
integerToTest = 0
try:
integerInput = int(stringInput)
integerToTest = integerInput
except:
print("Element is not a number")
continue
while integerToTest > 0:
if integerToTest % 2 == 0:
integerToTest /= 2
else:
integerToTest -= 1
stepsCount += 1
listOfintegers.append((integerInput, stepsCount))
print(listOfintegers)您可能需要做一些更多的检查,以确保数字是正数,但这应该会让您开始。
https://stackoverflow.com/questions/66629681
复制相似问题