- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Python 编写标准的康威生命游戏程序。当我迭代数组时尝试计算邻居时遇到问题。我创建了打印语句来打印 if 语句的连续性,以及每个语句的 count 值。
这是我的代码:(我在整个代码的#内都有问题)
import random
numrows = 10
numcols = 10
def rnd():
rn = random.randint(0,1)
return rn
def initial():
grid = []
count = 0
for x in range(numrows):
grid.append([])
for y in range(numcols):
rand=random.randrange(1,3)
if(rand == 1):
grid[x].append('O')
else:
grid[x].append('-')
for x in grid:
print(*x, sep=' ',end="\n") #this prints the random 2d array
print("")
print("")
answer = 'y'
newgrid = []
count = 0
while(answer == 'y'): # I believe I am going through, checking neighbors
# and moving onto the next index inside these for
#loops below
for r in range(0,numrows):
grid.append([])
for c in range(0,numcols):
if(r-1 > -1 and c-1 > -1): #I use this to check out of bound
if(newgrid[r-1][c-1] == 'O'):#if top left location is O
count = count + 1 #should get count += 1
else:
count = count
print("top left check complete")
print(count)
if(r-1 > -1):
if(newgrid[r-1][c] == 'O'):
count = count + 1
else:
count = count
print("top mid check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r-1][c+1] == 'O'):
count = count + 1
else:
count = count
print("top right check complete")
print(count)
if(c-1 > -1 and r-1 > -1):
if(newgrid[r][c-1] == 'O'):
count = count + 1
else:
count = count
print("mid left check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r][c+1] == 'O'):
count = count + 1
else:
count = count
print("mid right check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c-1] == 'O'):
count = count + 1
else:
count = count
print("bot left check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c] == 'O'):
count = count + 1
else:
count = count
print("bot mid check complete")
print(count)
if(r+1 < numrows and c+1 < numcols):
if(newgrid[r+1][c+1] == 'O'):
count = count + 1
else:
count = count
print("bot right check complete")
print(count)
# I am not sure about the formatting of the code below, how do I know that
# the newgrid[r][c] location is changing? should it be according to the for-
# loop above? Or should it get it's own? If so, how could I construct it as
# to not interfere with the other loops and items of them?
if(newgrid[r][c] == '-' and count == 3):
newgrid[r][c] ='O'
elif(newgrid[r][c] == 'O' and count < 2):
newgrid[r][c] = '-'
elif(newgrid[r][c] == 'O' and (count == 2 or count == 3)):
newgrid[r][c] = 'O'
elif(newgrid[r][c] == 'O' and count > 3):
newgrid[r][c] = '-'
# I'm also confused how to go about printing out the 'new' grid after each
# element has been evaluated and changed. I do however know that after the
# new grid prints, that I need to assign it to the old grid, so that it can
# be the 'new' default grid. How do I do this?
for z in newgrid:
print(*z, sep=' ',end="\n")
answer = input("Continue? y or n( lower case only): ")
newgrid = grid
if(answer != 'y'):
print(" Hope you had a great life! Goodbye!")
initial()
这是当前的输出和错误消息:
>>> initial()
- O - - O - - O - -
- O - - O - - - O O
- O - - O - O O - O
O - - O - - O O O O
O - O O - - - O O -
O - O - O - O - O -
O - O O O O - - O -
- - - - O O O - - O
O O - O - - O - - -
- - O O O - O - - -
top left check complete
0
top mid check complete
0
top right check complete
0
mid left check complete
0
mid right check complete
0
bot left check complete
0
bot mid check complete
0
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
initial()
File "C:\Users\Ted\Desktop\combined.py", line 86, in initial
if(newgrid[r+1][c+1] == 'O'):
IndexError: list index out of range
当我迭代随机数组以查看邻居是什么时,它似乎很好,直到它在检查机器人右邻居时移动到 [0][1]。
此外,中右邻居应该 + 1 才算存活。但是,即使连续使用 if 语句,count 仍然为 0?
问题 1:我怎么可能知道我的 if 条件足以满足数组所有边的 [r][c] 的每个实例?
问题 2:我当前的出界检查方法是否最适合我的情况?有没有办法在检查值之前进行“检查所有内容是否超出范围”?
我现在已经无计可施了。预先感谢您花时间帮助回答我的问题
最佳答案
您收到该索引错误是因为您的 newgrid
仅包含一个空行。并且您在 newgrid
中而不是在 grid
中测试邻居(正如 Blckknght 在评论中提到的那样)。我已经进行了一些修复,但是还有很多工作可以改进此代码。看起来它现在正在工作,但是很难判断你何时正在处理随机生命形式。 :) 我建议为您的程序提供某种使用已知生命模式(例如眨眼器和滑翔机)的方法,以查看它们的行为是否正确。
确保 newgrid
有效的最简单方法是从 grid
复制它。如果我们只是执行 newgrid = grid
,那么就会为 newgrid
对象创建另一个名称。为了正确复制列表的列表,我们需要复制每个内部列表。我的新代码使用 copy_grid
函数来实现这一点。
我修复了在邻居计数部分的 if
测试中遇到的几个小错误,并且简化了根据邻居计数更新单元格的逻辑。我还压缩了生成随机网格的代码,并且添加了一个简单的函数,可以从字符串中读取生命模式并从中构建网格。这让我们可以用 Glider 测试代码。我还添加了一个创建空网格的函数。尽管我在测试期间使用了该函数,但该程序当前并未使用该函数,我想这是一个有用的示例。 :)
import random
# Set a seed so that we get the same random numbers each time we run the program
# This makes it easier to test the program during development
random.seed(42)
numrows = 10
numcols = 10
glider = '''\
----------
--O-------
---O------
-OOO------
----------
----------
----------
----------
----------
----------
'''
# Make an empty grid
def empty_grid():
return [['-' for y in range(numcols)]
for x in range(numrows)]
# Make a random grid
def random_grid():
return [[random.choice('O-') for y in range(numcols)]
for x in range(numrows)]
# Make a grid from a pattern string
def pattern_grid(pattern):
return [list(row) for row in pattern.splitlines()]
# Copy a grid, properly!
def copy_grid(grid):
return [row[:] for row in grid]
# Print a grid
def show_grid(grid):
for row in grid:
print(*row)
print()
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
count = 0
# Above this row
if(r-1 > -1 and c-1 > -1):
if(grid[r-1][c-1] == 'O'):
count += 1
if(r-1 > -1):
if(grid[r-1][c] == 'O'):
count += 1
if(r-1 > -1 and c+1 < numcols):
if(grid[r-1][c+1] == 'O'):
count += 1
# On this row
if(c-1 > -1):
if(grid[r][c-1] == 'O'):
count += 1
if(c+1 < numcols):
if(grid[r][c+1] == 'O'):
count += 1
# Below this row
if(r+1 < numrows and c-1 > -1):
if(grid[r+1][c-1] == 'O'):
count += 1
if(r+1 < numrows):
if(grid[r+1][c] == 'O'):
count += 1
if(r+1 < numrows and c+1 < numcols):
if(grid[r+1][c+1] == 'O'):
count += 1
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
if count < 2 or count> 3:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
#grid = random_grid()
grid = pattern_grid(glider)
run(grid)
此代码确实可以正常工作,但仍有大量改进空间。例如,这是 run()
的改进版本,它通过使用几个循环来压缩邻居计数部分。
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
# This includes the cell itself in the count
count = 0
for y in range(max(0, r - 1), min(r + 2, numrows)):
for x in range(max(0, c - 1), min(c + 2, numcols)):
count += grid[y][x] == 'O'
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
# Remember, this count includes the cell itself
if count < 3 or count > 4:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
关于python - 康威的生命游戏没有正确计算邻居数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40373222/
这个问题已经有答案了: How to do case insensitive string comparison? (23 个回答) 已关闭 3 年前。 用户在我的输入栏中写入“足球”,然后执行第 6
啊,不习惯 javascript 中的字符串。 character_id= + id + correct= + correctOrIncorrect 这就是我需要制作成字符串的内容。如果您无法猜测字符
$(function() { var base_price = 0; CalculatePrice(); $(".math1").on('change', function(e) { Calc
我找不到任何文章回答问题:将Spinnaker部署到Spinnaker将管理的同一Kubernetes集群是否安全/正确?我主要是指生产,HA部署。 最佳答案 我认为Spinnaker和Kuberne
我正在使用MSVC在Windows上从源代码(官方源代码发布,而不是从仓库中)构建Qt5(Qt 5.15.0)。 我正在设置环境。变量,依赖项等,然后运行具有1600万个选项的configure,最后
我需要打印一个包含重复单词的数组。我的数组已经可以工作,但我不知道如何正确计算单词数。我已经知道,当我的索引计数器 (i) 为 49 时,并且当 (i) 想要计数到 50 时,我会收到错误,但我不知道
我正在遵循一个指南,该指南允许 Google map 屏幕根据屏幕尺寸禁用滚动。我唯一挣扎的部分是编写一个代码,当我手动调整屏幕大小时动态更改 True/False 值。 这是我按照说明操作的网站,但
我有一个类“FileButton”。它的目的是将文件链接到 JButton,FileButton 继承自 JButton。子类继承自此以使用链接到按钮的文件做有用的事情。 JingleCardButt
我的 friend 数组只返回一个数字而不是所有数字。 ($myfriends = 3) 应该是…… ($myfriends = 3 5 7 8 9 12). 如果我让它进入 while 循环……整个
这个问题在这里已经有了答案: Is there a workaround to make CSS classes with names that start with numbers valid?
我正在制作一个 JavaScript 函数,当调整窗口大小时,它会自动将 div 的大小调整为与窗口相同的宽度/高度。 该功能非常基本,但我注意到在调整窗口大小时出现明显的“绘制”滞后。在 JS fi
此问题的基本视觉效果可在 http://sevenx.de/demo/bootstrap-carousel/inc.carousel/tabbed-slider.html 获得。 - 如果你想看一看。
我明白,如果我想从函数返回一个字符串文字或一个数组,我应该将其声明为静态的,这样当被调用的函数被返回时,内容就不会“消亡”。 但我的问题是,当我在函数内部使用 malloc 分配内存时会怎样? 在下面
在 mySQL 数据库中存储 true/false/1/0 值最合适(读取数据消耗最少)的数据字段是什么? 我以前使用过一个字符长的 tinyint,但我不确定它是否是最佳解决方案? 谢谢! 最佳答案
我想一次读取并处理CSV文件第一行中的条目(例如打印)。我假设使用Unix风格的\n换行符,没有条目长度超过255个字符,并且(现在)在EOF之前有一个换行符。这意味着它是fgets()后跟strto
所以,我们都知道 -1 > 2u == true 的 C/C++ 有符号/无符号比较规则,并且我有一种情况,我想有效地实现“正确”比较。 我的问题是,考虑到人们熟悉的尽可能多的架构,哪种方法更有效。显
**摘要:**文章的标题看似自相矛盾。 本文分享自华为云社区《Java异常处理:如何写出“正确”但被编译器认为有语法错误的程序》,作者: Jerry Wang 。 文章的标题看似自相矛盾,然而我在“正
我有一个数据框,看起来像: dataDemo % mutate_each(funs(ifelse(. == '.', REF, as.character(.))), -POS) # POS REF
有人可以帮助我使用 VBScript 重新格式化/正确格式化带分隔符的文本文件吗? 我有一个文本文件 ^分界如下: AGREE^NAME^ADD1^ADD2^ADD3^ADD4^PCODE^BAL^A
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我是一名优秀的程序员,十分优秀!