For the Python’il USE per hundred square meters or why Python will help on the USE

All comers – I invite you below!

Fast transfer from system to system

Python has interesting features bin(), oct() and hex()… These functions work very simply:

bin(156) #Выводит '0b10011100'
oct(156) #Выводит '0o234'
hex(156) #Выводит '0x9c'
Inference in interpretive mode
Inference in interpretive mode

As you can see, a string is displayed, where 0b means that the number is further in the binary system, 0o in octal, and 0x in hexadecimal. But these are standard systems, and there are also unusual ones …

Let’s take a look at them too:

n = int(input()) #Вводим целое число
 
b = '' #Формируем пустую строку
 
while n > 0: #Пока число не ноль
    b = str(n % 2) + b #Остатот от деления нужной системы (в нашем сл записываем слева
    n = n // 2 #Целочисленное деление
 
print(b) #Вывод

This program will work when translating from the decimal number system to any number up to 9, since we do not have letters. Let’s add letters:

n = int(input()) #Вводим целое число

b = '' #Формируем пустую строку

while n > 0: #Пока число не ноль
	if (n % 21) > 9: #Если остаток от деления больше 9...
		if n % 21 == 10: #... и равен 10...
			b = 'A' + b #... запишем слева A
		elif n % 21 == 11:#... и равен 11...
			b = 'B' + b#... запишем слева B

'''

И так далее, пока не дойдём до системы счисления -1 (я переводил в 21-ную систему и шёл до 20)

'''

		elif n % 21 == 11:
			b = 'B' + b
		elif n % 21 == 12:
			b = 'C' + b
		elif n % 21 == 13:
			b = 'D' + b
		elif n % 21 == 14:
			b = 'E' + b
		elif n % 21 == 15:
			b = 'F' + b
		elif n % 21 == 16:
			b = 'G' + b
		elif n % 21 == 17:
			b = 'H' + b
		elif n % 21 == 18:
			b = 'I' + b
		elif n % 21 == 19:
			b = 'J' + b
		elif n % 21 == 20:
			b = 'K' + b
	else: #Иначе (остаток меньше 10)
		b = str(n % 21) + b #Остатот от деления записываем слева
	n = n // 21 #Целочисленное деление

print(b) #Вывод

The method is voluminous, but understandable. Now let’s use the same translation function from any number system to any one:

def convert_base(num, to_base=10, from_base=10):
    # Перевод в десятичную систему
    if isinstance(num, str): # Если число - строка, то ...
        n = int(num, from_base) # ... переводим его в нужную систему счисления
    else: # Если же ввели число, то ...
        n = int(num) # ... просто воспринять его как число
    # Перевод десятичной в 'to_base' систему
    alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Берём алфавит
    if n < to_base: # Если число меньше системы счисления в которую переводить...
        return alphabet[n] # ... вернуть значения номера в алфавите (остаток от деления)
    else: # Иначе...
        return convert_base(n // to_base, to_base) + alphabet[n % to_base] # ... рекурсивно обратиться к функии нахождения остатка

By calling the output function print(convert_base(156, 16, 10)) we will translate 156 from 10 to 16 in the number system, and by entering print(convert_base('23', 21, 4)) will translate 23 from 4-ary to 21-ary system (Answer: B).

Problem 2

I take all tasks from the first October version (aka version number 9325894) from the site I will solve the exam

The solution to this problem is quite simple: a trivial brute force.

print('y', 'x', 'z', 'F') #Напечатаем заголовки таблицы
for y in range(2): #Берём все переменные и меняем их в циклах '0' и '1'
	for x in range(2):
		for z in range(2):
			for w in range(2):
				F = ((not x or y) == (not z or w)) or (x and w) #Записываем функцию
				print(x, y, z, F) #Выводим результат

Result:

The whole truth table was displayed for us (1 = True, 0 = False). But this is not very convenient. Note that in the assignment, the function is 0, so let’s correct the code:

print('y', 'x', 'z', 'F') #Напечатаем заголовки таблицы
for y in range(2): #Берём все переменные и меняем их в циклах '0' и '1'
	for x in range(2):
		for z in range(2):
			for w in range(2):
				F = ((not x or y) == (not z or w)) or (x and w) #Записываем функцию
				if not F:
					print(x, y, z, F) #Выводим результат

Result:

Next is a simple analysis.

Problem 5

This task is easily solved by a simple sequence of actions in the interpretation mode:

Problem 6

Reprinted and got the answer:

s = 0
k = 1
while s < 66:
    k += 3
    s += k
print(k)

Assignment 12

Once again, let’s just replace the words with the code:

a="9" * 1000

while '999' in a or '888' in a:
	if '888' in a:
		a = a.replace('888', '9', 1)
	else:
		a = a.replace('999', '8', 1)
print(a)

Assignment 14

The computer is iron, it will calculate everything:

a = 4 ** 2020 + 2 ** 2017 - 15
k = 0

while a > 0:
    if a % 2 == 1:
    	k += 1
    a = a // 2

print(k)

Assignment 16

Again, just duplicate the program in python:

def F(n):
    if n > 0:
        F(n // 4)
        print(n)
        F (n - 1)
print(F(5))

Result:

Assignment 17

Task with file… The hardest part is getting the data out of the file. But where didn’t ours disappear ?!

with open("17.txt", "r") as f: #Открыли файл 17.txt для чтения
    text = f.read() #В переменную text запихнули строку целиком
a = text.split("n") #Разбили строку энтерами (n - знак перехода на новую строку)

k = 0 #Стандартно обнуляем количество
m = -20001 #Так как у нас сумма 2-ух чисел и минимальное равно -10000, то минимум по условию равен -20000, поэтому...

for i in range(len(a)): #Обходим все элементы массива
	if (int(a[i - 1]) % 3 == 0) or (int(a[i]) % 3 == 0): #Условное условие
		k += 1 #Счётчик
		if int(a[i - 1]) + int(a[i]) > m: #Нахождение минимума
			m = int(a[i - 1]) + int(a[i])

print(k, m) #Вывод

Few explanations. The with () function opens the file, reads the data using the read () function, and closes the file. Otherwise, the task is standard.

Problem 19, 20 and 21

All three tasks are recursive tasks. The tasks are identical, but the questions are different. So the first task:

We write a recursive function and an iteration loop S:

def f(x, y, p): #Рекурсивная функция
	if x + y >= 69 or p > 3: #Условия завершения игры
		return p == 3
	return f(x + 1, y, p + 1) or f(x, y + 1, p + 1) or
		   f(x * 2, y, p + 1) or f(x, y * 3, p + 1) #Варианты действий

for s in range (1, 58 + 1): #Перебор S
	if f(10, s, 1): #Начали с 10 камней
		print(s)
		break

Few explanations. There are 3 variables in the recursive function x – the number of stones in the first heap, y – the number of stones in the second heap, p – position. The position is calculated according to the table:

The game

Peter

Vania

Peter

Vania

Peter

p

1

2

3

4

5

6

Further – everything according to the condition of the problem.

The second problem on game theory:

All the differences are in the frame. Well, the code, respectively, is not very different:

def f(x, y, p): #Рекурсивная функция
	if x + y >= 69 or p > 4: #Условия завершения игры
		return p == 4
	if p % 2 != 0:
		return f(x + 1, y, p + 1) or f(x, y + 1, p + 1) or
			   f(x * 2, y, p + 1) or f(x, y * 3, p + 1) #Варианты действий
	else:
		return f(x + 1, y, p + 1) and f(x, y + 1, p + 1) and
			   f(x * 2, y, p + 1) and f(x, y * 3, p + 1) #Варианты действий


for s in range (1, 58 + 1): #Перебор S
	if f(10, s, 1): #Начали с 10 камней
		print(s)

Differences:

  1. Petya won, respectively, position 4

  2. Since Petya cannot win in one move – he wins in 2 moves (and, not or in odd positions (Petya’s games))

  3. We removed break, since we need all the S’s, not the only one

The last variation of the problem:

Immediately the code:

def f(x, y, p): #Рекурсивная функция
	if x + y >= 69 or p > 5: #Условия завершения игры
		return p == 3 or p == 5
	if p % 2 == 0:
		return f(x + 1, y, p + 1) or f(x, y + 1, p + 1) or
			   f(x * 2, y, p + 1) or f(x, y * 3, p + 1) #Варианты действий
	else:
		return f(x + 1, y, p + 1) and f(x, y + 1, p + 1) and
			   f(x * 2, y, p + 1) and f(x, y * 3, p + 1) #Варианты действий


for s in range (1, 58 + 1): #Перебор S
	if f(10, s, 1): #Начали с 10 камней
		print(s)

Well, there are only 2 differences:

  1. Positions 3 or 5, not 4, since Vanya won

  2. On the second move Vanya wins and we need to change or and and. I only replaced the multiplicity of 2.

Assignment 22

Ctrl + C, Ctrl + V – our everything! 🙂

for i in range(1, 100000):
	x = i
	L = 0
	M = 0
	while x > 0 :
		L = L+1
		if (x % 2) != 0:
			M = M + x % 8
		x = x // 8
	if L == 3 and M == 6:
		print(i)

Assignment 23

So the code is:

def f(x, y):
	if x > y: #Перегнали цель
		return 0
	if x == y:  #Догнали цель
		return 1
	if x < y: #Догоняем цель тремя методами
		return f(x + 1, y) + f(x + 2, y) + f(x * 2, y)

print(f(3, 10) * f(10, 12)) #Прошло через 10, значит догнали 10 и от де догоняем 12

Since in the problem statement we increase the number, but we will “catch up” with the numbers. Three methods are described, but to go through 10 means to reach it and go from it.

Actually, this is the entire first part of the exam in computer science, solved in Python.

Link to the repository with all programs:

I hope I was able to help graduates and those who are preparing in my article;)

There is only one question left – is it necessary to analyze the second part of the exam in computer science in Python? I’ll leave this question to your vote.

Good luck to all!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *