在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问一共有多少种摆法。
分别用递归回溯算法与遗传算法实现,代码如下
import numpy
def findQueen(column):
if column > 7:
global count
count+=1
print(matrix)
return
else:
for row in range(8):
if check(row,column):
matrix[row][column]=1
arr[column]=row
findQueen(column+1)
matrix[row][column]=0
arr[column]=0
def check(row,column):
for k in range(len(arr)):
if k >= column:
return True
if arr[k] == row or abs(arr[k] - row) == abs(k - column):
return False
if __name__ == '__main__':
count = 0
matrix = numpy.zeros((8,8),dtype=int)
arr = numpy.zeros(8,dtype=int)
findQueen(0)
print(count)
import copy
import random
import math
# 种群大小
population_size = 8
# 父种群的编码列表
parent = []
# 子种群的编码列表
children = []
# 父种群每个个体的适应度
parent_fitness = []
# 子种群每个个体的适应度
children_fitness = []
# 初始化个体
def initial_individual():
# 个体的编码
individual = []
# 8个编码
for i in range(8):
a = random.randint(0, 7)
individual.append(a)
# 计算生成的个体的适应度
fit_score = update_fitness_score(individual)
# 加入到种群中
parent_fitness.append(fit_score)
parent.append(individual)
return
# 更新适应度函数
def update_fitness_score(individual):
value = 0
for i in range(8):
for j in range(i + 1, 8):
if individual[i] != individual[j]:
x = j - i
y = abs(individual[i] - individual[j])
if x != y:
value += 1
return value
# 初始化1个种群,种群大小为population_size
def initial_population():
for i in range(population_size):
initial_individual()
return
# 选择出一个父本
def select():
# 所有个体的适应度之和
total_score = 0
for fit in parent_fitness:
total_score += fit
# 轮盘赌中的数
num = random.randint(0, total_score)
# 前面的适应度之和
front_score = 0
for i in range(population_size):
front_score += parent_fitness[i]
# 如果此时前面的适应度之和大于生成的随机数,那么该数必定落在编号为 i 的个体上
if front_score >= num:
return i
# 变异
def mutation(change_individual):
# 第pos个基因发生变异
pos = random.randint(0, 7)
# 改变的值
change = random.randint(0, 7)
change_individual[pos] = change
return change_individual
# 交叉产生后代
def hybridization():
# 选择两个父本
first = select()
second = select()
selected_parents = copy.deepcopy([parent[first], parent[second]])
# 交换从pos1到pos2的基因
pos1 = random.randint(0, 6)
pos2 = random.randint(0, 6)
# 保证pos1 <= pos2
if pos1 > pos2:
pos1, pos2 = pos2, pos1
# 交叉
tmp = selected_parents[0][pos1:pos2]
selected_parents[0][pos1:pos2] = selected_parents[1][pos1:pos2]
selected_parents[1][pos1:pos2] = tmp
# 一定的概率发生变异,假设概率为0.5
may = random.random()
if may > 0.5:
selected_parents[0] = mutation(selected_parents[0])
may = random.random()
if may > 0.5:
selected_parents[1] = mutation(selected_parents[1])
# 更新适应度
first_fit = update_fitness_score(selected_parents[0])
second_fit = update_fitness_score(selected_parents[1])
# 加入到子代中
children.append(selected_parents[0])
children.append(selected_parents[1])
children_fitness.append(first_fit)
children_fitness.append(second_fit)
return
# 初始化种群
initial_population()
# 计算迭代次数
count = 0
# not a number
find = float('nan')
while True:
count += 1
if count % 1000 == 0:
print('第%d' % count + '次迭代')
# 杂交population_size/2次产生population_size个后代
for k in range(population_size // 2):
hybridization()
# 如果某个个体适应度达到28,说明此时找到了一个解
for k in range(population_size):
if children_fitness[k] == 28:
# 记录解的位置
find = k
break
if not math.isnan(find):
break
# 将子代种群放入父代中作为新的父代,子代清空
parent[0:population_size] = children[0:population_size]
parent_fitness[0:population_size] = children_fitness[0:population_size]
children = []
children_fitness = []
# 此时找到满足要求的子代个体
res = children[find]
print(res)
# 构造棋盘
res_queen = [[0 for i in range(8)] for j in range(8)]
for t in range(8):
res_queen[res[t]][t] = 1
# 将棋盘打印
print("找到结果:")
for t in range(8):
print(res_queen[t])
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
由于fast-stemmer的问题,我很难安装我想要的任何rubygem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。