小编joj*_*ojo的帖子

生成列表的所有排列而不相邻的相等元素

当我们对列表进行排序时,比如

a = [1,2,3,3,2,2,1]
sorted(a) => [1, 1, 2, 2, 2, 3, 3]
Run Code Online (Sandbox Code Playgroud)

等值元素在结果列表中始终相邻.

我怎样才能完成相反的任务 - 对列表进行洗牌,使相邻的元素永远(或尽可能不相邻)相邻?

例如,对于上面的列表,可能的解决方案之一是

p = [1,3,2,3,2,1,2]
Run Code Online (Sandbox Code Playgroud)

更正式地说,给定一个列表a,生成一个p最小化对的数量的排列p[i]==p[i+1].

由于列表很大,因此不能生成和过滤所有排列.

奖金问题:如何有效地生成所有这些排列?

这是我用来测试解决方案的代码:https://gist.github.com/gebrkn/9f550094b3d24a35aebd

UPD:在这里选择获胜者是一个艰难的选择,因为许多人发布了很好的答案.@VincentvanderWeele,@大卫Eisenstat,@Coady,@ enrico.bacis@srgerg提供函数完美产生的最佳可能的排列.@tobias_k和大卫也回答了红利问题(生成所有排列).大卫的其他要点是正确性证明.

来自@VincentvanderWeele的代码似乎是最快的.

python algorithm combinatorics

86
推荐指数
7
解决办法
9784
查看次数

使用psycopg2连接到数据库而不使用密码

我在localhost上有一个postgres数据库,我可以在没有密码的情况下访问

$ psql -d mwt
psql (8.4.12)
Type "help" for help.

mwt=# SELECT * from vatid;
  id   | requester_vatid |...
  -----+-----------------|...   
  1719 | IT00766780266   |...
Run Code Online (Sandbox Code Playgroud)

我想从django访问该数据库.所以我投入了DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mwt',
        'USER': 'shaoran',
        'HOST': 'localhost'
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我不需要密码来访问我的测试数据库,因此我没有PASSWORD在设置中提供任何值.

$ ./manage.py shell
>>> from polls.models import Vatid
>>> Vatid.objects.all()
  connection_factory=connection_factory, async=async)
  OperationalError: fe_sendauth: no password supplied
Run Code Online (Sandbox Code Playgroud)

我尝试使用,PASSWORD: ''但我收到相同的错误消息.我尝试使用,PASSWORD: None但这也没有帮助.

我一直在搜索关于这个的django文档,但我找不到任何有用的东西.可以配置django.db.backends.postgresql_psycopg2为接受空密码?

python django postgresql psycopg2

44
推荐指数
4
解决办法
3万
查看次数

AppRegistryNotReady:无法初始化转换基础结构

当我尝试访问我的应用程序时,我收到以下错误.

AppRegistryNotReady:在应用注册表准备就绪之前,无法初始化转换基础结构.检查您是否在导入时不进行非延迟的gettext调用

这是我的wsgi.py文件:

"""                                                                                                                                                                                     
WSGI config for Projectizer project.                                                                                                                                                    

It exposes the WSGI callable as a module-level variable named ``application``.                                                                                                          

For more information on this file, see                                                                                                                                                  
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/                                                                                                                            
"""

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Projectizer.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪.

mod_wsgi (pid=28928): Exception occurred processing WSGI script '/var/www/projectizer/apache/django.wsgi'.

Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 187, in __call__

    response = self.get_response(request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 199, in get_response

    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 236, in handle_uncaught_exception …
Run Code Online (Sandbox Code Playgroud)

python django django-i18n

19
推荐指数
4
解决办法
1万
查看次数

Python 3.x的字典视图对象和matplotlib

在蟒蛇3.X keys(),values()items()返回意见.现在虽然视图肯定有优势,但它们似乎也会导致一些兼容性问题.例如matplotlib(最终是numpy).作为一个例子对stackexchange问题的答案只是正常工作与Python 2.x的,但在Python 3.4执行他们的时候抛出一个异常.

一个最小的例子是:

import matplotlib.pyplot as plt
d = {1: 2, 2: 10}
plt.scatter(d.keys(), d.values())
Run Code Online (Sandbox Code Playgroud)

哪个TypeError: float() argument must be a string or a number, not 'dict_values'用python 3.4 引发.

虽然对于最小的例子,Exception非常清楚,但是由于同样的问题而出现了这个问题,而且这里的Exception不太清楚:TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' …

python numpy matplotlib python-3.x

14
推荐指数
1
解决办法
3087
查看次数

使用python xlrd将日期作为字符串读取而不是从excel中浮动

可能重复:
如何在Python中读取Excel格式的日期?

我的日期可以在excel文件的任何字段中,但是当我使用python xlrd读取它时,它被读作浮点数.有没有办法将所有excel单元格读取为字符串?

我想准备一个脚本来生成一个文件,其中excel文件中的所有值都由管道分隔,但这个日期的事情正在产生问题.

python xlrd

13
推荐指数
1
解决办法
3万
查看次数

如何在子类中装饰继承的方法?

我不太确定如何在继承的方法上使用装饰器.通常装饰器放在定义之前,但对于继承的函数,定义是在父类而不是子类中给出的.我想避免重写子类中方法的定义,只需指定将装饰器放在继承的方法周围.

为了让自己更清楚,这是我的意思的一个实例:

class Person():
    def __init__(self, age):
        self.age = age

    @classmethod
    def gets_drink(cls, ):
        print "it's time to get a drink!"
        return "A beer"

def dec(some_f):
    def legal_issue(obj,):
        some_f(obj)
        return 'A Coke'
    return legal_issue

class Child(Person):
    def __init__(self, age):
        Person.__init__(self, age=age)

    #in principle i'd like to write
    #@dec
    #self.gets_drink
    #which does not work
    #the only working way I found is by defining the method as a classmethod
    #and write this:

    @dec
    def gets_drink(self, ):
        return Person.gets_drink()

dad = Person(42)
son …
Run Code Online (Sandbox Code Playgroud)

python inheritance decorator python-2.7 python-decorators

10
推荐指数
1
解决办法
3311
查看次数

按升序/降序排列条形图

我有一个随机森林特征重要性程序。已为每个变量生成所有特征重要性参数。我还将其绘制在水平条形图上。

现在我想将条形按升序/降序排序。我该怎么做?

我的代码如下:

#Feature Selection (shortlisting key variables)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score

df = pd.read_excel(r'C:\Users\z003v0ee\Desktop\TP Course\project module\ProjectDataSetrev4.xlsx',sheet_name=0)
df2 = pd.read_excel(r'C:\Users\z003v0ee\Desktop\TP Course\project module\ProjectDataSetrev4.xlsx',sheet_name=1)

## Convert date time format and set as index
df['DateTime']=pd.to_datetime(df['Time Stamp'], format='%Y-%m-%d %H:%M:%S')
df.set_index(df['DateTime'], inplace=True)

## Save each feature to a list (independent variables)
allvarlist = …
Run Code Online (Sandbox Code Playgroud)

python visualization scikit-learn sklearn-pandas

8
推荐指数
1
解决办法
5万
查看次数

基于其元素的成对关联对排序列表进行排序

比如[1,2,3,4],给出一个元素列表,以及它们的成对关联

[[0,  0.5, 1,  0.1]
 [0.5, 0,  1,  0.9]
 [ 1,  1,  0,  0.2]
 [0.1, 0.9, 0.2, 0]]
Run Code Online (Sandbox Code Playgroud)

对于熟悉图论的人来说,这基本上是一个邻接矩阵.

对列表进行排序的最快方法是什么,使列表中的距离与成对关联最佳相关,即具有高隶属关系的节点对应彼此接近.

有没有办法做到这一点(即使是贪婪的算法也没关系),而不必过多地研究MDS排序理论?

作为奖金问题:

请注意,某些成对关联可以完美表示,例如列表[1,2,3]和成对关联:

[[0, 0, 1]
 [0, 0, 1]
 [1, 1, 0]]
Run Code Online (Sandbox Code Playgroud)

完美的秩序将是[1,3,2].但有些隶属关系不能像这样:

[[0, 1, 1]
 [1, 0, 1]
 [1, 1, 0]]
Run Code Online (Sandbox Code Playgroud)

任何订单同样好/坏.

有没有办法告诉订购的质量?从多大程度上说它代表了成对的隶属关系?

sorting algorithm graph-theory greedy

6
推荐指数
1
解决办法
140
查看次数

我可以将一个类定义放入__init__.py吗?

我有一个类似于的类结构的包. Baseclass是一个典型的,简单的父类,用于几个单独的层次结构.

我的包布局如下所示:

__init__.py (empty)
base.py
ab.py
cd.py
ef.py
Run Code Online (Sandbox Code Playgroud)

Base类放入__init__.py而不是仅为一个类创建单独的模块是一个好主意还是一个好习惯?通过这种方式,我不需要每次都在模块中导入它.

python

6
推荐指数
1
解决办法
3345
查看次数

带有axes.title.set_text的子图中的标题字体

我打算制作多个子图来展示我的结果。我使用了 matplotlib 的子图。我有文字大小的问题。正如您在此处的简单代码中所见。在plt.title文档中它说title(label, fontdict=None, loc='center', pad=None, **kwargs)

import random
from matplotlib.pyplot import figure, plot, xlabel, ylabel, legend, close, subplots, title, savefig, get_current_fig_manager, show, pause, clf

x = []
for i in range(10):
    x.append(random.random()*i)

y_1 = []

for i in range(10):
    y_1.append(random.random()*i)
y_2 = []

for i in range(10):
    y_2.append(random.random()*i)


fig, ax = subplots(1, 2, squeeze = False, figsize = (10,10))
ax[0,1].title.set_text('y_1', fontdict = {'font.size':22})
ax[0,1].plot(x,y_1)
ax[0,1].set_xlabel('x')
ax[0,1].set_ylabel('y_1')

ax[0,0].title.set_text('y_2', fontdict = {'font.size':22})
ax[0,0].plot(x,y_2)
ax[0,0].set_xlabel('x')
ax[0,0].set_ylabel('y_2')
Run Code Online (Sandbox Code Playgroud)

但是如果我运行这段代码,我会收到一个错误 TypeError: set_text() …

python matplotlib

6
推荐指数
1
解决办法
6145
查看次数