回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>这个问题特别是关于使用生成器语句的问题,源于Udacity的计算机程序设计课程:</p>
<p>旨在解决这个难题<a href="https://en.wikipedia.org/wiki/Zebra_Puzzle" rel="nofollow">https://en.wikipedia.org/wiki/Zebra_Puzzle</a>
这个img可能更可读<a href="http://imgur.com/klkaSry" rel="nofollow">http://imgur.com/klkaSry</a></p>
<pre><code>import itertools
def zebra_puzzle():
houses = [first, _, middle, _,_] = [1,2,3,4,5]
orderings = list(itertools.permutations(houses))
return next((WATER, ZEBRA)
for (red, green, ivory, yellow, blue) in orderings
if im_right(green,ivory)
for (Englishman, Spaniard, Ukranian, Japanese, Norwegian) in orderings
if Englishman is red
if first is Norwegian
if nextto(Norwegian, blue)
for (dog, snails, fox, horse, ZEBRA) in orderings
if Spaniard is dog
for (coffee, tea, milk, oj, WATER) in orderings
if coffee is green
if Ukranian is tea
if middle is milk
for (OldGold, Kools, Chesterfields, LuckyStrike, Parliaments) in orderings
if OldGold is snails
if Kools is yellow
if nextto(Chesterfields, fox)
if nextto(Kools,horse)
if LuckyStrike is oj
if Parliaments is Japanese
)
def im_right(h1,h2):
return h1-h2 == 1
def nextto(h1,h2):
return abs(h1-h2) == 1
def main():
zebra_puzzle()
if __name__ == '__main__':
main()
</code></pre>
<p>我在projecteuler中经常遇到这样的问题,这会很有用,但我最终不得不使用普通的嵌套循环。你知道吗</p>
<p>还有,这个问题可以吗?你知道吗</p>