W by H grid tiles?

时间:2017-01-25 16:33:37

标签: python grid

想象一下,我们有wh网格,其中的图块从左上角的1开始编号。 w(宽度)和h(高度)已存储在函数中。您可以访问这些存储的值,只要您将其称为wh即可。编写要返回的程序:用户给出的区号的列号。开始计算第1列的列。

import subprocess
    def template(w, h, t):

        #w and h are memory locations that already contain values
        tile = t

        sum = ((t - 1) // w) + 1 
#END OF YOUR CODE

failed = 0
width = 1
while width <= 3:
    height = 1
    while height <= 3:
        tile = 1
        while tile  <=  width * height:
            result  =  template(width, height, tile)
            col = (tile - 1) % width + 1
            if (result == col):
                print "On a " + str(width) + " by " + str(height) +" board, with tile " + str(tile) +", col is " + str(col) + ", you got it RIGHT!"
            else:
                print "On a " + str(width) + " by " +:str(height)%+" board, with tile " + str(tile)%+", col is " + str(col) + ", you got: " + str(result)
                failed = 1
            tile += 1
        height += 1
    width += 1



if (failed == 0):
    print "Your code is CORRECT!"

    print "Please check your code, at least one test case did not pass."

我认为我几乎就在那里,但这个公式并不完全正确,而且我没有想法。

2 个答案:

答案 0 :(得分:0)

要创建网格,请使用list comprehension

grid=[list(range(x,x+w))for x in range(1,w*h,w)]

要查找t的列号,请查找t的剩余部分除以w

t%w

所以函数将是:

def template(w,h,t):
    grid=[list(range(x,x+w))for x in range(1,w*h,w)]
    return t%w

示例:

template(6,5,22)

输出:

4

答案 1 :(得分:0)

见下面的伪代码,这种方法适合你,

# divide t by h, the tile should reside in the next row
tileRow = (t/h)+1
# get the reminder of the division, that's the column number
tileColumn = t%h

请参阅我在下面尝试的示例代码

>>> w = 5
>>> h = 10
>>> t =36
>>> tileRow = (t/h)+1
>>> tileRow
4     # the tile is in the 4th row
>>> tileColumn = t%h
>>> tileColumn
6     # the tile is in the 6th column
>>> 

您可能还需要检查图块编号是否在范围内,在上面的例子中是w x h(50)

如果您需要进一步澄清,请发表评论。如果这可以解决您的问题,您可以接受并投票给答案