from queue import LifoQueue def evaluate_expression(expressions) : val = LifoQueue() op = LifoQueue() for c in expressions: if c == '(' or c == '|' or c == '&' or c == '!': op.put(c) elif c == 'V' or c == 'F' or c == ')': b = None if c != ')': b = True if c == 'V' else False else: b = val.get() while not op.empty(): if op.queue[-1] == '!': b = not b op.get() elif op.queue[-1] == '|': pre = val.get() b = pre or b op.get() elif op.queue[-1] == '&': pre = val.get() b = pre and b op.get() val.put(b) ch = 'V' if val.get() else 'F' return ch while True: expressions = input() n=1 if not expressions: break else: q=evaluate_expression(expressions) print("Expression {}: {}".format(n, q)) n+=1
时间: 2024-01-18 21:02:12 浏览: 29
这段代码是用 Python 实现了一个逻辑表达式的求值器,可以计算由 V, F, !, &, |, (, ) 组成的逻辑表达式的值。使用 LifoQueue 作为栈来存储操作数和操作符,通过遍历表达式并依次计算得出结果。在代码最后的 while 循环中,程序会循环读取输入的表达式,并输出计算结果。每次循环会将计算结果和表达式编号一并输出。
相关问题
import time from queue import Queue from threading import Thread class Producer(Thread): def __init__(self, name, queue): Thread.__init__(self, name=name) self.queue = queue def run(self): for i in range(1, 6): print(f'{self.name}将产品{i}放入队列中') self.queue.put(i) time.sleep(1) print('生产者完成了全部的数据存放') class Consumer(Thread): def __init__(self, name, queue): Thread.__init__(self, name=name) self.queue = queue def run(self): for _ in range(5): value = self.queue.get() print(f'消费者线程取出了{value}') time.sleep(1) print('消费者线程完成了所有线程的取出') if __name__ == '__main__': queue = Queue p = Producer('Produce', queue) con = Consumer('Consumer', queue) p.start() con.start() p.join() con.join() print('主线程运行结束')
这是一个生产者-消费者模型的多线程程序。在这个程序中,Producer 类表示生产者,Consumer 类表示消费者。
生产者将 1 到 5 的产品放入队列中,每放入一个产品后休眠 1 秒钟。当生产者完成全部数据存放后,打印"生产者完成了全部的数据存放"。
消费者从队列中取出产品,每次取出后休眠 1 秒钟。当消费者完成所有线程的取出后,打印"消费者线程完成了所有线程的取出"。
在主程序中,创建一个队列对象 queue,并将其作为参数传递给生产者和消费者线程。然后启动生产者和消费者线程,并等待它们完成。最后打印"主线程运行结束"。
这个程序使用了多线程技术,生产者和消费者线程可以并发执行。生产者将产品放入队列中,而消费者从队列中取出产品,实现了线程间的通信和协作。
以下代码有什么错误,怎么修改: import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from PIL import Image import matplotlib.pyplot as plt import input_data import model import numpy as np import xlsxwriter num_threads = 4 def evaluate_one_image(): workbook = xlsxwriter.Workbook('formatting.xlsx') worksheet = workbook.add_worksheet('My Worksheet') with tf.Graph().as_default(): BATCH_SIZE = 1 N_CLASSES = 4 image = tf.cast(image_array, tf.float32) image = tf.image.per_image_standardization(image) image = tf.reshape(image, [1, 208, 208, 3]) logit = model.cnn_inference(image, BATCH_SIZE, N_CLASSES) logit = tf.nn.softmax(logit) x = tf.placeholder(tf.float32, shape=[208, 208, 3]) logs_train_dir = 'log/' saver = tf.train.Saver() with tf.Session() as sess: print("从指定路径中加载模型...") ckpt = tf.train.get_checkpoint_state(logs_train_dir) if ckpt and ckpt.model_checkpoint_path: global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] saver.restore(sess, ckpt.model_checkpoint_path) print('模型加载成功, 训练的步数为: %s' % global_step) else: print('模型加载失败,checkpoint文件没找到!') prediction = sess.run(logit, feed_dict={x: image_array}) max_index = np.argmax(prediction) workbook.close() def evaluate_images(test_img): coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for index,img in enumerate(test_img): image = Image.open(img) image = image.resize([208, 208]) image_array = np.array(image) tf.compat.v1.threading.Thread(target=evaluate_one_image, args=(image_array, index)).start() coord.request_stop() coord.join(threads) if __name__ == '__main__': test_dir = 'data/test/' import glob import xlwt test_img = glob.glob(test_dir + '*.jpg') evaluate_images(test_img)
在代码中,我注意到了几个错误:
1. 在导入`input_data`和`model`模块时,代码中没有找到这两个模块的导入语句。
2. `evaluate_one_image`函数中的`image_array`参数未定义。
3. 在`evaluate_images`函数中,`tf.train.Coordinator()`和`tf.train.start_queue_runners()`函数之间缺少了一个空行。
4. 在调用`evaluate_one_image`函数时,传递的参数应该是`(image_array, index)`而不是`(image_array, index)`。
以下是修改后的代码:
```python
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from PIL import Image
import matplotlib.pyplot as plt
import input_data
import model
import numpy as np
import xlsxwriter
num_threads = 4
def evaluate_one_image(image_array, index):
workbook = xlsxwriter.Workbook('formatting.xlsx')
worksheet = workbook.add_worksheet('My Worksheet')
with tf.Graph().as_default():
BATCH_SIZE = 1
N_CLASSES = 4
image = tf.cast(image_array, tf.float32)
image = tf.image.per_image_standardization(image)
image = tf.reshape(image, [1, 208, 208, 3])
logit = model.cnn_inference(image, BATCH_SIZE, N_CLASSES)
logit = tf.nn.softmax(logit)
x = tf.placeholder(tf.float32, shape=[208, 208, 3])
logs_train_dir = 'log/'
saver = tf.train.Saver()
with tf.Session() as sess:
print("从指定路径中加载模型...")
ckpt = tf.train.get_checkpoint_state(logs_train_dir)
if ckpt and ckpt.model_checkpoint_path:
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
saver.restore(sess, ckpt.model_checkpoint_path)
print('模型加载成功, 训练的步数为: %s' % global_step)
else:
print('模型加载失败,checkpoint文件没找到!')
prediction = sess.run(logit, feed_dict={x: image_array})
max_index = np.argmax(prediction)
workbook.close()
def evaluate_images(test_img):
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for index, img in enumerate(test_img):
image = Image.open(img)
image = image.resize([208, 208])
image_array = np.array(image)
tf.compat.v1.threading.Thread(target=evaluate_one_image, args=(image_array, index)).start()
coord.request_stop()
coord.join(threads)
if __name__ == '__main__':
test_dir = 'data/test/'
import glob
import xlwt
test_img = glob.glob(test_dir + '*.jpg')
evaluate_images(test_img)
```
请注意,我只修复了我在代码中发现的错误,并没有对其他部分进行修改。如果还有其他错误或问题,请提供更多信息,以便我能够更好地帮助你。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)