LoginSignup
kiri___
@kiri___

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

JavaScriptからPythonへの書き換えをお願いしたい。

解決したいこと

リンクに貼らせていただきましたのは、無料で閲覧可能な基本情報技術者試験のサイトです。
ここには、問題と解説が掲載されているのですが、問題文中に出てくるmakeHeapをJavaScriptで実装したコードが末尾に記載されていて、後学の為、意味を読み解き、プログラムを実行したいのですが、現在pythonのみ文法を理解できる状況です。pythonでサイト内のプログラムを実行したいので、JavaScriptからpythonへの変換をお願いしたいです。

発生している問題・エラー

エラーメッセージはありません。

該当するソースコード

//基本情報技術者試験 平成30年春期問8 makeHeap
var data = [5,13,36,8,2,2,34,63,32,1,23,9,16,24,54];
var heap = [];
var hnum = data.length;
makeHeap(data, heap, hnum);

document.write('整列後の配列 => ['+heap+']
');
//木構造として整形して出力
var tree = heap[0]+'
';
var j = 1;
while (heap[Math.pow(2, j) -1]) {
tree += heap.slice(Math.pow(2, j) -1, Math.pow(2, j+1) -1).toString()+'
';
j++;
}
document.write('木構造 =>

'+tree+'
');

function makeHeap(data, heap, hnum)
{
var i, k;
for (i=0; i<hnum; i++) {
heap[i] = data[i];
k = i;
while (k > 0) {
if (heap[k] > heap[parent(k)]) {
swap(heap, k, parent(k));
k = parent(k);
} else {
break;
}
}
}
}

function swap(heap, i, j)
{
var tmp;
tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}

function lchild(i)
{
return 2 * i + 1;
}

function rchild(i)
{
return 2 * i + 2;
}

function parent(i)
{
return Math.floor((i - 1) / 2);
}


自分で試したこと
JavaScriptの文法を少し調べてみましたが、想像以上に時間がかかりそうであった為、ここに質問させていただきました。
0

1Answer

ほぼChatGPTの出力です。

def make_heap(data, heap, hnum):
    for i in range(hnum):
        heap[i] = data[i]
        k = i
        while k > 0:
            if heap[k] > heap[parent(k)]:
                swap(heap, k, parent(k))
                k = parent(k)
            else:
                break

def swap(heap, i, j):
    tmp = heap[i]
    heap[i] = heap[j]
    heap[j] = tmp

def lchild(i):
    return 2 * i + 1

def rchild(i):
    return 2 * i + 2

def parent(i):
    return (i - 1) // 2

data = [5, 13, 36, 8, 2, 2, 34, 63, 32, 1, 23, 9, 16, 24, 54]
heap = [0] * len(data)
hnum = len(data)
make_heap(data, heap, hnum)

print('整列後の配列 =>', heap)
# 木構造として整形して出力
tree = str(heap[0]) + '\n'
j = 1
try:
    while heap[(2 ** j) - 1]:
        tree += ', '.join(map(str, heap[(2 ** j) - 1: (2 ** (j + 1)) - 1])) + '\n'
        j += 1
except:
    pass

print('木構造 =>\n', tree)


1

Your answer might help someone💌