任务:使用random.randint()随机选择两个类型语句之一,然后使用random.choice()打印其内容。
我写了这段代码:
import random
i = 0
ii = 0
line1 = ''
articles = ['the', 'a', 'an']
nouns = ['cat', 'dog', 'man', 'woman']
verbs = ['sang', 'run', 'jumped']
adverb = ['loudly', 'quietly', 'well', 'badly']
structure1 = [articles, nouns, verbs, adverb]
structure2 = [articles, nouns, verbs]
while i < 5:
if random.randint(1,2) == 1:
c = len(structure1)
while ii < c:
line1 += str(random.choice(structure1[ii])) + ' '
ii += 1
print (line1)
else:
c = len(structure2)
while ii < c:
line1 += str(random.choice(structure2[ii])) + ' '
ii += 1
print (line1)
i += 1;
可以。没问题。
但是我认为这段代码太复杂了。 您能帮我使这段代码更简单吗?
答案 0 :(得分:0)
是的,看起来您的代码有点复杂。您可以通过以下方法进行改进:
app.get('/getFile', (req, res) => {
const {email, courseid, filename} = req.query;
console.log(email);
console.log(courseid);
console.log(filename);
var filePath = `${__dirname}`+'/uploads/'+`${filename}`;
fs.readFile(filePath , function (err,data){
console.log(data);
res.contentType("application/pdf");
res.send(data);
});
});
我包含了两个函数import random
articles = ['the', 'a', 'an']
nouns = ['cat', 'dog', 'man', 'woman']
verbs = ['sang', 'run', 'jumped']
adverb = ['loudly', 'quietly', 'well', 'badly', '']
structure1 = [articles, nouns, verbs, adverb]
def generate_sentence_pythonic():
return ' '.join([random.choice(obj) for obj in structure1])
def generate_sentence():
res = []
for obj in structure1:
res.append(random.choice(obj))
return ' '.join(res)
# Number of sentences you want to generate
n = 1
for i in range(n):
print(generate_sentence())
print(generate_sentence_pythonic())
和generate_sentence_pythonic
来生成句子。
答案 1 :(得分:0)
您可以将structure1
和structure2
之间的随机选择映射到random.choice
:
for _ in range(5):
print(' '.join(map(random.choice, random.choice((structure1, structure2)))))
示例输出:
the man run
a woman sang badly
the woman jumped loudly
the woman jumped quietly
the cat run loudly