{ "question_id": 827445, "question_title": "循环随机取数组直到得出指定数字?", "question_content": "举个例子:\n随机数字范围:0~100\n每组数字量:6(s1,s2,s3,s4,s5,s6)\n第二轮开始随机数字范围:新s1和新s2取值为旧s1和s2之间,新s3和新s4取值为旧s3和s4之间,新s5和新s6取值为旧s5和s6之间。\n跳出循环条件:任意数字=37\n如因s1=s2!=37&&s3=s4!=37&&s5=s6!=37使数组进入无意义无限循环,则重新取0~100六个数字并开始如上述第二轮随机的随机取值。", "difficulty": "简单", "answer_id": 924449, "answer_content": "\n```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport random\n\ndef random_test():\n # 初始化一个列表,随机0-100的6个数字\n rst_list = [random.randint(0,100) for i in range(0, 6)]\n print(rst_list)\n while 1:\n # 新建临时数据,用来存储rst_list按规则处理后的数据\n temp = []\n for k,v in enumerate(rst_list):\n if k%2==0:\n temp.append(random.randint(min([rst_list[k],rst_list[k+1]]),max([rst_list[k],rst_list[k+1]])))\n else:\n temp.append(random.randint(min(rst_list[k-1], rst_list[k]),max(rst_list[k-1], rst_list[k])))\n # 将结果temp列表,写入结果列表 rst_list\n rst_list = temp\n print(rst_list)\n # 判断37在结果列表中,则返回结果列表 rst_list\n if 37 in rst_list:\n print('rst_list:',rst_list)\n return rst_list\n else:\n # 37没在列表中,则按要求判断死循环情况(需求里的 s1=s2!=37&s3=s4!=37&s5=s6!=37 )\n # 如果进入死循环,则重新初始化结果列表 rst_list\n if rst_list[0]==rst_list[1] and rst_list[2]==rst_list[3] and rst_list[4]==rst_list[5]:\n rst_list = [random.randint(0, 100) for i in range(0, 6)]\n\ndef main():\n random_test()\n\n\nif __name__ == '__main__':\n main()\n\n```\n\n\n根据需求描述,按照最简单和容易理解的方式,逐步实现需求。注释和打印较多,实际代码篇幅并不多", "tag_name": "python", "python": "import random\ndef random_test():\n\trst_list = [random.randint(0,100) for i in range(0, 6)]\n\tprint(rst_list)\n\twhile 1:\n\t\ttemp = []\n\t\tfor k,v in enumerate(rst_list):\n\t\t\tif k%2==0:\n\t\t\t\ttemp.append(random.randint(min([rst_list[k],rst_list[k+1]]),max([rst_list[k],rst_list[k+1]])))\n\t\t\telse:\n\t\t\t\ttemp.append(random.randint(min(rst_list[k-1], rst_list[k]),max(rst_list[k-1], rst_list[k])))\n\t\trst_list = temp\n\t\tprint(rst_list)\n\t\tif 37 in rst_list:\n\t\t\tprint('rst_list:',rst_list)\n\t\t\treturn rst_list\n\t\telse:\n\t\t\tif rst_list[0]==rst_list[1] and rst_list[2]==rst_list[3] and rst_list[4]==rst_list[5]:\n\t\t\t\trst_list = [random.randint(0, 100) for i in range(0, 6)]\ndef main():\n\trandom_test()\nif __name__ == '__main__':\n\tmain()", "topic_link": "https://bbs.csdn.net/topics/600469992", "status": 1, "keywords": "算法初阶,基础知识,随机算法,概率分析和随机算法", "license": "csdn.net", "notebook": { "python": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/answer/ipynb/python/45.ipynb?type=file" }, "notebook_enable": 1 }