我目前正在學習python的過程中,所以我試圖重寫我在java中的項目到python。我不確定我出錯的地方。代碼試圖將n個節點分配給k個通道並打印出結果/配置。我接受在評論中被關閉,因爲我真的無法弄清楚我的代碼出了什麼問題,可能是因爲我只知道Java。這可能是因爲我使用終端而不是標準的Python IDE嗎? 此外,這是我在StackOverflow平臺上的第一個問題,所以如果有任何方法可以改變我的方法來提問我想知道和學習的問題。 set_of_channels是指用於保持生成的設置 available_combos保持每個所生成的集合的軌跡基於輸入將java代碼翻譯成python,IDE建議?
鑑於3個節點和2個信道,這是在輸出
的Python
1 sets with occupancies: []
1 sets with occupancies: ['3']
Total number of assignments: 2
爪哇
3 Nodes, 2 Channels:
1 set(s) with occupancies: [0, 3]
3 set(s) with occupancies: [1, 2]
3 set(s) with occupancies: [2, 1]
1 set(s) with occupancies: [3, 0]
Total number of assignments: 8
不確定是否要添加新代碼,因爲我的帖子可能太長,不知道這是不是堆棧溢出禮儀
def start():
availableCombos = [[]]
numberOfNodes = raw_input("How many nodes?")
numberOfChannels = raw_input("How many channels?")
index = 0
setOfChannels = [numberOfChannels]
while True:
generate(numberOfNodes, setOfChannels,
index, numberOfNodes, availableCombos)
totalAssignments(availableCombos, numberOfNodes)
# The base case is the last channel
# Set the channel to have the value of nodes
# currentChannel should be set to 0
# as this is the base that lists in java work with
# it is incremented with every call so as to fill up next channel
# remaining nodes helps to keep track of nodes
# to put into channels based on nodes in previous channels
# As arrays are filled they are copied into the list of available combinations
def generate(nodes, combo, currentChannel, remainingNodes, availableCombos):
sum = 0
if(currentChannel < len(combo) - 1):
if(currentChannel != 0):
remainingNodes -= combo[currentChannel - 1]
for i in range(0, remainingNodes):
combo[currentChannel] = i
sum + 1
generate(nodes - i, combo, currentChannel + 1, remainingNodes)
print(sum)
# base case
if(currentChannel == len(combo) - 1):
combo[currentChannel] = nodes
channelSet = range(len(combo))
for i in range(0, len(combo)):
channelSet[i] = combo[i]
availableCombos.append(channelSet)
# computes the total number of combos
# and displays sets of channels that were generated
def totalAssignments(combos, nodes):
totalCombos = 0
for combo in combos:
totalCombos += countCombos(combo, nodes, 0)
'{}{}{}'.format(countCombos(combo, nodes, 0),
" sets with occupancies: ", combo)
'{}{}'.format("Total number of assignments: ", totalCombos)
def countCombos(combo, nodes, currentChannel):
if(currentChannel < len(combo)):
binomials = binomial(nodes, combo[currentChannel])
recursed = countCombos(combo, int(nodes) -
int(combo[currentChannel]), currentChannel + 1)
result = binomials * recursed
return result
return 1
def binomial(n, k):
if(k == n or k == 0):
return 1
result = binomial(n - 1, k - 1) + binomial(n - 1, k)
return result
def main():
start()
main()
縮進是絕對錯誤的。我希望你沒有使用這個代碼。此外,你應該給你一個錯誤的賬戶。 – Pbd
將檢討我的語法,謝謝你一堆 – cmoioverflow