我想在数组elemen中使用int

2024-03-29 05:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在数组元素中使用int。 现在我的密码是

def hanoi_pos(discs, index):
    power = 2**discs
    stacks = ['', '', '']
    for disc in range(discs):
        stack = (index+power//2)//power % 3

        if disc % 2 == 0: stack = (3 - stack) % 3
        power = power // 2
        stacks[stack] += chr(64 + discs - disc)

    return stacks

def get_game_state(stacks):
    return '\n'.join([' '.join(st) if st else '-' for st in stacks])


x = hanoi_pos(4, 6)
y = get_game_state(x)
print(y)

在我的代码中,我使用chr方法代替chr(64 + discs - disc)。 但这次,我想用int,比如1,2,3・・・・・・・。 “A”对应1,“B”对应2,“C”对应3・・・・・・。 我写这个地方就像int(64 + discs - disc),但是错误发生了。我以为for语句可以用,但它是多余的。那么,我该怎么做呢? 如何将str转换为int?你知道吗


Tags: inposforindexifstackdefint
1条回答
网友
1楼 · 发布于 2024-03-29 05:15:17

你好mikimiki,

试试下面的代码

def hanoi_pos(discs, index):
    power = 2**discs

    stacks = ['', '', '']
    for disc in range(discs):
        stack = (index+power//2)//power % 3

        if disc % 2 == 0: stack = (3 - stack) % 3
        power = power // 2
        print " ",discs, disc," "
        stacks[stack] += chr(48 + discs - disc)

    return stacks

def get_game_state(stacks):
    return '\n'.join([' '.join(st) if st else '-' for st in stacks])


x = hanoi_pos(4, 6)
y = get_game_state(x)
print(y)

希望我的回答能有所帮助。
如果有任何疑问,请评论。你知道吗

相关问题 更多 >