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?

1
  • 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. Commented Jul 29, 2017 at 7:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.