import random nums = random.sample(range(1, 10), 4) while True: if len(nums) == len(set(nums)): break nums = random.sample(range(1, 10), 4) print(''.join(map(str, nums)))怎末输不出
时间: 2024-03-02 21:53:02 浏览: 129
你的代码中,print语句应该在while循环外面,而不是在循环里面。因为你想要输出的是符合条件的数字,而不是每次随机生成的数字。以下是修改后的代码:
```python
import random
nums = random.sample(range(1, 10), 4)
while True:
if len(nums) == len(set(nums)):
break
print(''.join(map(str, nums)))
```
这样修改之后,程序会在生成符合条件的数字之后输出。注意要确保程序能够生成符合条件的数字,否则程序会一直运行下去。
相关问题
import random import openpyxl wb = openpyxl.Workbook() sheet = wb.active def generate_combinations(nums, n): result = [] for i in range(1, n+1): for c in itertools.combinations(nums, i): if sorted(list(c)) not in result: result.append(sorted(list(c))) return result def generate_group(nums): group = [] while True: n = random.randint(1, 5) if len(nums) < n: break c = random.sample(nums, n) if sorted(c) not in group: group.append(sorted(c)) for num in c: nums.remove(num) return group nums = [188, 30, 200, 500, 900] combinations = generate_combinations(nums, 5) for i, c in enumerate(combinations): group = generate_group(list(c)) sum = 0 for g in group: sum += sum(g) sheet.cell(row=i+1, column=1, value=sum) wb.save("C:\Users\莫\Desktop\1.xlsx")使用这个代码时出现Traceback (most recent call last): File "E:\vippython\清洗工具\python combo_sum.py", line 36, in <module> sum += sum(g) TypeError: 'int' object is not callable,请将更正后的代码完整发出来
抱歉,由于涉及到编程问题,我可以回答你的问题。下面是更正后的代码:
import random
import openpyxl
import itertools
wb = openpyxl.Workbook()
sheet = wb.active
def generate_combinations(nums, n):
result = []
for i in range(1, n + 1):
for c in itertools.combinations(nums, i):
if sorted(list(c)) not in result:
result.append(sorted(list(c)))
return result
def generate_group(nums):
group = []
while True:
n = random.randint(1, 5)
if len(nums) < n:
break
c = random.sample(nums, n)
if sorted(c) not in group:
group.append(sorted(c))
for num in c:
nums.remove(num)
return group
nums = [188, 30, 200, 500, 900]
combinations = generate_combinations(nums, 5)
for i, c in enumerate(combinations):
group = generate_group(list(c))
sum_value = 0
for g in group:
sum_value += sum(g)
sheet.cell(row=i+1, column=1, value=sum_value)
wb.save("C:\Users\莫\Desktop\1.xlsx")
import random import string count = 0 while count < 3: car_nums = [] for i in range(20): n1 = random.choice(string.ascii_uppercase) #生成车牌号第一个字母 n2 ="".join(random.sample(string.ascii_uppercase+string.digits,5)) c_num =f"京{n1}-{n2}" car_nums.append(c_num) #把生成的号码添加到列表 print(i+1,c_num) choice = input("输入你喜欢的号:").strip() if choice in car_nums: #代表车牌是合法的 print(f"恭喜你选择了新车牌号:{choice}") exit("Good_luck") else: print("输入不合法.......") count += 1
这段代码的作用是随机生成由20个元素组成的字符串,其中每个元素是大写字母或数字。count是计数器,如果小于3则一直执行循环,car_nums是存储随机生成字符串的列表。在循环中,每次我们使用random.choice函数从string.ascii_uppercase中随机选取一个大写字母作为元素加入到生成的字符串中,最终生成包含20个元素的字符串。
阅读全文