Найти - Пользователи
Полная версия: вернуть случайное число из списка но с условием
Начало » Python для новичков » вернуть случайное число из списка но с условием
1
vrabey
как написать функцию которая будет бесконечно выдавать случайное число из заданного диапазона,
но с условием следующее число != предыдущему
решил вот так:
import random
class A:
    l = range(1,5)
    pre = None
    def randiter(self):
       x = random.choice(self.l)
       if not self.pre is None:
           self.l.append(self.pre)
       self.l.remove(x)
       self.pre = x
       return x
x = A()
rep = None
while not rep == "q":
    w = x.randiter()
    print w
    rep = raw_input()
но мне не нравитсякак то для такой задачи громоздко,хоть и работает)
помогите решить по другому
o7412369815963
from random import randint
from time import sleep
def myrand(a, b):
    prev = -1
    while True:
        x = randint(a, b+1)
        if x == prev:
            continue
        prev = x
        yield x
for i in myrand(1, 5):
    print(i)
    sleep(0.2)
vrabey
спасибо за ответ пришось перечитывать про генераторы

py.user.next
>>> def g(a, b):
...     assert a < b
...     j = a - 1
...     while True:
...         i = random.randint(a, b)
...         if i != j:
...             yield i
...             j = i
... 
>>> gen = g(-3, -1)
>>> next(gen)
-3
>>> next(gen)
-2
>>> next(gen)
-3
>>> next(gen)
-2
>>> next(gen)
-3
>>> next(gen)
-2
>>> next(gen)
-3
>>> next(gen)
-1
>>> next(gen)
-3
>>>
sp3
import random
def unicRand(a,b):
    lst = range(a,b)
    random.shuffle(lst)
    for x in lst:
        yield x
for x in unicRand(1,5):
    print x

upd: условия из #0 не дочитал :(
py.user.next
random.shuffle() не подходит, потому что элементы вообще должны повторяться, а с random.shuffle() можно вычислить, что среди следующих не будет пройденных

да и диапазон у тебя не от 1 до 5, а от 1 до 4 получится, так как range(), в отличие от random.randint(), не учтёт 5
FishHook
#-*- coding:utf-8 -*-
import random
def foo(start, stop):
   z = start
   lst = range(start, stop)
   while True:
       i = lst.index(z)
       z = random.choice(lst[:i] + lst[i + 1:])
       yield z
for i in foo(1, 5):
   print i
   raw_input("")
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB