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

I am creating a program in Python that allows the user to input a credit card...
I am creating a program in Python that allows the user to input a credit card number, and determine if the card is valid. This should be done by taking every other number, starting from the right, and adding them together. The doubling each of the other digits, and adding them together as single digits, and then adding the two sums together. For example, if the number 4833 1200 3412 3456 is used, the first sum should be 6+4+2+4+0+2+3+8=29, the...
JAVA - I am asking for the user to input their firstName and lastName but I...
JAVA - I am asking for the user to input their firstName and lastName but I want the method myMethod() to be able to print it when it is called. Is that possible? I'm new to Java and i'm not too sure what I should do to fix this. Also if I were to create a IF statement would I have to declare int amountDeposited; , int accountBalance; , int newBalance; in the new if statement. import java.util.Scanner; import java.util.Arrays;...
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.
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
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)...
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 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...
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"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT