7/19 Hide


#1



https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/7?curriculum_id=4f89dab3d788890003000096


This code does pass, but I had a quick question. Why are we not allowed to return randint(1,5) and we have to use randint(0, len(board)-1) instead? When I tried returning with limits (1,5), it wouldn't let me pass.


from random import randint 

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

# Add your code below!

def random_row(board):
    return randint(0,len(board)-1)
    
def random_col(board):
    return randint(0,len(board)-1)

random_row(board)
random_col(board)


#2

If you wrote a program that looked like this:

print 1 + 2

Then it would be rather useless, and an extremely bloated way of expressing 3, its only result.
If you instead did the following:

import sys
print sum(map(int, sys.argv[1:]))

Then you would have a program that sums integers provided as arguments to the program. Far more useful:

$ python2 add.py 45 2 1 -3
45

So by hard-coding values you make something much less useful.

You'll further make it more difficult to change (such as changing the board size) and make it much more likely to become buggy when you do, by breaking code as you make changes or by forgetting to change everything that should now act differently. Besides, it's not really automating if you have to manually re-write everything if anything changes.


#3

Why wouldn't I be allowed to code

return randint(1, len(board))

instead of

return randint(0, len(board)-1)

then?


#4

"allow" is bit of a strong term, you'll just have to consider what effect that change has. They'll both do something, the question is which one matches the intended behaviour.


#5

Is the answer a question? Cuz you are making people think about the code more than we should... :grinning::grinning::grinning:


#6

I'm having a problem with this piece of code where I can't find out what is wrong.

from random import randint 

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

# Add your code below!
def random_row(board):
    randint(0, len(board) - 1)
def random_col(board):
    randint(0, len(board) - 1)
    
random_row(board)
random_col(board)

Fixed!

from random import randint

board = []

for x in range(0,5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

random_row(board)
random_col(board)

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.