社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python math在命令行中是正确的,而py文件中却是错误的?

Chau Loi • 6 年前 • 1874 次点击  

我在做一个关于r/dailyprogrammer的项目。 我复制了一个代码作为参考,并试图运行它,但它做的数学苦涩。

def N_queens_validator(n):

(…)这一部分我试图说明董事会

if len(set(n))!=len(n):
    return print(f'{n} =>False same row')

else:
    origin=[(ind,val) for ind,val in enumerate(n)]
    a=origin[:]
    for m in range (len(n)):
        root=a.pop(0)
        for i in range(m+1,len(n)):
            result=root[0]-origin[i][0]/root[1]-origin[i][1]
            print(str(root[0]-origin[i][0])+'/'+str(root[1]-origin[i][0])+'the result is: '+str(result))
            if  np.abs(result)==1:
                return print(f'{n} =>False same diagonal')
    return print(f'{n} =>True')

N_queens_validator([8, 6, 4, 2, 7, 1, 3, 5])

这是一个毫无意义的结果。很明显数学计算错了 The result of program

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54230
文章 [ 1 ]  |  最新文章 6 年前
Steve
Reply   •   1 楼
Steve    7 年前

您的代码有两个问题:

1) 正如用户2357112所说,您需要在两个减法前后加上括号,这样减法就在除法之前完成了。

str(root[1]-origin[i][0]) 应该是 str(root[1]-origin[i][1])

def N_queens_validator(n):

    if len(set(n))!=len(n):
        return print(f'{n} =>False same row')

    else:
        origin=[(ind,val) for ind,val in enumerate(n)]
        a=origin[:]
        for m in range (len(n)):
            root=a.pop(0)
            for i in range(m+1,len(n)):
                result=(root[0]-origin[i][0])/(root[1]-origin[i][1])
                print(str(root[0]-origin[i][0])+'/'+str(root[1]-origin[i][1])+' the result is: '+str(result))
                if abs(result)==1:
                    return print(f'{n} =>False same diagonal')
        return print(f'{n} =>True')

N_queens_validator([8, 6, 4, 2, 7, 1, 3, 5])

结果:

-1/2 the result is: -0.5
-2/4 the result is: -0.5
-3/6 the result is: -0.5
-4/1 the result is: -4.0
-5/7 the result is: -0.7142857142857143
-6/5 the result is: -1.2
-7/3 the result is: -2.3333333333333335
-1/2 the result is: -0.5
-2/4 the result is: -0.5
-3/-1 the result is: 3.0
-4/5 the result is: -0.8
-5/3 the result is: -1.6666666666666667
-6/1 the result is: -6.0
-1/2 the result is: -0.5
-2/-3 the result is: 0.6666666666666666
-3/3 the result is: -1.0
[8, 6, 4, 2, 7, 1, 3, 5] =>False same diagonal