0

I want to use int in my array element. Now my code is

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)

In my code, I use chr method in the place of chr(64 + discs - disc). But this time, I want to use int like 1,2,3・・・・. "A" corresponds to 1, "B" corresponds to 2, "C" corresponds to 3・・・・. I wrote this place like int(64 + discs - disc),but error happen. I thought for statement can be used, but it is redundant. So, how can I do this? How can I convert str into int?

Daniel
  • 2,744
  • 1
  • 31
  • 41
mikimiki
  • 177
  • 1
  • 1
  • 12
  • First if you have an error you should also post the traceback. Second, Python is a strongly typed language. You are trying to append an int to a string and that gives you (I assume) `TypeError` exception. – bergerg Jul 29 '17 at 07:33

1 Answers1

0

Hello mikimiki,

Try this below code,

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)

I hope my answer is helpful.
If any query so comment please.

Mayur Vora
  • 922
  • 2
  • 14
  • 25