1.幸运数字6(包括6的倍数):输入任意数字,例如数字8,生成nums列表,元素值为[1~8],从中选取幸运数字移动到新列表lucky,输出nums与lucky。 2.列表嵌套:有3间教室[[],[],[]],8名教师['TeacherA','TeacherB','TeacherC','TeacherD','TeacherE','TeacherF','TeacherG','TeacherH'],需要将8名教师随机分配到3间教室中,每间教室至少有一名教师 3.编程实现:用户输入月份,输出这个月是大月还是小月,共有多少天 4.随机生成1000个大小在[1, 100]的整数,统计其中每个整数出现的次数 作业状态
时间: 2023-06-11 16:10:12 浏览: 517
1. 幸运数字6(包括6的倍数)的代码如下:
```python
num = int(input("请输入一个数字:"))
nums = list(range(1, num+1))
lucky = [n for n in nums if n % 6 == 0]
print("nums:", nums)
print("lucky:", lucky)
```
2. 列表嵌套的代码如下:
```python
import random
classrooms = [[], [], []]
teachers = ['TeacherA', 'TeacherB', 'TeacherC', 'TeacherD', 'TeacherE', 'TeacherF', 'TeacherG', 'TeacherH']
for teacher in teachers:
classroom = random.choice(classrooms)
classroom.append(teacher)
while not all(classrooms):
empty_classrooms = [i for i in range(len(classrooms)) if not classrooms[i]]
teacher = random.choice(teachers)
classroom = random.choice(empty_classrooms)
classrooms[classroom].append(teacher)
print("教室分配情况:")
for i, classroom in enumerate(classrooms):
print("教室{}:{}".format(i+1, classroom))
```
3. 判断月份大小月的代码如下:
```python
month = int(input("请输入月份:"))
if month in [1, 3, 5, 7, 8, 10, 12]:
print("这是大月,有31天")
elif month in [4, 6, 9, 11]:
print("这是小月,有30天")
elif month == 2:
print("这是2月,有28或29天")
else:
print("请输入合法的月份!")
```
4. 统计随机生成的1000个整数出现次数的代码如下:
```python
import random
nums = [random.randint(1, 100) for _ in range(1000)]
count_dict = {}
for n in nums:
if n in count_dict:
count_dict[n] += 1
else:
count_dict[n] = 1
for k, v in count_dict.items():
print("{}出现了{}次".format(k, v))
```
阅读全文