. Write a program that generates a vector with 30 random integers between –20 and 20 and then finds the sum of all the elements that are divisible by 3.
时间: 2024-03-18 10:38:37 浏览: 75
EWA.zip_The One And Only_cauchy mutation_earthworm_metaheuristic
Sure, here's the Python program to generate a vector with 30 random integers between -20 and 20 and find the sum of all the elements that are divisible by 3:
```python
import random
# Generate a list of 30 random integers between -20 and 20
vec = [random.randint(-20, 20) for _ in range(30)]
# Find the sum of all elements that are divisible by 3
div_by_3_sum = sum([num for num in vec if num % 3 == 0])
# Print the results
print("Generated vector:", vec)
print("Sum of all elements divisible by 3:", div_by_3_sum)
```
This program uses a list comprehension to generate a list of 30 random integers between -20 and 20. Then, it uses another list comprehension to find all the elements in the list that are divisible by 3 and calculates their sum using the `sum()` function. Finally, it prints the generated vector and the sum of all elements that are divisible by 3.
阅读全文