0

ユーザーが入力した値を取り込んだ三角形を作成しようとしています。値から、これらの入力の最大ルートを見つけたいと思います。私は最初にこれで最大ルートを見つけるために質問をしました:与えられた入力で最大ルートを見つける

コード:

def triangle(rows):
    for rownum in range (rows):
        PrintingList = list()
        print ("Row no. %i" % rownum)
        for iteration in range (rownum):
            newValue = input("Please enter the %d number:" %iteration)
            PrintingList.append(int(newValue))
            print()
def routes(rows,current_row=0,start=0):
    for i,num in enumerate(rows[current_row]):
        #gets the index and number of each number in the row
        if abs(i-start) > 1:   # Checks if it is within 1 number radius, if not it skips this one. Use if not (0 <= (i-start) < 2) to check in pyramid
            continue
        if current_row == len(rows) - 1: # We are iterating through the last row so simply yield the number as it has no children
            yield [num]
        else:
            for child in routes(rows,current_row+1,i): #This is not the last row so get all children of this number and yield them
                yield [num] + child


numOfTries = input("Please enter the number of tries:")
Tries = int(numOfTries)
for count in range(Tries):
    numstr= input("Please enter the height:")
    rows = int(numstr)
    triangle(rows)
    routes(triangle)
    max(routes(triangle),key=sum)

三角形のすべての値を入力した後に発生するエラー:

Traceback (most recent call last):
  File "C:/Users/HP/Desktop/sa1.py", line 25, in <module>
    max(routes(triangle),key=sum)
  File "C:/Users/HP/Desktop/sa1.py", line 10, in routes
    for i,num in enumerate(rows[current_row]): #gets the index and number of each number in the row
TypeError: 'function' object is not subscriptable

コードのどこにエラーがありますか?助けが必要です..ありがとう...

4

3 に答える 3

2

使用しているもの:

routes(triangle)

このtriangle名前は、関数の最初の引数として渡される関数を指しrowsますroutes。関数本体では、実際に関数であるrows[current_row]ようにエラーを生成します。rows

私はあなたが何をしようとしているのか本当にわかりません。PrintingListおそらく、この結果から戻ってtrianglesこの結果を関数に渡したいroutesですか?

于 2012-04-13T13:21:53.567 に答える
1

関数内の変数として関数PrintingList内で作成されたの値を取得しようとしている可能性があります。trianglerowsroutes

プログラムをそのように機能させるには、三角形関数にreturnステートメントを追加する必要があります(つまりreturn PrintingList、最後のステートメントとしてaを追加します)。関数を呼び出すときにこの値を格納し、格納された値を関数に渡しますroutes。つまり、プログラムの終了は次のようになります。

result = triangle(rows)
routes(result)
max(routes(triangle),key=sum)

これでこの問題は修正されます。上記のコードには他の問題がある可能性があります。

于 2012-04-13T13:26:33.000 に答える
-3

トレースバックで述べたように、25行目と10行目です。関数は添え字化できないと言っていますが、これは本当です。関数をサブスクライブすることはできません。ただし、サブスクライブできます。

String:  "x"[2] == "foo"
Tuple:   (2,5,2,7)[3] == 7
List:    [1,2,3,"foo"][3] == "foo"
Dict:    {"a":1, "b":5, "c":5}["a"] == 1
于 2012-04-13T13:23:38.950 に答える