所以,在通过"Scala for the Impatient"的过程中,我发现自己在想:你能不使用Scala for循环吗?
例如,本书中有一个练习,要求您构建一个无法递增超过Integer.MAX_VALUE的计数器对象.为了测试我的解决方案,我编写了以下代码:
var c = new Counter
for( i <- 0 to Integer.MAX_VALUE ) c.increment()
Run Code Online (Sandbox Code Playgroud)
这会引发错误:序列不能包含多个Int.MaxValue元素.在我看来,这意味着Scala首先分配和填充序列对象,值为0到Integer.MaxValue,然后在该序列对象上执行foreach循环.
我意识到我可以这样做:
var c = new Counter
while(c.value < Integer.MAX_VALUE ) c.increment()
Run Code Online (Sandbox Code Playgroud)
但有没有办法用for语句做一个传统的C风格for循环?
我偶然遇到过这样的情况:
while (true) {
while (age == 5); //What does this semi-colon indicate?
//Code
//Code
//Code
}
Run Code Online (Sandbox Code Playgroud)
这while(true)表明这是一个无限循环,但我无法理解while条件完成后的分号是什么,是不是等于这个?:
while (age == 5) { }
//Code
//Code
Run Code Online (Sandbox Code Playgroud)
换句话说,它是否意味着while循环是无用的,因为它永远不会进入块?
我是mysqli的新手,并且遇到了使用mysqli循环结果的问题.不幸的是,我只得到了一个结果.当我将查询放入phpMyAdmin时,它会得到三个结果.我相信相关的代码在这里,我只是称错了:
$connection = new mysqli($host, $databaseUsername, $databasePassword, $database);
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT clientId, studentFirstName, studentLastName
FROM clients
WHERE (studentEmail = '$postEmail') OR (parentEmail = '$postEmail');";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
echo '<select class = "toolbarDropdown" id = "toolbarDropdown-MultipleAccounts">';
while ($row = $result->fetch_array()) {
echo '<option value="'.$row["clientId"].'">'.$row["studentFirstName"].' '.$row["studentLastName"].'</option>';
}
echo '</select>';
Run Code Online (Sandbox Code Playgroud) 我总是有问题放在;最后while或不放在do while循环结束.那是什么原因?为什么
int numItemsToProcess = 3;
while(numItemsToProcess > 0)
{
// process an item
numItemsToProcess--;
}
Run Code Online (Sandbox Code Playgroud)
;最后不需要但是
do
{
numItemsToProcess --;
} while (numItemsToProcess > 0);
Run Code Online (Sandbox Code Playgroud)
呢?也许原因并不太重要.但是当你知道你能记住放在哪里的原因时;.
我正在尝试创建一种类型的多个对象.然后我想将这些值传输到数组列表中.如何使用具有不同名称的while循环创建对象.例如,这里是我的代码,但它只会生成一个名称的对象.
Customer cust = new Customer("bob", 20.0);
Run Code Online (Sandbox Code Playgroud)
和我的构造函数,如果你想看到:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
Run Code Online (Sandbox Code Playgroud)
StoreTest类(使用main方法):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{ …Run Code Online (Sandbox Code Playgroud) 这是一个非常简单的C程序:
int main()
{
int i = 0;
while(i++ < 10)
printf("%d\n", i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
为什么0不打印第一个数字?如果我更换了i++,++i我会得到这个:
1
2
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)
对于两者而言i++,++i第一个数字是1.
我期望0在while循环中看到for post增量while().
谢谢.
在我的一些项目中,我经常使用do-while-checkNextForNull-getNext循环模式(不知道它是否有正式名称).但是在Java8中,使用Optional比在客户端代码中检查空引用更清晰.但是当在这个循环模式中使用Optional时,代码有点冗长和丑陋,但是因为Optional有一些方便的方法,我希望必须存在比我下面提到的方法更清晰的方法.
例:
鉴于以下课程.
class Item {
int nr;
Item(nr) {
this.nr = nr;
// an expensive operation
}
Item next() {
return ...someCondition....
? new Item(nr + 1)
: null;
}
}
Run Code Online (Sandbox Code Playgroud)
其中第一个项目始终具有nr == 1并且每个项目确定下一个项目,并且您不希望创建不必要的新项目.
我可以在客户端代码中使用以下循环do-while-checkNextForNull-getNext模式:
Item item = new Item(1);
do {
// do something with the item ....
} while ((item = item.next()) != null);
Run Code Online (Sandbox Code Playgroud)
使用Java8-Optional,给定的类变为:
class Item {
....
Optional<Item> next() {
return ...someCondition....
? Optional.of(new Item(nr + 1))
: Optional.empty();
}
}
Run Code Online (Sandbox Code Playgroud)
然后do-while-checkNextForNull-getNext循环模式变得有点丑陋和冗长:
Item item = …Run Code Online (Sandbox Code Playgroud) 该进程替换工作与文件名细,比如他们都
$ cat <FILENAMERun Code Online (Sandbox Code Playgroud)
和
$ while read i; do echo $i; done <FILENAMERun Code Online (Sandbox Code Playgroud)
工作.
但是如果我们使用echo命令(或任何其他生成输出到stdout的命令)而不是FILENAME ,则cat继续工作
$ cat <(echo XXX)
XXXRun Code Online (Sandbox Code Playgroud)
而循环
$ while read i; do echo $i; done <(echo XXX)
bash: syntax error near unexpected token `<(echo XXX)'
Run Code Online (Sandbox Code Playgroud)
产生错误.
有什么想法吗?
我是multiprocessingpython中的新软件包,对于那些了解更多内容的人来说,我的困惑可能很容易.我一直在阅读有关并发的内容,并且已经搜索了其他类似的问题并且一无所获.(仅供参考我不希望使用multithreading,因为GIL将我的应用程序有很多慢下来.)
我在事件的框架内思考.我希望有多个进程在运行,等待事件发生.如果事件发生,它将被分配给特定进程,该进程运行然后返回其空闲状态.可能有更好的方法来做到这一点,但我的理由是我应该生成所有进程一次并使它们无限期地打开,而不是每次事件发生时创建然后关闭进程.速度对我来说是一个问题,我的事件每秒可能发生数千次.
我想出了以下玩具示例,其意图是将偶数发送到一个进程,将奇数发送到另一个进程.两个进程都是相同的,它们只是将数字附加到列表中.
from multiprocessing import Process, Queue, Pipe
slist=['even','odd']
Q={}
Q['even'] = Queue()
Q['odd'] = Queue()
ev,od = [],[]
Q['even'].put(ev)
Q['odd'].put(od)
P={}
P['even'] = Pipe()
P['odd'] = Pipe()
def add_num(s):
""" The worker function, invoked in a process. The results are placed in
a list that's pushed to a queue."""
# while True :
if not P[s][1].recv():
print s,'- do nothing'
else:
d = Q[s].get()
print d
d.append(P[s][1].recv())
Q[s].put(d)
print Q[s].get()
P[s][0].send(False)
print …Run Code Online (Sandbox Code Playgroud) python multiprocessing while-loop python-2.7 python-multiprocessing
给定TensorFlow tf.while_loop,如何计算x_out每个时间步长相对于网络所有权重的梯度?
network_input = tf.placeholder(tf.float32, [None])
steps = tf.constant(0.0)
weight_0 = tf.Variable(1.0)
layer_1 = network_input * weight_0
def condition(steps, x):
return steps <= 5
def loop(steps, x_in):
weight_1 = tf.Variable(1.0)
x_out = x_in * weight_1
steps += 1
return [steps, x_out]
_, x_final = tf.while_loop(
condition,
loop,
[steps, layer_1]
)
Run Code Online (Sandbox Code Playgroud)
一些笔记
tf.gradients(x, tf.trainable_variables())崩溃AttributeError: 'WhileContext' object has no attribute 'pred'.似乎tf.gradients在循环中使用的唯一可能性是仅计算相对于weight_1和x_in/时间步的当前值的梯度而不反向传播时间.