簡體   English   中英

輸入多個以空格分隔的條目

[英]input multiple entries separated by space

我是 python 的新手,我有一個任務要編寫一個程序,提示用戶輸入一組以空格分隔的正整數 0、1、...、-1。 然后程序只讀取和存儲正整數並忽略任何無效條目

然后,您的程序應使用以下規則計算將每個數字減為 0 的步驟: • 如果數字是偶數,則將其除以 2 • 如果數字是奇數,則將其減 1

例如,要減少數字 10:

  • 10 是偶數,10 除以 2 就變成 5
  • 5 為奇數,5 減 1,變為 4 - 4 為偶數,4 除以 2,變為 2
  • 2 是偶數,用 2 除以 2 就變成 1
  • 1 為奇數,1 減 1,變為 0,所以需要 5 步將 10 減為 0。

到目前為止,在代碼中,我可以輸入一個條目,但我需要多個以空格分隔的條目。

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

output:

[(3, 3), (45, 9), (59, 10), (16, 5), (32, 6), (89, 10)]

請你幫助我好嗎?

我認為你的循環的開始是一個問題,正如for e in stringInput:實際上是遍歷你輸入字符串中的每個字符。 您可能想要的是 go 通過每個空格分隔的條目。 有一個很好的 function , split()

split()是一個字符串 function ,它將一個字符串“拆分”為一個列表,其中列表中的每個項目由您提供的參數分隔。 例如,

# 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)

您可能需要進行更多檢查以確保該數字為正數,但這應該可以幫助您入門。

您所需要的只是使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM