Форум сайта python.su
Здравствуйте, программисты! Пожалуйста, помогите перевести решение с Paskal на Python
Условие задачи:
Решение на Паскале:
Program Game;
type
playtype = ‘0’..'9';
seedtype = 0..65535;
scoretype = 0..4;
var
pool, target: set of playtype;
a, b, c, d: playtype;
seed: seedtype;
bulls, cows: scoretype;
function random: real;
begin
random := seed / 65536;
seed := (25173 * seed + 13849) mod 65536;
end;
function unique: playtype;
var ch: char;
begin
repeat
ch := chr(trunc(10 * random) + ord('0'));
until ch in pool;
unique := ch;
pool := pool - ;
target := target + ;
end;
procedure try(thisone: char);
var ch: char;
begin
read(ch);
if ch in target then
if ch = thisone then
bulls := succ(bulls)
else
cows := succ(cows)
end;
begin
write('Загадайте случайное число, ‘);
writeln(’затем отгадывайте');
readln(seed);
pool := ;
target := ;
a := unique; b := unique; c := unique; d := unique;
repeat
bulls := 0; cows := 0;
try(a); try(b); try©; try(d);
writeln('Быков: ‘, bulls:1, ’; коров: ', cows:1);
readln
until bulls = 4;
readln
end.
Отредактировано Casha (Фев. 9, 2015 17:23:07)
Офлайн
Проверки на корректность ввода и оптимизацию оставим на вашей совести.
from random import sample number = map(str, sample(range(10), 4)) bulls = 0 print 'Komp zagadal chislo...' while bulls != 4: hypothesis = raw_input('Vy schitaete, chto eto chislo: ') bulls = sum([number[i] == hypothesis[i] for i in range(len(number))]) cows = sum([hypothesis[i] in number and hypothesis[i] != number[i] for i in range(len(number))]) print 'bulls = {}; cows = {}'.format(bulls, cows) print 'We are the champions!'
Офлайн
botinag
1. если в двух строках одинакоывый цикл - стоит задуматся
2. зачем len(number) если явно указано в sample(range(10), 4) что всегда только 4 знака?
from random import sample number = map(str, sample(range(10), 4)) bulls = 0 print 'Komp zagadal chislo...' while bulls != 4: bulls = cows = 0 hypothesis = raw_input('Vy schitaete, chto eto chislo: ') for i in xrange(4): if number[i] == hypothesis[i]: bulls += 1 elif hypothesis[i] in number: cows += 1 print 'bulls = {}; cows = {}'.format(bulls, cows) print 'We are the champions!'
Офлайн
terabaytnumber = map(str, sample(range(10), 4))
def game(size=4, chars='0123456789'): ...
Vy schitaete, chto eto chislo: 2100 bulls = 2; cows = 0 Vy schitaete, chto eto chislo: 219 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 9, in f IndexError: string index out of range >>>
Отредактировано py.user.next (Фев. 10, 2015 02:49:38)
Офлайн
py.user.nextну можно так
играл-играл
hypothesis = "%04d" % input('Vy schitaete, chto eto chislo: ')
Офлайн