Question

In: Computer Science

I am creating a crop watering "simulator" in Python. I have the user input an array...

I am creating a crop watering "simulator" in Python. I have the user input an array and then must compare the placement of water and crops to determine if all the crops in the array are watered. The user will either input a "w" for water or "c" for crop when creating the array. A w cell can water 8 cells around it, including itself. My end result must determine if all the crops will be watered or not. How do I compare the values in the cells to output this? And how do I output the crops not watered, if they are not all watered?

Here is an example, given the following array:

cccw

wccc

cccc

cwcc

How do I ouput that not all the crops are watered, and the crops in positions (2,3) and (3,3) are not watered?

Here is my code so far as well:

print("Input number of rows and columns in the crop field:")

rows = int(input("ROWS>"))

columns = int(input("COLUMNS>"))

array = []

for i in range(columns):

array.append([])

for j in range(rows):

current_input=input(f"Type in the value for row={i}, column={j}: ")

array[i].append(current_input)

for i in array:

print(i)

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code with no comments, for easy copying


def neighbors(array, r, c):
    values = []
    if (r - 1) >= 0:
        values.append((r - 1, c))
    if (r - 1) >= 0 and (c - 1) >= 0:
        values.append((r - 1, c - 1))
    if (r - 1) >= 0 and (c + 1) < len(array[r]):
        values.append((r - 1, c + 1))
    if (r + 1) < len(array):
        values.append((r + 1, c))
    if (r + 1) < len(array) and (c - 1) >= 0:
        values.append((r + 1, c - 1))
    if (r + 1) < len(array) and (c + 1) < len(array[r]):
        values.append((r + 1, c + 1))
    if (c - 1) >= 0:
        values.append((r, c - 1))
    if (c + 1) < len(array[r]):
        values.append((r, c + 1))
    return values


print("Input number of rows and columns in the crop field:")
rows = int(input("ROWS> "))
columns = int(input("COLUMNS> "))

array = []

for i in range(rows):
    array.append([])
    for j in range(columns):
        current_input = input(f"Type in the value for row={i}, column={j}: ")
        array[i].append(current_input)

for i in array:
    print(i)

for i in range(rows):
    for j in range(columns):
        if array[i][j] == 'w':
            array[i][j] = 'x'
            for r,c in neighbors(array,i,j):
                array[r][c]='x'


not_watered=[]
for i in range(rows):
    for j in range(columns):
        if array[i][j]=='c':
            not_watered.append((i,j))


if len(not_watered)==0:
    print("All crops are watered")
else:
    print("Not all crops are watered; unwatered crops are in position(s): ",end='')
    print(*not_watered,sep=', ')
    print()

#same code with comments, for learning

# helper method defined to return the row,column indices of all cells around r,c
# assuming r and c are valid
def neighbors(array, r, c):
    # creating a list
    values = []
    # if r-1 is a valid index, adding tuple (r-1,c) to values
    if (r - 1) >= 0:  # top center
        values.append((r - 1, c))
    # similarly checking addresses of all cells around (r,c), adding to values
    if (r - 1) >= 0 and (c - 1) >= 0:  # top left
        values.append((r - 1, c - 1))
    if (r - 1) >= 0 and (c + 1) < len(array[r]):  # top right
        values.append((r - 1, c + 1))
    if (r + 1) < len(array):  # bottom center
        values.append((r + 1, c))
    if (r + 1) < len(array) and (c - 1) >= 0:  # bottom left
        values.append((r + 1, c - 1))
    if (r + 1) < len(array) and (c + 1) < len(array[r]):  # bottom right
        values.append((r + 1, c + 1))
    if (c - 1) >= 0:  # left
        values.append((r, c - 1))
    if (c + 1) < len(array[r]):  # right
        values.append((r, c + 1))
    # returning values
    return values


print("Input number of rows and columns in the crop field:")
rows = int(input("ROWS> "))
columns = int(input("COLUMNS> "))

array = []

for i in range(rows):
    array.append([])
    for j in range(columns):
        current_input = input(f"Type in the value for row={i}, column={j}: ")
        array[i].append(current_input)

for i in array:
    print(i)

# we read and print the 2d list, now we can mark all watered crops with 'x'

# looping through each row and column
for i in range(rows):
    for j in range(columns):
        # checking if value at i,j is 'w'
        if array[i][j] == 'w':
            # marking current position with value 'x'
            array[i][j] = 'x'
            # looping through each neighbor cell of i,j and marking them
            for r, c in neighbors(array, i, j):
                array[r][c] = 'x'

# now creating a list
not_watered = []
# looping and adding row,col indices of all unwatered crops as tuples into not_watered list
for i in range(rows):
    for j in range(columns):
        if array[i][j] == 'c':  # value is still 'c', means unwatered crop
            not_watered.append((i, j))

# if not_watered list is empty, then all crops are watered
if len(not_watered) == 0:
    print("All crops are watered")
else:
    # else, not all crops are watered
    print("Not all crops are watered; unwatered crops are in position(s): ", end='')
    print(*not_watered, sep=', ')  # printing tuples in not_watered separated by ', '
    print()

#output

Input number of rows and columns in the crop field:
ROWS> 4
COLUMNS> 4
Type in the value for row=0, column=0: c
Type in the value for row=0, column=1: c
Type in the value for row=0, column=2: c
Type in the value for row=0, column=3: w
Type in the value for row=1, column=0: w
Type in the value for row=1, column=1: c
Type in the value for row=1, column=2: c
Type in the value for row=1, column=3: c
Type in the value for row=2, column=0: c
Type in the value for row=2, column=1: c
Type in the value for row=2, column=2: c
Type in the value for row=2, column=3: c
Type in the value for row=3, column=0: c
Type in the value for row=3, column=1: w
Type in the value for row=3, column=2: c
Type in the value for row=3, column=3: c
['c', 'c', 'c', 'w']
['w', 'c', 'c', 'c']
['c', 'c', 'c', 'c']
['c', 'w', 'c', 'c']
Not all crops are watered; unwatered crops are in position(s): (2, 3), (3, 3)

Related Solutions

Post a Python program that contains an array variable whose values are input by the user....
Post a Python program that contains an array variable whose values are input by the user. It should the perform some modification to each element of array using a loop and then the modified array should be displayed. Include comments in your program that describe what the program does. Also post a screen shot of executing your program on at least one test case.
Java Programming I need an application that collects the user input numbers into an array and...
Java Programming I need an application that collects the user input numbers into an array and after that calls a method that sums all the elements of this array. and display the array elements and the total to the user. The user decides when to stop inputting the numbers. Thanks for your help!
PYTHON Write a python program that encrypts and decrypts the user input. Note – Your input...
PYTHON Write a python program that encrypts and decrypts the user input. Note – Your input should be only lowercase characters with no spaces. Your program should have a secret distance given by the user that will be used for encryption/decryption. Each character of the user’s input should be offset by the distance value given by the user For Encryption Process: Take the string and reverse the string. Encrypt the reverse string with each character replaced with distance value (x)...
I am working on making a simple grade book that will take user input like name...
I am working on making a simple grade book that will take user input like name and grade and then return the name and grade of multiple inputs when the person quits the program. Here is the code that I have been working on. This is in Python 3. I can get one line to work but it gives me an error. Here is what it is supposed to look like: These are just examples billy 100 greg 60 jane...
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked...
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked to calculate the sum of all fines in the policeOfficer class from the arraylist i created. I modified the issueParking ticket method which i bolded at the very end to add each issued Parking ticket to the arrayList, i think thats the right way? if not please let me know. What I dont understand how to do is access the fineAmountInCAD from the arrayList...
I am supposed to answer these conceptual questions with this lab simulator, but I can never...
I am supposed to answer these conceptual questions with this lab simulator, but I can never get the simulator to work https://phet.colorado.edu/en/simulation/legacy/energy-skate-park Help please? Energy State Park Lab Handout Click on the “Energy State Park Simulation” link to perform simulations in the setup satisfying the given conditions. Upon opening the simulation, the skate should be alternating between the walls of the skate park with no friction added and with Earth’s gravity. Click on the Show Pie Chart under the Energy...
I am currently working on creating a dice game. I have not figured out how to...
I am currently working on creating a dice game. I have not figured out how to make it work? What should I do to make it work? Here is what I have so far: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Dice Game</title> <link rel="stylesheet" type="text/css" href="dice.css"> </head> <body> <div class="row" align="center"> <div class="col-4"> <h3>Your Dice</h3> <img src="dice images/m1.png" width="100" height="100" alt="roll: 1" id="mydice1"/> <img src="dice images/m1.png" width="100" height="100" alt="roll: 1" id="mydice2"/> </div> <div class="col-4"> <h3>Opponent's Dice</h3> <img src="dice images/o1.png" width="100"...
I am working on creating a Wiebull distribution from a large set of data I have....
I am working on creating a Wiebull distribution from a large set of data I have. Everything I find online says that I should be given the shape parameter (beta), and scale parameter (eta/apha). I do not have these numbers and I am not sure how to find them to accurately create a Weibull dist.
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
I am trying to make a Risk Management tool in Python. I have it partially started....
I am trying to make a Risk Management tool in Python. I have it partially started. The scenario is that the Project Manager needs to be able to log on and enter information ( the required information is located in the code). I then need to capture that data and store it in an array with the ability to call back and make changes if necessary. Could you please help me out and explain what was done? Current code: Start...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT