我正在使用一些python来做一些变量名称生成.出于某种原因,我只是得到了我需要的一部分.
import sys
import csv
params = csv.reader(open('params.csv'), delimiter=',', skipinitialspace=True)
flags_r = []
flags_w = []
numbers_r = []
numbers_w = []
station = ['AC1','DC1','DC1']
drive = ['','Fld','Arm']
for i in range(3):
for p in params:
try:
desc = p[1].split(' ')
desc = [part.capitalize() for part in desc]
desc = "".join(desc)
except IndexError, e:
print 'IndexError: %s' %(e,)
continue
print station[i],drive[i],p[0]
flags_r.append( 'mod%(station)s_%(drive)sP%(param)04dr_%(desc)s' % \
{ 'station' : station[i], 'drive' : drive[i], 'param': int(p[0]), 'desc':desc })
flags_w.append( 'mod%(station)s_%(drive)sP%(param)04dw_%(desc)s' % \ …Run Code Online (Sandbox Code Playgroud) 我一直在尝试优化以下两个嵌套循环:
def startbars(query_name, commodity_name):
global h_list
nc, s, h_list = [], {}, {}
query = """ SELECT wbcode, Year, """+query_name+"""
FROM innovotable WHERE commodity='"""+commodity_name+"""' and
"""+query_name+""" != 'NULL' """
rows = cursor.execute(query)
for row in rows:
n = float(row[2])
s[str(row[0])+str(row[1])] = n
nc.append(n)
for iso in result:
try:
for an_year in xrange(1961, 2031, 1):
skey = iso+str(an_year)
h_list[skey] = 8.0 / max(nc) * s[skey]
except:
pass
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢.
我对R很陌生,我正在苦苦挣扎.我有以下代码:
repeat {
if (t > 1000)
break
else {
y1 <- rpois(50, 15)
y2 <- rpois(50, 15)
y <- c(y1, y2)
p_0y <- matrix(nrow = max(y) - min(y), ncol = 1)
i = min(y)
while (i <= max(y)) {
p_0y[i - min(y), ] = (length(which(y1 == i))/50)
i <- i + 1
}
p_y <- matrix(nrow = max(y) - min(y), ncol = 1)
j = min(y)
while (j <= max(y)) {
p_y[j - min(y), ] = (length(which(y == j))/100) …Run Code Online (Sandbox Code Playgroud) 有人问我这个问题,在阅读了一些大的东西后,我仍然无法弄清楚这两个设计中哪一个更快.
如果我在一个方法中有这种嵌套循环
public void someMethod(){
for (a=0;a<10;a++){
for (b=0;b<10;b++){
for (c=0;c<10;c++){
for (d=0;d<10;d++){
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我决定重新设计方法并将2个内部for循环放到另一个类似的方法中
public void someMethod(){
for (a=0;a<10;a++){
for (b=0;b<10;b++){
2loopsMethod();
}
}
}
public void 2loopsMethod(){
for (c=0;c<10;c++){
for (d=0;d<10;d++){
}
}
Run Code Online (Sandbox Code Playgroud)
}
我的问题是重新设计的方法是否会比原始代码更快,因为我将它放在另一个方法中或者它没有任何区别?
我有两张不同的桌子.对于那些我选择一些结果.在第一个基于最小值/最大值,第二个基于Lat/Lng.这很容易(不要过多关注值)并且由以下因素创建:
$sql1="SELECT * FROM events WHERE value BETWEEN '".$min2d."' AND '".$max2d."'";
$sql2="SELECT * FROM locations WHERE (lng BETWEEN ".$wl." AND ".$el.") AND (lat BETWEEN '".$sl."'AND'".$nl."')";
Run Code Online (Sandbox Code Playgroud)
既然我们已经缩小了结果,我们希望匹配'id'第一个表的行(如果存在于第二个表中).成功的我们创造了结果.
所以让我们先得到一些数字:
$result1 = mysql_query($sql1);
$result2 = mysql_query($sql2);
$numRows1 = mysql_num_rows($result1);
$numRows2 = mysql_num_rows($result2);
$loopCount1 = 1;
$loopCount2 = 1;
Run Code Online (Sandbox Code Playgroud)
为了更有效地解析JSON(来自用户),我们希望通过将事件创建为JSON数组来对事件进行排序,并将该位置作为"持有者".这意味着,每个位置可能有几个事件.
某些位置可能没有事件,但某些事件可能与某个位置不对应.我们唯一的比较方法是相同的'id'.
通过我的以下尝试,当然即使对于那些没有事件的人,也会为所有(那个错误的)位置创建错误.这就是我需要你宝贵帮助的地方.
$json = '{"markers":[';
while ($row2 = mysql_fetch_array($result2)){
$json .= '{"coordinates": { "lat":'. …Run Code Online (Sandbox Code Playgroud) 我有嵌套的json对象它包含列表和dicts ..我想在里面搜索所有'foo'键.我正在尝试做递归生成器,但是在解析dunno的第二次调用时函数失败,为什么,我甚至只看到'in'输出一次.看起来翻译不会第二次进入解析等等.帮我理解哪里错了?
def parse(d,key):
print('in')
if type(d)==type({}):
if key in d:
yield d[key]
for k in d:
parse(d[k],key)
if type(d)==type([]):
for i in d:
parse(i,key)
Run Code Online (Sandbox Code Playgroud) 我正在开发一个项目,我需要使用Python执行shell脚本.到目前为止一切都很好看.
下面是我的Python脚本,它将执行一个简单的hello world shell脚本.
MAX_TRIES = 2
jsonStr = '{"script":"#!/bin/bash \\n echoo Hello world 1 "}'
j = json.loads(jsonStr)
shell_script = j['script']
steps = ['step1', 'step2', 'step3']
for step in steps:
print "start"
print step
for i in xrange(MAX_TRIES):
proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if stderr:
print "Shell script gave some error..."
sleep(0.05) # delay for 50 ms
else:
print "end" # Shell script ran fine.
break
Run Code Online (Sandbox Code Playgroud)
在我上面的脚本中,如果上面的shell脚本由于某种原因而失败并且工作正常,我会重试两次.
现在我的问题是,在上面的脚本中,我有一个错误的shell脚本,它将失败.我有一个for循环,它将steps逐个迭代列表并执行shell脚本.
目前,每个步骤都会打印出来,这不是我想要的 -
start
step1 …Run Code Online (Sandbox Code Playgroud) 我已经搜索过这个问题的简单解决方案.
我有一个叫做的方法
printCross(int size,char display)
Run Code Online (Sandbox Code Playgroud)
它接受一个大小并打印一个X,其中包含它接收的高度和宽度的char变量.
调用方法printShape(int maxSize, char display)接受形状的最大大小并进入循环,向printCross方法发送2的倍数,直到达到最大值.
这是我的代码,但它没有给我预期的结果.
public static void drawShape(char display, int maxSize)
{
int currentSize = 2; //start at 2 and increase in multiples of 2 till maxSize
while(currentSize<=maxSize)
{
printCross(currentSize,display);
currentSize = currentSize + 2;//increment by multiples of 2
}
}
public static void printCross(int size, char display)
{
for (int row = 0; row<size; row++)
{
for (int col=0; col<size; col++)
{
if (row == col)
System.out.print(display);
if (row == …Run Code Online (Sandbox Code Playgroud) 如何检查整数是否可以表示为长度为n的给定数组中元素的线性组合?当前,当n = 2时,我可以为特定情况编写代码,但是当n未知时,我不知道如何编码。
这是n = 2时的函数(当数组中只有两个元素时):
bool check(int array[], int n, int value){//n values in the array //
for (int i=1; i<array[0]; i++){
for (int j=1; j<array[1]; j++){
if ((i*array[0]+j*array[1])%value==0){
printf("x=%d, y=%d, i=%d, j=%d\n", array[0], array[1], i, j);
return 1;
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在2d平面上,有一个以(0,0)为中心的大圆,半径为.它包含约100个左右的较小圆圈,这些圆圈在父圆上随机分布,否则具有相对于原点的已知半径和位置.(有些较小的子圆可能部分或全部位于较大的子圆内.)
整个平面均匀地网格化为像素,边长为水平和垂直(沿坐标轴).像素的大小是固定的并且是先验已知的,但是远小于父圆的大小; 在父圆圈上有大约1000个特殊像素的顺序.我们给出了所有这些特殊网格(的中心)的2D笛卡尔坐标.包含这些特殊网格中的至少一个的那些子圆被命名为*特殊的"子圆圈以供以后使用.
现在,想象一下所有这个3d空间都充满了~100,000,000个粒子.我的代码尝试在每个特殊子圈内添加这些粒子.
我设法调试我的代码,但似乎当我处理如此大量的粒子时,它很慢,如下所示.我想看看我是否可以使用任何技巧来加速它至少一个数量级.
.
.
.
for x, y in zip(vals1, vals2): # vals1, vals2 are the 2d position array of the *special* grids each with a 1d array of size ~1000
enclosing_circles, sub_circle_catalog, some_parameter_catalog, totals = {}, [], [], {}
for id, mass in zip(ids_data, masss_data): # These two arrays are equal in size equal to an array of size ~100,000,000
rule1 = some_condition # this check if each special grid is within each circle …Run Code Online (Sandbox Code Playgroud)