how to use random function in python?

时间:2017-12-18 06:28:24

标签: python random tic-tac-toe

#program to tic-tac-toe
from random import *
num=[i for i in range(1,10)]
flag=0
ulist=list();
xlist=list();
olist=list();
count=0
while(count < 9):
  if(flag==0):
    x=random.choice(num)
    if(x not in ulist):
      ulist.append(x)
      xlist.append(x)
      flag=1
  if(flag==1):
    o=random.choice(num)
    if(o not in ulist):
        ulist.append(o)
        olist.append(o)
        flag=0
  count+=1

print (ulist)
print (xlist)
print (olist)

this is my code i have called for the random function but still its saying i did not use the random function

2 个答案:

答案 0 :(得分:0)

Correct usage of random function:

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2

答案 1 :(得分:0)

   <?php
$array=array(
array("no"=>"1","subtitle"=>"Perbekalan", "title"=>"lombok ijo"),
array("no"=>"11","subtitle"=>"Perbekalan", "title"=>"lombok asdf"),
array("no"=>"2","subtitle"=>"Perbekalan", "title"=>"bawang abang"),
array("no"=>"3","subtitle"=>"Inventaris", "title"=>"Wajan")
);
echo "<pre>";
//print_r($array);
$Perbekalan=array();
$Inventaris=array();
$i=0;
foreach ($array as $value) {
    if($value['subtitle']=="Perbekalan")
    {
        $Perbekalan[$i]['no']=$value['no'];
        $Perbekalan[$i]['subtitle']=$value['subtitle'];
        $Perbekalan[$i]['title']=$value['title'];
    }
    if($value['subtitle']=="Inventaris")
    {
        $Inventaris[$i]['no']=$value['no'];
        $Inventaris[$i]['subtitle']=$value['subtitle'];
        $Inventaris[$i]['title']=$value['title'];
    }
    $i++;

}
echo "per";
print_r($Perbekalan);
echo "ins";
print_r($Inventaris);
?>

isn't compatible with

from random import *

Either do

random.choice()

or

import random
...
random.choice()