Lucas Lucas - 1 year ago 93
HTML Question

Python/Flask/HTML and random random length variables output


Code I have below does two things I wanted to achieve:

1)Produces random lenght output from randomly choosen, previously defined list of variables and shows it in html.

for instance (output):

apple orange


apple orange orange

I do not want however for fruits to repeat in produced output, keeping everything else as it is.

So I want to prohibit

"apple orange orange"

from happening

How can it be achieved?

Code below:

from flask import Flask, render_template
import os
import random

app = Flask(__name__)


def main():
z=randint(1, 4)
fruits = [Hash1, Hash2,Hash3, Hash4]
a=[choice(fruits) for x in range(z)]

return render_template ('show.html', a=a)

if __name__ == '__main__':'IP', ''),port=int(os.getenv('PORT', 8080)))






<h2>your fruits are {{ a }} </h2>



Answer Source

random.choice can return an item that has already been selected before. To return unique samples, use random.sample:

z = random.randint(1, len(fruits))
a = random.sample(fruits, z)
return render_template('show.html', a=a)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download