我对此非常困惑,正在努力,但我不认为我得到了想要的

2024-09-25 00:36:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很困惑,需要你的帮助,我试过,但不认为我得到了我应该得到的

5a. (5 pts) Write a function takes an input parameter an integer x, and generates a list of that many 0’s and returns that list.
5b.( 6 pts) Now write a function that takes as an input parameter the same integer and, using the first function, generates a list of x lists of 0’s (so you’ll be appending the lists you made in the first function onto your new list.

5c.(6 pts) Finally, write a third function that loops 5 times. Each time, it generates a first random number (a) between 0 and x, and then a second random number (b) between 0 and x. It uses those two numbers to change the list of lists at [a][b] to -1. You’ve just placed your battleships onto the board (sort of – I know battleships are different lengths. I didn’t want to complicate this with random length battleships).

#5a

def lister(x):
    return([0]*x)

print(lister(15))


#5b

def lister2(x):
    return [lister(x)]*x

print(lister2(3))

#5c

def looplist(x):
    n=5
    a=lister2(x)
    while n>0:
        r1=randrange(0,(x))
        r2=randrange(0,(x))
        a[r1]=-1
        a[r2]=-1
        print(a)
        n-=1

looplist(4)

Tags: andofthetoanthatdeffunction
1条回答
网友
1楼 · 发布于 2024-09-25 00:36:16

我相信在最后一种方法中你要做的是:

a[r1][r2]=-1

您创建了一个二维数组,因此第一部分a[r1]将得到一个列表,即位于位置[r1]的列表,然后在此列表上访问位置r2,并将值修改为-1。你知道吗

另外,我认为一个简单的for将比您当前使用while循环的解决方案更具可读性:

for _ in range(5):
     #generate the two rands, etc

相关问题 更多 >