-1

I am fairly new to python, and was wondering whether anybody could help me with the following problem:

I am trying to map a Christmas tree after receiving an input from the user about the tree's height and base branch length. Here is the code I currently have:

tree_map_5 = ['B']
tree_map_4 = ['B']
tree_map_3 = ['B']
tree_map_2 = ['B']
tree_map_1 = ['B']
# (B means Bark (For the trunk))

Layers = int(input("\nHow many layers will your christmas tree have? (Maximum 5)\n\nInput: "))
Base_Branch_Length = int(input("\nHow long will the base branches of your tree be? (in centimetres)\n\nInput: "))

for i in range (Layers):
  for j in range (Base_Branch_Length+1):
    tree_map_'i'.append(0)
    tree_map_'i'.insert(0, 0)

If the user were to say 5 layers and 5 base branch length, the lists would show this:

tree_map_5 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_4 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_3 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_2 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_1 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]

I was wondering whether I would be able to write a for loop that adds noughts into a changeable number of lists (like I tried to do) depending on the number of layers they input.

Sorry if my question wasn't clear.

Thanks

0x5453
  • 12,753
  • 1
  • 32
  • 61
KieranLock
  • 48
  • 1
  • 6
  • 2
    I think you don't know that you can have multidimensional lists, aka. lists in lists. Also please edit you question and surround your code with triple backticks (\`\`\`) so it can be more readable. – Maxxik CZ Dec 12 '19 at 16:03
  • 1
    Have the `tree_map` variables as one list instead, then just append to the list to add layers. – Carcigenicate Dec 12 '19 at 16:04
  • 1
    Creating variables iteratively is considered bad practice (might easily lead to problems), so it's better to use dictionaries or lists to store your variables. – Juan C Dec 12 '19 at 16:07
  • Thanks for the answers - sorry for the badly formatted question (I'm new to Stack Overflow). – KieranLock Jan 02 '20 at 12:54

1 Answers1

0

Have a look at this article to get a grasp at dynamic variable names. Like the article already warns you, you shouldn't want to have dynamic variable bames. If you insist on it, in your for loop you should replace the .append(0) and .insert(0, 0) respectively by the following:

globals()['tree_map_{}'.format(i)].append(0)
globals()['tree_map_{}'.format(i)].insert(0, 0)

But a better solution would be to use one big list:

Layers = int(input("\nHow many layers will your christmas tree have? (Maximum 5)\n\nInput: "))
Base_Branch_Length = int(input("\nHow long will the base branches of your tree be? (in centimetres)\n\nInput: "))

tree_map = [['B'] for i in range(Layers)]

for i in range (Layers):
  for j in range (Base_Branch_Length+1):
    tree_map[i].append(0)
    tree_map[i].insert(0, 0)

print(tree_map[0])
Anteino
  • 1,044
  • 7
  • 28