我正在尝试计算具有以下方程式的矩阵。
S = (D^?1/2) * W * (D^?1/2)
Run Code Online (Sandbox Code Playgroud)
其中D是这种形式的对角矩阵:
array([[ 0.59484625, 0. , 0. , 0. ],
[ 0. , 0.58563893, 0. , 0. ],
[ 0. , 0. , 0.58280472, 0. ],
[ 0. , 0. , 0. , 0.58216725]])
Run Code Online (Sandbox Code Playgroud)
和W:
array([[ 0. , 0.92311635, 0.94700586, 0.95599748],
[ 0.92311635, 0. , 0.997553 , 0.99501248],
[ 0.94700586, 0.997553 , 0. , 0.9995501 ],
[ 0.95599748, 0.99501248, 0.9995501 , 0. ]])
Run Code Online (Sandbox Code Playgroud)
我试图D^-1/2通过使用numpyfunction linalg.matrix_power(D,-1/2) …
我是Python的新手我正在尝试一个小的随机时间生成器,它从给定的初始化变量生成随机时间,并以1000条记录的给定结束变量结束,并且必须将这1000条记录保存到数据库中.
我到目前为止已经达到了这个代码.
SQL.py
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///sql.sqlite')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
time = Column(Integer, default=None, index=True)
Base.metadata.create_all(engine)
Run Code Online (Sandbox Code Playgroud)
Random.py
import datetime
import time
import random
MINTIME = datetime.datetime(2010,8,6,8,14,59)
MAXTIME = datetime.datetime(2013,8,6,8,14,59)
RECORDS = 1000
for RECORD in range(RECORDS):
RANDOMTIME = random.randint(MINTIME, MAXTIME)
print RANDOMTIME
Run Code Online (Sandbox Code Playgroud)
它会产生回溯
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int' …Run Code Online (Sandbox Code Playgroud) 我试图找出Python中的生成器,我试图过滤列表并对它们进行平方并返回输出.
list = [1, 4, -5, 10, -7, 2, 3, -1]
def square_generator(optional_parameter):
return (x ** 2 for x in list if x > optional_parameter)
g = (square_generator(i) for i in list)
h = square_generator(0)
print h
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
我有这样的字典
data = {
'a': [95, 93, 90],
'b': [643, 611, 610]
}
Run Code Online (Sandbox Code Playgroud)
我想迭代dict并从每个项的值列表中获取键和值,类似这样
{'a': 95, 'b': 643}
{'a': 93, 'b': 611}
{'a': 90, 'b': 610}
Run Code Online (Sandbox Code Playgroud)
我已经为此实现了逻辑并且它工作正常,但是当我看到正在temp_dict创建的过程中,我看到许多中间不必要的循环.最终的结果很好,但我认为它可以改进很多.
import timeit
data = {
'a': [95, 93, 90],
'b': [643, 611, 610]
}
def calculate(**kwargs):
temp_dict = {}
index = 0
len_values = list(kwargs.values())[0]
while index < len(len_values):
for k, v in kwargs.items():
temp_dict[k] = v[index]
index += 1
yield temp_dict
start_time = timeit.default_timer()
for k in (calculate(**data)):
print(k)
print(timeit.default_timer() …Run Code Online (Sandbox Code Playgroud) 假设我有一个名为A的类,我想列出从该特定类创建的所有对象.这是我到目前为止所做的,它提出了AttributeError: type object 'A' has no attribute 'items'如何做到这一点?
class A:
def __init__(self):
self.items = []
self.items.append(self)
@classmethod
def list_objects(cls):
return cls.items
a = A()
b = A()
print(A.list_objects())
# Expected output is [a,b]
Run Code Online (Sandbox Code Playgroud) 我正在使用Django 1.5.4
我是Django的新手,我试图显示通过管理面板上传的图像,但遗憾的是图像源代码中的url字段为空,如果我更改{{ article.image.url }}为{{ article.image }},则图像网址显示为
<img src="media/abyss.jpg" alt="" height="450"/>
Run Code Online (Sandbox Code Playgroud)
当我点击图片链接时,它说
TypeError at /media/abyss.jpg
can only concatenate tuple (not "unicode") to tuple
Run Code Online (Sandbox Code Playgroud)
请帮我.
Settings.py文件
MEDIA_ROOT = (os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/'),)
MEDIA_URL = '/media/'
Run Code Online (Sandbox Code Playgroud)
Models.py文件
class Article(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=255)
description = models.TextField()
content = models.TextField()
published = models.BooleanField(default=True)
image = models.ImageField(upload_to='media', blank=True)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ['-created']
def get_absolute_url(self):
return …Run Code Online (Sandbox Code Playgroud) 我试图Rainbow Tables用密码加密来解决这个问题,并且只是到目前为止.
import sys
import random
import hashlib
def mt_rand (low = 0, high = sys.maxint):
"""Generate a better random value
"""
return random.randint (low, high)
def substr (s, start, length = None):
"""Returns the portion of string specified by the start and length
parameters.
"""
if len(s) >= start:
return False
if not length:
return s[start:]
elif length > 0:
return s[start:start + length]
else:
return s[start:length]
def unique_salt():
return substr(hashlib.sha1(mt_rand()),0,22)
password = "12345"
salt = unique_salt() …Run Code Online (Sandbox Code Playgroud) d = {
"key": "Impress the playing crowd with these classic "
"Playing Cards \u00a9 Personalized Coasters.These beautiful"
" coasters are made from glass, and measure approximately 4\u201d x 4\u201d (inches)"
".Great to look at, and lovely to the touch.There are 4 coasters in a set.We have "
"created this exclusive design for all card lovers.Each coaster is a different suit, "
"with the underneath.Make your next Bridge, or Teen Patti session uber-personal!"
"Will look great on the bar, or …Run Code Online (Sandbox Code Playgroud) 我试图根据这些表中的技能查询用户.
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
skills = db.relationship('Skill', backref='author', lazy='dynamic')
Run Code Online (Sandbox Code Playgroud)
class Skill(db.Model):
__tablename__ = 'skills'
id = db.Column(db.Integer, primary_key=True)
skill = db.Column(db.String(64), index=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
Run Code Online (Sandbox Code Playgroud)
我在用户表中尝试了这个并得到了这个错误.
@classmethod
def users_by_skill(cls, skill):
return User.query.join(Skill).filter(skill.skill).all()
Run Code Online (Sandbox Code Playgroud)
AttributeError: 'str' object has no attribute 'skill'
Run Code Online (Sandbox Code Playgroud)
我错过了哪里?
我正在尝试对文件名进行哈希处理,然后保存到数据库中。我正在使用 Flask 和 Python 3.4
这是上传代码:
@app.route('/', methods=['GET', 'POST'])
def upload_pic():
if request.method == 'POST':
file = request.files['file']
try:
extension = file.filename.rsplit('.', 1)[1].lower()
except IndexError as e:
abort(404)
if file and check_extension(extension):
# Salt and hash the file contents
filename = md5(file.read() + str(round(time.time() * 1000))).hexdigest() + '.' + extension
file.seek(0) # Move cursor back to beginning so we can write to disk
file.save(os.path.join(app.config['UPLOAD_DIR'], filename))
add_pic(filename)
gen_thumbnail(filename)
return redirect(url_for('show_pic', filename=filename))
else: # Bad file extension
abort(404)
else:
return render_template('upload.html')
Run Code Online (Sandbox Code Playgroud)
当我发布表单时,我收到此错误回溯。 …
python ×10
dictionary ×2
cryptography ×1
datetime ×1
django ×1
generator ×1
list ×1
matrix ×1
numpy ×1
rainbowtable ×1
random ×1
string ×1
unicode ×1