Home > Back-end >  Python: Simplifying selection statements to using a loop
Python: Simplifying selection statements to using a loop

Time:12-17

I have the following code, and for teaching purposes want to go from here to simplifying it into using iteration. I want students to be able to see any repetition (e.g. the patterns) and use either a for or while loop to achieve this instead.

What would the best way to approach this be?

https://trinket.io/python/5e56cf6a5c

def matrix():
  print("---The Matrix---")
  #create a 1d array of 7 stars
  matrix1=[
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"]
  ]
  #user enters a number
  number=int(input("Enter number:"))
  #you are always finding the remainder on each row to place the X
  remainder=number%7
  
  #an 'X' is placed in the position of the number
  #remainder-1 because we start at index 0
  
  if number<1:
    matrix1[0][0]="X"
  elif number<=7:
    matrix1[0][remainder-1]="X"
  elif number>7 and number<15:
    matrix1[1][remainder-1]="X"
  elif number>14 and number<22:
    matrix1[2][remainder-1]="X"
  elif number>21 and number<29:
    matrix1[3][remainder-1]="X"
  elif number>28 and number<36:
    matrix1[4][remainder-1]="X"
  elif number>35 and number<43:
    matrix1[5][remainder-1]="X"
  elif number>42 and number<50:
    matrix1[6][remainder-1]="X"



  #the updated matrix is printed.
  print(matrix1)
matrix()

Without using iteraton at all, this was suggested:

def matrix():
    print("---The Matrix---")
    # create a 2d array of 7x7 stars
    matrix1 = [["*" for _ in range(7)] for _ in range(7)]

    number = int(input("Enter number: "))
    matrix1[number // 7][number % 7] = "X"

    # print the matrix
    print('\n'.join(''.join(row) for row in matrix1))


matrix()

I can't understand the following:

For say '14'. matrix1[number // 7][number % 7] = "X" number//7 = 2 and number%7 = 0. This should put the X in row 2 and position 0?

CodePudding user response:

This doesn't use any loops, but perhaps this simplification is along the lines of what you want.

def matrix():
  print("---The Matrix---")
  #create a 1d array of 7 stars
  matrix1=[
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"],
  ["*","*","*","*","*","*","*"]
  ]
  #user enters a number
  number=int(input("Enter number:"))
  #you are always finding the remainder on each row to place the X
  q,r = divmod(number-1,7)
  
  matrix1[q][r] = 'X'



  #the updated matrix is printed.
  print(matrix1)
matrix()

Also, here's a prettier way to print that matrix.

for row in matrix1:
    print(*row)

In Python 2:

for row in matrix1:
    print(' '.join(row))

Here's a trinket link for the Python 3 version.

Sample output:

---The Matrix---
Enter number:8
* * * * * * *
X * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *

CodePudding user response:

You don't need to do remainder-1, as remainder=number%7 always returns a value between 0 and 6.

0%7 = 0
1%7 = 1
...
6%7 = 6
7%7 = 0

Which solves your underlying problem.

CodePudding user response:

You can use loops like this:

def matrix():
    print("---The Matrix---")
    #create a 1d array of 7 stars
    matrix1=[
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"],
    ["*","*","*","*","*","*","*"]
    ]
    #user enters a number
    number= int(float(input("Enter number:")))
    
    #you are always finding the remainder on each row to place the X
    
    #an 'X' is placed in the position of the number
    #remainder-1 because we start at index 0
    
    for i in range(1,len(matrix1) 1):
        for j in range(1,len(matrix1) 1):
            if i * j == number:
                matrix1[i-1][j-1] = "X"



    #the updated matrix is printed.
    print(matrix1)
matrix()

CodePudding user response:

It puts the 14 into Row 2 Column 0 as you said. Your implementation have bugs. For example, 0 and 1 has same output. So, normally if you using zero indexing the suggested code is perfect.

When we give 14 for your implementation, it assumes it is in Row 1 because of the el-if statements. matrix1[1][remainder-1]becomes matrix1[1][-1] then it puts X to last element of row. The -1 functionality of python shows like your implementation is correct. But it is not.

The suggested implementation is correct if you using zero indexing. If you say it should start 1, so your loopy implementation is also wrong.

CodePudding user response:

If the use of a 2D array isn't a key part, then a better option is just to do simple replacements on a single list, and use other functions to style the output. Here we use textwrap to split the text into lines 7 chars long:

import textwrap

def matrix():
  print("---The Matrix---")
  # Create a list of '*', 49 items long
  matrix1= ["*"] * 49
  #user enters a number
  number=int(input("Enter number:"))

  # Update the list element in that position
  matrix1[number] = "X"

  #the updated matrix is printed.
  print('\n'.join(textwrap.wrap(''.join(matrix1), 7)))

matrix()

Admittedly this also means that no loops or iterations are involved, which might defeat the point of the exercise...

  • Related