2017-03-29 28 views
0

本質上,如果我輸入n爲4,k輸入4,則應該在文件中返回4行4位二進制字符串。如何在文件中返回(k)二進制字符串的位數?

取而代之,它返回四行二進制,但是按照位的升序。 (所以,第一行有一個位,第二行有兩個,第三行有三個,等等。)

這裏是我的代碼:

import random 
def makeStrings(): 
    fileName = str(input("file:")) 
    outputFile = open(fileName, "w") 
    userInput = str(input("k:")) 
    anotherinput = str(input("n:")) 
    counter = 0 
    while (counter < int(anotherinput)): 
     stringy = "" 
     for i in range(int(userInput)): 
      RandoNumber=int(random.random()*2) 
      stringy=stringy+str(RandoNumber) 
      outputFile.write(str(stringy) + "\n") 
      counter = counter +1 
    outputFile.close() 

感謝您的幫助!

回答

0

在此代碼:

stringy = "" 
    for i in range(int(userInput)): 
     RandoNumber=int(random.random()*2) 
     stringy=stringy+str(RandoNumber) 
     outputFile.write(str(stringy) + "\n") 
     counter = counter +1 

你循環多達userInput,但打印每次。 (在這種情況下,每次都需要outputFile.write)。

您需要等到您的for循環完成後再將值寫入outputFile。這樣,你的stringy變量將具有正確的長度。

0

你錯誤地處理了你的循環索引。你的內部循環寫入字符串的每一個加法。你的外部循環與內部循環並行運行; 計數器每次通過內部循環遞增。試試這個。我簡化了幾行測試。

userInput = 4 
anotherinput = 4 
for counter in range(int(anotherinput)): 
    stringy = "" 
    for i in range(int(userInput)): 
     RandoNumber=int(random.random()*2) 
     stringy=stringy+str(RandoNumber) 
    print(str(stringy) + "\n") 
# outputFile.close() 
+0

非常感謝!我知道這是一個簡單的修復,但我無法弄清楚。 – Sinopia

相關問題