用python随机生成100个2-1000范围内的整数,将生成的原始数据存入yuanshi列表,将素数存入sushu列表,将和数存入heshu列表,如有重复的数据,存入chongfu列表,并将素数的判断定义为一个函数并进行打印;
时间: 2023-06-14 19:04:29 浏览: 88
可以按照如下方法生成100个2-1000范围内的整数,并将它们分别存入yuanshi列表:
```python
import random
yuanshi = []
for i in range(100):
yuanshi.append(random.randint(2, 1000))
```
接下来,可以定义一个判断素数的函数,并将素数存入sushu列表:
```python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
sushu = []
for num in yuanshi:
if is_prime(num):
sushu.append(num)
```
接着,可以将所有数据求和,并将和存入heshu列表:
```python
heshu = []
for num in yuanshi:
heshu.append(sum(yuanshi))
```
最后,可以将重复的数据存入chongfu列表:
```python
chongfu = []
for num in yuanshi:
if yuanshi.count(num) > 1:
chongfu.append(num)
```
完整代码如下:
```python
import random
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
yuanshi = []
for i in range(100):
yuanshi.append(random.randint(2, 1000))
sushu = []
for num in yuanshi:
if is_prime(num):
sushu.append(num)
heshu = []
for num in yuanshi:
heshu.append(sum(yuanshi))
chongfu = []
for num in yuanshi:
if yuanshi.count(num) > 1:
chongfu.append(num)
print("原始数据:", yuanshi)
print("素数:", sushu)
print("和数:", heshu)
print("重复的数据:", chongfu)
```
阅读全文