Download presentation
Presentation is loading. Please wait.
1
Snakify Theory, Questions
and Model Answers Taken from
2
Index Input, Print and Numbers Conditions: if, then, else
Integer and Float numbers For loop with range Strings While Loop Lists Functions and Recursion Two-dimensional lists (arrays) Dictionaries
3
Input, Print and Numbers
7
Statement a = int(input()) b = int(input()) c = int(input())
Write a program that takes three numbers and prints their sum. Every number is given on a separate line. a = int(input()) b = int(input()) c = int(input()) print(a + b + c)
8
Statement a = int(input()) b = int(input()) print(a * b / 2)
Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. Every number is given on a separate line. a = int(input()) b = int(input()) print(a * b / 2)
9
Statement n = int(input()) k = int(input()) print(k // n) print(k % n)
N students take K apples and distribute them among each other evenly. The remaining (the undivisible) part remains in the basket. How many apples will each single student get? How many apples will remain in the basket? The program reads the numbers N and K. It should print the two answers for the questions above. n = int(input()) k = int(input()) print(k // n) print(k % n)
10
Statement n = int(input()) hours = n // 60 minutes = n % 60
Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock? The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59). For example, if N = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So the program should print 2 30. n = int(input()) hours = n // 60 minutes = n % 60 print(hours, minutes)
11
print('Hello, ' + input() + '!')
Statement Write a program that greets the user by printing the word "Hello", a comma, the name of the user and an exclamation mark after it. See the examples below. Warning. Your program's output should strictly match the desired one, character by character. There shouldn't be any space between the name and the exclamation mark. You can use + operator to concatenate two strings. See the lesson for details. print('Hello, ' + input() + '!')
12
Statement n = int(input())
Write a program that reads an integer number and prints its previous and next numbers. See the examples below. Remember that you can convert the numbers to strings using the function str. n = int(input()) print('The next number for the number ' + str(n) + ' is ' + str(n + 1) + '.') print('The previous number for the number ' + str(n) + ' is ' + str(n - 1) + '.')
13
print(a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2)
Statement A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest possible number of desks that can be purchased. The program should read three integers: the number of students in each of the three classes, a, b and c respectively. In the first test there are three groups. The first group has 20 students and thus needs 10 desks. The second group has 21 students, so they can get by with no fewer than 11 desks. 11 desks is also enough for the third group of 22 students. So we need 32 desks in total. a = int(input()) b = int(input()) c = int(input()) print(a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2)
14
Conditions: if, then, else
22
Statement a=int(input()) b=int(input()) if a<b: print(a) else:
Given the two integers, print the least of them. a=int(input()) b=int(input()) if a<b: print(a) else: print(b)
23
Statement x = int(input()) if x > 0: print(1) elif x == 0: print(0)
For the given integer X print 1 if it's positive, -1 if it's negative, or 0 if it's equal to zero. Try to use the cascade if-elif-else for it. x = int(input()) if x > 0: print(1) elif x == 0: print(0) else: print(-1)
24
Statement a = int(input()) b = int(input()) c = int(input())
Given the three integers, print the least of them. a = int(input()) b = int(input()) c = int(input()) if b >= a <= c: print(a) elif a >= b <= c: print(b) else: print(c)
25
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON. The rules in Gregorian calendar are as follows: • a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100 • a year is always a leap year if its number is exactly divisible by 400 Warning. The words LEAP and COMMON should be printed all caps. year = int(input()) if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): print('LEAP') else: print('COMMON')
26
elif a == b or b == c or a == c: print(2) else: print(0)
Statement Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third is different) or 0 (if all numbers are different). a = int(input()) b = int(input()) c = int(input()) if a == b == c: print(3) elif a == b or b == c or a == c: print(2) else: print(0)
27
Statement x1 = int(input()) y1 = int(input()) x2 = int(input())
Chess rook moves horizontally or vertically. Given two different cells of the chessboard, determine whether a rook can go from the first cell to the second in one move. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. The program should output YES if a rook can go from the first cell to the second in one move, or NO otherwise. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if x1 == x2 or y1 == y2: print('YES') else: print('NO')
28
Statement x1 = int(input()) y1 = int(input()) x2 = int(input())
Given two cells of a chessboard. If they are painted in one color, print the word YES, and if in a different color - NO. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if (x1 + y1 + x2 + y2) % 2 == 0: print('YES') else: print('NO')
29
if abs(x1 - x2) <= 1 and abs(y1 - y2) <= 1: print('YES') else:
Statement Chess king moves horizontally, vertically or diagonally to any adjacent cell. Given two different cells of the chessboard, determine whether a king can go from the first cell to the second in one move. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. The program should output YES if a king can go from the first cell to the second in one move, or NO otherwise. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if abs(x1 - x2) <= 1 and abs(y1 - y2) <= 1: print('YES') else: print('NO')
30
if abs(x1 - x2) == abs(y1 - y2): print('YES') else: print('NO')
Statement In chess, the bishop moves diagonally, any number of squares. Given two different squares of the chessboard, determine whether a bishop can go from the first to the second in one move. The program receives as input four numbers from 1 to 8, specifying the column and row numbers of the starting square and the column and row numbers of the ending square. The program should output YES if a Bishop can go from the first square to the second in one move, or NO otherwise. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if abs(x1 - x2) == abs(y1 - y2): print('YES') else: print('NO')
31
if abs(x1 - x2) == abs(y1 - y2) or x1 == x2 or y1 == y2: print('YES')
Statement Chess queen moves horizontally, vertically or diagonally to any number of cells. Given two different cells of the chessboard, determine whether a queen can go from the first cell to the second in one move. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. The program should output YES if a queen can go from the first cell to the second in one move, or NO otherwise. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if abs(x1 - x2) == abs(y1 - y2) or x1 == x2 or y1 == y2: print('YES') else: print('NO')
32
if dx == 1 and dy == 2 or dx == 2 and dy == 1: print('YES') else:
Statement Chess knight moves like the letter L. It can move two cells horizontally and one cell vertically, or two cells vertically and one cells horizontally. Given two different cells of the chessboard, determine whether a knight can go from the first cell to the second in one move. The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the last two - for the second cell. The program should output YES if a knight can go from the first cell to the second in one move, or NO otherwise. x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) dx = abs(x1 - x2) dy = abs(y1 - y2) if dx == 1 and dy == 2 or dx == 2 and dy == 1: print('YES') else: print('NO')
33
if k < n * m and ((k % n == 0) or (k % m == 0)): print('YES') else:
Statement Chocolate bar has the form of a rectangle divided into n×m portions. Chocolate bar can be split into two rectangular parts by breaking it along a selected straight line on its pattern. Determine whether it is possible to split it so that one of the parts will have exactly k squares. The program reads three integers: n, m, and k. It should print YES or NO. n = int(input()) m = int(input()) k = int(input()) if k < n * m and ((k % n == 0) or (k % m == 0)): print('YES') else: print('NO')
34
Integer and Float numbers
41
Statement a = int(input()) print(a % 10)
Given an integer number, print its last digit. a = int(input()) print(a % 10)
42
Statement x = float(input()) print(x - int(x))
Given a positive real number, print its fractional part. x = float(input()) print(x - int(x))
43
Statement x = float(input()) print(int(x * 10) % 10)
Given a positive real number, print its first digit to the right of the decimal point. x = float(input()) print(int(x * 10) % 10)
44
Statement from math import ceil n = int(input()) m = int(input())
A car can cover distance of N kilometers per day. How many days will it take to cover a route of length M kilometers? The program gets two numbers: N and M. from math import ceil n = int(input()) m = int(input()) print(ceil(m / n))
45
Statement a = int(input()) b = int(input()) n = int(input())
A cupcake costs A dollars and B cents. Determine, how many dollars and cents should one pay for N cupcakes. A program gets three numbers: A, B, N. It should print two numbers: total cost in dollars and cents. a = int(input()) b = int(input()) n = int(input()) cost = n * (100 * a + b) print(cost // 100, cost % 100)
46
Statement n = int(input()) print(n // 10 % 10)
Given an integer. Print its tens digit. n = int(input()) print(n // 10 % 10)
47
Statement n = int(input()) a = n // 100 b = n // 10 % 10 c = n % 10
Given a three-digit number. Find the sum of its digits. n = int(input()) a = n // 100 b = n // 10 % 10 c = n % 10 print(a + b + c)
48
Statement h = int(input()) m = int(input()) s = int(input())
H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60). Determine the angle (in degrees) of the hour hand on the clock face right now. h = int(input()) m = int(input()) s = int(input()) print(h * 30 + m * 30 / 60 + s * 30 / 3600)
49
alpha = float(input()) print(alpha % 30 * 12)
Statement Hour hand turned by α degrees since the midnight. Determine the angle by which minute hand turned since the start of the current hour. Input and output in this problems are floating-point numbers. alpha = float(input()) print(alpha % 30 * 12)
50
For loop with range
55
Statement a = int(input()) b = int(input()) for i in range(a, b + 1):
Given two integers A and B (A ≤ B). Print all numbers from A to B inclusively. a = int(input()) b = int(input()) for i in range(a, b + 1): print(i)
56
Statement a = int(input()) b = int(input()) if a < b:
Given two integers A and B. Print all numbers from A to B inclusively, in increasing order, if A < B, or in decreasing order, if A ≥ B. a = int(input()) b = int(input()) if a < b: for i in range(a, b + 1): print(i) else: for i in range(a, b - 1, -1):
57
Statement res = 0 for i in range(10): res += int(input()) print(res)
10 numbers are given in the input. Read them and print their sum. Use as few variables as you can. res = 0 for i in range(10): res += int(input()) print(res)
58
Statement n = int(input()) res = 0 for i in range(n):
N numbers are given in the input. Read them and print their sum. The first line of input contains the integer N, which is the number of integers to follow. Each of the next N lines contains one integer. Print the sum of these N integers. n = int(input()) res = 0 for i in range(n): res += int(input()) print(res)
59
for i in range(1, int(input()) + 1): res += i ** 3 print(res)
Statement For the given integer N calculate the following sum: res = 0 for i in range(1, int(input()) + 1): res += i ** 3 print(res)
60
Statement res = 1 n = int(input()) for i in range(1, n + 1): res *= i
In mathematics, the factorial of an integer n, denoted by n! is the following product: For the given integer n, calculate the value n!. Don’t use math module in this exercise. res = 1 n = int(input()) for i in range(1, n + 1): res *= i print(res)
61
for i in range(int(input())): if int(input()) == 0: num_zeroes += 1
Statement Given N numbers: the first number in the input is N, after that N integers are given. Count the number of zeros among the given integers and print it. You need to count the number of numbers that are equal to zero, not the number of zero digits. num_zeroes = 0 for i in range(int(input())): if int(input()) == 0: num_zeroes += 1 print(num_zeroes)
62
partial_factorial *= i partial_sum += partial_factorial
Statement Given an integer n, print the sum 1!+2!+3!+...+n! This problem has a solution with only one loop, so try to discover it. And don't use the math library :) n = int(input()) partial_factorial = 1 partial_sum = 0 for i in range(1, n + 1): partial_factorial *= i partial_sum += partial_factorial print(partial_sum)
63
# One can prove the following: # sum_cards == n * (n + 1) // 2
Statement There was a set of cards with numbers from 1 to N. One of the card is now lost. Determine the number on that lost card given the numbers for the remaining cards. Given a number N, followed by N − 1 integers - representing the numbers on the remaining cards (distinct integers in the range from 1 to N). Find and print the number on the lost card. n = int(input()) sum_cards = 0 for i in range(1, n + 1): sum_cards += i # One can prove the following: # sum_cards == n * (n + 1) // 2 # However, we'll calculate that using the loop. for i in range(n - 1): sum_cards -= int(input()) print(sum_cards)
64
Statement n = int(input()) for i in range(1, n + 1):
For given integer n ≤ 9 print a ladder of n steps. The k-th step consists of the integers from 1 to k without spaces between them. To do that, you can use the sep and end arguments for the function print(). n = int(input()) for i in range(1, n + 1): for j in range(1, i + 1): print(j, sep='', end='') print()
65
Strings
75
Statement s = input() print(s[2]) print(s[-2]) print(s[:5])
You are given a string. In the first line, print the third character of this string. In the second line, print the second to last character of this string. In the third line, print the first five characters of this string. In the fourth line, print all but the last two characters of this string. In the fifth line, print all the characters of this string with even indices (remember indexing starts at 0, so the characters are displayed starting with the first). In the sixth line, print all the characters of this string with odd indices (i.e. starting with the second character in the string). In the seventh line, print all the characters of the string in reverse order. In the eighth line, print every second character of the string in reverse order, starting from the last one. In the ninth line, print the length of the given string. s = input() print(s[2]) print(s[-2]) print(s[:5]) print(s[:-2]) print(s[::2]) print(s[1::2]) print(s[::-1]) print(s[::-2]) print(len(s))
76
print(input().count(' ') + 1)
Statement Given a string consisting of words separated by spaces. Determine how many words it has. To solve the problem, use the method count. print(input().count(' ') + 1)
77
print(s[(len(s) + 1) // 2:] + s[:(len(s) + 1) // 2])
Statement Given a string. Cut it into two "equal" parts (If the length of the string is odd, place the center character in the first string, so that the first string contains one more characther than the second). Now print a new string on a single row with the first and second halfs interchanged (second half first and the first half second) Don't use the statement if in this task. s = input() print(s[(len(s) + 1) // 2:] + s[:(len(s) + 1) // 2])
78
first_word = s[:s.find(' ')] second_word = s[s.find(' ') + 1:]
Statement Given a string consisting of exactly two words separated by a space. Print a new string with the first and second word positions swapped (the second word is printed first). This task should not use loops and if. s = input() first_word = s[:s.find(' ')] second_word = s[s.find(' ') + 1:] print(second_word + ' ' + first_word)
79
print(s.find('f'), s.rfind('f'))
Statement Given a string that may or may not contain a letter of interest. Print the index location of the first and last appearance of f. If the letter f occurs only once, then output its index. If the letter f does not occur, then do not print anything. Don't use loops in this task. s = input() if s.count('f') == 1: print(s.find('f')) elif s.count('f') >= 2: print(s.find('f'), s.rfind('f'))
80
print(s.find('f', s.find('f') + 1))
Statement Given a string that may or may not contain the letter of interest. Print the index location of the second occurrence of the letter f. If the string contains the letter f only once, then print -1, and if the string does not contain the letter f, then print -2. s = input() if s.count('f') == 1: print(-1) elif s.count('f') < 1: print(-2) else: print(s.find('f', s.find('f') + 1))
81
s = s[:s.find('h')] + s[s.rfind('h') + 1:] print(s)
Statement Given a string in which the letter h occurs at least twice. Remove from that string the first and the last occurrence of the letter h, as well as all the characters between them. s = input() s = s[:s.find('h')] + s[s.rfind('h') + 1:] print(s)
82
b = s[s.find('h'):s.rfind('h') + 1] c = s[s.rfind('h') + 1:]
Statement Given a string in which the letter h occurs at least two times, reverse the sequence of characters enclosed between the first and last appearances. s = input() a = s[:s.find('h')] b = s[s.find('h'):s.rfind('h') + 1] c = s[s.rfind('h') + 1:] s = a + b[::-1] + c print(s)
83
print(input().replace('1', 'one'))
Statement Given a string. Replace in this string all the numbers 1 by the word one. print(input().replace('1', 'one'))
84
print(input().replace('@', ''))
Statement Given a string. Remove from this string all the ''))
85
b = s[s.find('h') + 1:s.rfind('h')] c = s[s.rfind('h'):]
Statement Given a string. Replace every occurrence of the letter h by the letter H, except for the first and the last ones. s = input() a = s[:s.find('h') + 1] b = s[s.find('h') + 1:s.rfind('h')] c = s[s.rfind('h'):] s = a + b.replace('h', 'H') + c print(s)
86
for i in range(len(s)): if i % 3 != 0: t = t + s[i] print(t)
Statement Given a string. Delete from it all the characters whose indices are divisible by 3. s = input() t = '' for i in range(len(s)): if i % 3 != 0: t = t + s[i] print(t)
87
While Loop
97
Statement n = int(input()) i = 1 while i ** 2 <= n: print(i ** 2)
For a given integer N, print all the squares of integer numbers where the square is less than or equal to N, in ascending order. n = int(input()) i = 1 while i ** 2 <= n: print(i ** 2) i += 1
98
Statement n = int(input()) i = 2 while n % i != 0: i += 1 print(i)
Given an integer not less than 2. Print its smallest integer divisor greater than 1. n = int(input()) i = 2 while n % i != 0: i += 1 print(i)
99
while two_in_power <= n: two_in_power *= 2 power += 1
Statement For a given integer N, find the greatest integer x where 2x is less than or equal to N. Print the exponent value and the result of the expression 2x. Don't use the operation **. n = int(input()) two_in_power = 2 power = 1 while two_in_power <= n: two_in_power *= 2 power += 1 print(power - 1, two_in_power // 2)
100
Statement x = int(input()) y = int(input()) i = 1 while x < y:
As a future athlete you just started your practice for an upcoming event. Given that on the first day you run x miles, and by the event you must be able to run y miles. Calculate the number of days required for you to finally reach the required distance for the event, if you increases your distance each day by 10% from the previous day. Print one integer representing the number of days to reach the required distance. x = int(input()) y = int(input()) i = 1 while x < y: x *= 1.1 i += 1 print(i)
101
Statement len = 0 while int(input()) != 0: len += 1 print(len)
Given a sequence of non-negative integers, where each number is written in a separate line. Determine the length of the sequence, where the sequence ends when the integer is equal to 0. Print the length of the sequence (not counting the integer 0). The numbers following the number 0 should be omitted. len = 0 while int(input()) != 0: len += 1 print(len)
102
element = int(input()) while element != 0: sum += element print(sum)
Statement Determine the sum of all elements in the sequence, ending with the number 0. sum = 0 element = int(input()) while element != 0: sum += element print(sum)
103
element = int(input()) while element != 0: sum += element len += 1
Statement Determine the average of all elements of the sequence ending with the number 0. sum = 0 len = 0 element = int(input()) while element != 0: sum += element len += 1 print(sum / len)
104
element = int(input()) if element > max: max = element print(max)
Statement A sequence consists of integer numbers and ends with the number 0. Determine the largest element of the sequence. max = 0 element = -1 while element != 0: element = int(input()) if element > max: max = element print(max)
105
element = int(input()) if element > max: max = element
Statement A sequence consists of integer numbers and ends with the number 0. Determine the index of the largest element of the sequence. If the highest element is not unique, print the index of the first of them. max = 0 index_of_max = -1 element = -1 len = 1 while element != 0: element = int(input()) if element > max: max = element index_of_max = len len += 1 print(index_of_max)
106
element = int(input()) if element % 2 == 0: num_even += 1
Statement Determine the number of even elements in the sequence ending with the number 0. num_even = -1 element = -1 while element != 0: element = int(input()) if element % 2 == 0: num_even += 1 print(num_even)
107
if next != 0 and prev < next: answer += 1 prev = next print(answer)
Statement A sequence consists of integer numbers and ends with the number 0. Determine how many elements of this sequence are greater than their neighbours above. prev = int(input()) answer = 0 while prev != 0: next = int(input()) if next != 0 and prev < next: answer += 1 prev = next print(answer)
108
first_max = int(input()) second_max = int(input())
Statement The sequence consists of distinct positive integer numbers and ends with the number 0. Determine the value of the second largest element in this sequence. It is guaranteed that the sequence has at least two elements. first_max = int(input()) second_max = int(input()) if first_max < second_max: first_max, second_max = second_max, first_max element = int(input()) while element != 0: if element > first_max: second_max, first_max = first_max, element elif element > second_max: second_max = element print(second_max)
109
element = int(input()) if element > maximum:
Statement A sequence consists of integer numbers and ends with the number 0. Determine how many elements of this sequence are equal to its largest element. maximum = 0 num_maximal = 0 element = -1 while element != 0: element = int(input()) if element > maximum: maximum, num_maximal = element, 1 elif element == maximum: num_maximal += 1 print(num_maximal)
110
Statement n = int(input()) if n == 0: print(0) else: a, b = 0, 1
The Fibonacci sequence is defined as follows: Given a non-negative integer n, print the nth Fibonacci number This problem can also be solved with a for loop. ϕn n = int(input()) if n == 0: print(0) else: a, b = 0, 1 for i in range(2, n + 1): a, b = b, a + b print(b)
111
while fib_next <= a: if fib_next == a: print(n) break
Statement The Fibonacci sequence is defined as follows: Given an integer, a, determine its index among the Fibonacci numbers, that is, print the number n such that ϕn = a. If a is not a Fibonacci number, print -1. a = int(input()) if a == 0: print(0) else: fib_prev, fib_next = 0, 1 n = 1 while fib_next <= a: if fib_next == a: print(n) break fib_prev, fib_next = fib_next, fib_prev + fib_next n += 1 print(-1)
112
element = int(input()) while element != 0: if prev == element:
Statement Given a sequence of integer numbers ending with the number 0. Determine the length of the widest fragment where all the elements are equal to each other. prev = -1 curr_rep_len = 0 max_rep_len = 0 element = int(input()) while element != 0: if prev == element: curr_rep_len += 1 else: prev = element max_rep_len = max(max_rep_len, curr_rep_len) curr_rep_len = 1 print(max_rep_len)
113
Lists
128
for i in range(0, len(a), 2): print(a[i])
Statement Given a list of numbers, find and print all the list elements with an even index number. (i.e. A[0], A[2], A[4], ...). a = input().split() for i in range(0, len(a), 2): print(a[i])
129
a = [int(i) for i in input().split()] for elem in a: if elem % 2 == 0:
Statement Given a list of numbers, find and print all elements that are an even number. In this case use a for-loop that iterates over the list, and not over its indices! That is, don't use range() a = [int(i) for i in input().split()] for elem in a: if elem % 2 == 0: print(elem)
130
a = [int(i) for i in input().split()] for i in range(1, len(a)):
Statement Given a list of numbers, find and print all the elements that are greater than the previous element. a = [int(i) for i in input().split()] for i in range(1, len(a)): if a[i] > a[i - 1]: print(a[i])
131
a = [int(i) for i in input().split()] for i in range(1, len(a)):
Statement Given a list of numbers, find and print the first adjacent elements which have the same sign. If there is no such pair, leave the output blank. a = [int(i) for i in input().split()] for i in range(1, len(a)): if a[i - 1] * a[i] > 0: print(a[i - 1], a[i]) break
132
a = [int(i) for i in input().split()] counter = 0
Statement Given a list of numbers, determine and print the quantity of elements that are greater than both of their neighbors. The first and the last items of the list shouldn't be considered because they don't have two neighbors. a = [int(i) for i in input().split()] counter = 0 for i in range(1, len(a) - 1): if a[i - 1] < a[i] > a[i + 1]: counter += 1 print(counter)
133
a = [int(i) for i in input().split()] for i in range(1, len(a)):
Statement Given a list of numbers. Determine the element in the list with the largest value. Print the value of the largest element and then the index number. If the highest element is not unique, print the index of the first instance. index_of_max = 0 a = [int(i) for i in input().split()] for i in range(1, len(a)): if a[i] > a[index_of_max]: index_of_max = i print(a[index_of_max], index_of_max)
134
a = [int(i) for i in input().split()] num_distinct = 1
Statement Given a list of numbers with all of its elements sorted in ascending order, determine and print the quantity of distinct elements in it. a = [int(i) for i in input().split()] num_distinct = 1 for i in range(0, len(a) - 1): if a[i] != a[i + 1]: num_distinct += 1 print(num_distinct)
135
a = [int(i) for i in input().split()] for i in range(1, len(a), 2):
Statement Given a list of numbers, swap adjacent items in pairs (A[0] with A[1], A[2] with A[3], etc.). Print the resulting list. If a list has an odd number of elements, leave the last element in place. a = [int(i) for i in input().split()] for i in range(1, len(a), 2): a[i - 1], a[i] = a[i], a[i - 1] print(' '.join([str(i) for i in a]))
136
a = [int(s) for s in input().split()] index_of_min = 0
Statement Given a list of unique numbers, swap the minimal and maximal elements of this list. Print the resulting list. a = [int(s) for s in input().split()] index_of_min = 0 index_of_max = 0 for i in range(1, len(a)): if a[i] > a[index_of_max]: index_of_max = i if a[i] < a[index_of_min]: index_of_min = i a[index_of_min], a[index_of_max] = a[index_of_max], a[index_of_min] print(' '.join([str(i) for i in a]))
137
a = [int(s) for s in input().split()] counter = 0
Statement Given a list of numbers, count how many element pairs have the same value (are equal). Any two elements that are equal to each other should be counted exactly once. a = [int(s) for s in input().split()] counter = 0 for i in range(len(a)): for j in range(i + 1, len(a)): if a[i] == a[j]: counter += 1 print(counter)
138
a = [int(s) for s in input().split()] for i in range(len(a)):
Statement Given a list of numbers, find and print the elements that appear in the list only once. The elements must be printed in the order in which they occur in the original list. a = [int(s) for s in input().split()] for i in range(len(a)): for j in range(len(a)): if i != j and a[i] == a[j]: break else: print(a[i], end=' ')
139
new_x, new_y = [int(s) for s in input().split()] x.append(new_x)
Statement In chess it is known that it is possible to place 8 queens on an 8×8 chess board such that none of them can attack another. Given a placement of 8 queens on the board, determine if there is a pair of queens that can attach each other on the next move. Print the word NO if no queen can attack another, otherwise print YES. The input consists of eight coordinate pairs, one pair per line, with each pair giving the position of a queen on a standard chess board with rows and columns numbered starting at 1. n = 8 x = [] y = [] for i in range(n): new_x, new_y = [int(s) for s in input().split()] x.append(new_x) y.append(new_y) correct = True for j in range(i + 1, n): if x[i] == x[j] or y[i] == y[j] or abs(x[i] - x[j]) == abs(y[i] - y[j]): correct = False if correct: print('NO') else: print('YES')
140
n, k = [int(s) for s in input().split()] bahn = ['I'] * n
In bowling, the player starts with 10 pins at the far end of a lane. The object is to knock all the pins down. For this exercise, the number of pins and balls will vary. Given the number of pins N and then the number of balls K to be rolled, followed by K pairs of numbers (one for each ball rolled), determine which pins remain standing after all the balls have been rolled. The balls are numbered from 1 to N (inclusive) for this situation. The subsequent number pairs, one for each K represent the start to stop (inclusive) positions of the pins that were knocked down with each role. Print a sequence of N characters, where "I" represents a pin left standing and "." represents a pin knocked down. n, k = [int(s) for s in input().split()] bahn = ['I'] * n for i in range(k): left, right = [int(s) for s in input().split()] for j in range(left - 1, right): bahn[j] = '.' print(''.join(bahn))
141
Functions and Recursion
153
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) x1 = float(input())
Statement Given four real numbers representing cartesian coordinates: (x1,y1), (x2,y2). Write a function distance(x1, y1, x2, y2) to compute the distance between the points (x1,y1) and (x2,y2). Read four real numbers and print the resulting distance calculated by the function. The formula for distance between two points is the same as you were taught in maths (Pythagoras’ theorem). from math import sqrt def distance(x1, y1, x2, y2): return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) x1 = float(input()) x2 = float(input()) y1 = float(input()) y2 = float(input()) print(distance(x1, x2, y1, y2))
154
for i in range(abs(n)): res *= a if n >= 0: return res else:
Statement Given a positive real number a and integer n. Compute an. Write a function power(a, n) to calculate the results using the function and print the result of the expression. Don't use the same function from the standard library. def power(a, n): res = 1 for i in range(abs(n)): res *= a if n >= 0: return res else: return 1 / res print(power(float(input()), int(input())))
155
def capitalize(word): first_letter_small = word[0]
Statement Write a function capitalize(lower_case_word) that takes the lower case word and returns the word with the first letter capitalized. Eg., print(capitalize('word')) should print the word Word. Then, given a line of lowercase ASCII words (text separated by a single space), print it with the first letter of each word capitalized using the your own function capitalize(). In Python there is a function ord(character), which returns character code in the ASCII chart, and the function chr(code), which returns the character itself from the ASCII code. For example, ord('a') == 97, chr(97) == 'a'. def capitalize(word): first_letter_small = word[0] first_letter_big = chr(ord(first_letter_small) - ord('a') + ord('A')) return first_letter_big + word[1:] source = input().split() res = [] for word in source: res.append(capitalize(word)) print(' '.join(res))
156
print(power(float(input()), int(input())))
Given a positive real number a and a non-negative integer n. Calculate an without using loops, ** operator or the built in function math.pow(). Instead, use recursion and the relation an=an-1. Print the result. Form the function power(a, n). def power(a, n): if n == 0: return 1 else: return a * power(a, n - 1) print(power(float(input()), int(input())))
157
Statement def reverse(): x = int(input()) if x != 0: reverse()
Given a sequence of integers that end with a 0. Print the sequence in reverse order. Don't use lists or other data structures. Use the force of recursion instead. def reverse(): x = int(input()) if x != 0: reverse() print(x)
158
return fib(n - 1) + fib(n - 2) print(fib(int(input())))
Statement Given a non-negative integer n, print the nth Fibonacci number. Do this by writing a function fib(n) which takes the non-negative integer n and returns the nth Fibonacci number. Don't use loops, use the flair of recursion instead. However, you should think about why the recursive method is much slower than using loops. def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) print(fib(int(input())))
159
Two-dimensional lists (arrays)
174
n, m = [int(i) for i in input().split()]
Statement Given two integers representing the rows and columns (m×n), and subsequent m rows of n elements, find the index position of the maximum element and print two numbers representing the index (i×j) or the row number and the column number. If there exist multiple such elements in different rows, print the one with smaller row number. If there multiple such elements occur on the same row, output the smallest column number. n, m = [int(i) for i in input().split()] a = [[int(j) for j in input().split()] for i in range(n)] best_i, best_j = 0, 0 curr_max = a[0][0] for i in range(n): for j in range(m): if a[i][j] > curr_max: curr_max = a[i][j] best_i, best_j = i, j print(best_i, best_j)
175
a = [['.'] * n for i in range(n)] for i in range(n): a[i][i] = '*'
Statement Given an odd number integer n, produce a two-dimensional array of size (n×n). Fill each element with a single character string of "." . Then fill the middle row, the middle column and the diagonals with the single character string of "*" (an image of a snow flake). Print the array elements in (n×n) rows and columns and separate the characters with a single space. n = int(input()) a = [['.'] * n for i in range(n)] for i in range(n): a[i][i] = '*' a[n // 2][i] = '*' a[i][n // 2] = '*' a[i][n - i - 1] = '*' for row in a: print(' '.join(row))
176
n, m = [int(i) for i in input().split()] a = [] for i in range(n):
Statement Given two numbers n and m. Create a two-dimensional array of size (n×m) and populate it with the characters "." and "*" in a checkerboard pattern. The top left corner should have the character "." . n, m = [int(i) for i in input().split()] a = [] for i in range(n): a.append([]) for j in range(m): if (i + j) % 2 == 0: a[i].append('.') else: a[i].append('*') for row in a: print(' '.join(row))
177
a = [[abs(i - j) for j in range(n)] for i in range(n)] for row in a:
Statement Given an integer n, produce a two-dimensional array of size (n×n) and complete it according to the following rules, and print with a single space between characters: • On the main diagonal write 0 . • On the diagonals adjacent to the main, write 1 . • On the next adjacent diagonals write 2 and so forth. Print the elements of the resulting array. n = int(input()) a = [[abs(i - j) for j in range(n)] for i in range(n)] for row in a: print(' '.join([str(i) for i in row]))
178
a = [[0] * n for i in range(n)] for i in range(n): a[i][n - i - 1] = 1
Statement Given an integer n, create a two-dimensional array of size (n×n) and populate it as follows, with spaces between each character: • The positions on the minor diagonal (from the upper right to the lower left corner) receive 1 . • The positions above this diagonal recieve 0 . • The positions below the diagonal receive 2 . Print the elements of the resulting array. n = int(input()) a = [[0] * n for i in range(n)] for i in range(n): a[i][n - i - 1] = 1 for j in range(n - i, n): a[i][j] = 2 for row in a: for elem in row: print(elem, end=' ') print()
179
def swap_columns(a, i, j): for k in range(len(a)):
Statement Given two positive integers m and n, m lines of n elements, giving an m×n matrix A, followed by two non-negative integers i and j less than n, swap columns i and j of A and print the result. Write a function swap_columns(a, i, j) and call it to exchange the columns. def swap_columns(a, i, j): for k in range(len(a)): a[k][i], a[k][j] = a[k][j], a[k][i] n, m = [int(i) for i in input().split()] a = [[int(j) for j in input().split()] for i in range(n)] i, j = [int(i) for i in input().split()] swap_columns(a, i, j) print('\n'.join([' '.join([str(i) for i in row]) for row in a]))
180
m, n = [int(k) for k in input().split()]
Statement Given two positive integers m and n, m lines of n elements, giving an m×n matrix A, followed by one integer c, multiply every entry of the matrix by c and print the result. m, n = [int(k) for k in input().split()] A = [[int(k) for k in input().split()] for i in range(m)] c = int(input()) for i in range(m): for j in range(n): A[i][j] *= c print('\n'.join([' '.join([str(k) for k in row]) for row in A]))
181
m, n, r = [int(k) for k in input().split()]
A = [[int(k) for k in input().split()] for i in range(m)] B = [[int(k) for k in input().split()] for j in range(n)] C = [[0]*r for i in range(m)] for i in range(m): for k in range(r): for j in range(n): C[i][k] += A[i][j] * B[j][k] print('\n'.join([' '.join([str(k) for k in row]) for row in C]))
182
Sets
190
print(len(set(input().split())))
Statement Given a list of integers. Determine how many distinct numbers there are. This task can be solved in one line of code. print(len(set(input().split())))
191
print(len(set(input().split()) & set(input().split())))
Statement Given two lists of numbers. Count how many unique numbers occur in both of them. This task can be solved in one line of code. print(len(set(input().split()) & set(input().split())))
192
print(*sorted(set(input().split()) & set(input().split()), key=int))
Statement Given two lists of numbers. Find all the numbers that occur in both the first and the second list and print them in ascending order. Even this task can be solved in one line of code. print(*sorted(set(input().split()) & set(input().split()), key=int))
193
numbers = [int(s) for s in input().split()] occur_before = set()
Statement Given a sequence of numbers, determine if the next number has already been encountered. For each number, print the word YES (in a separate line) if this number has already been encountered, and print NO, if it has not already been encountered. numbers = [int(s) for s in input().split()] occur_before = set() for num in numbers: if num in occur_before: print('YES') else: print('NO') occur_before.add(num)
194
def print_set(some_set): print(len(some_set))
Statement Alice and Bob like to play with colored cubes. Each child has its own set of cubes and each cube has a distinct color, but they want to know how many unique colors exist if they combine their block sets. To determine this, the kids enumerated each distinct color with a random number from 0 to 108. At this point their enthusiasm dried up, and you are invited to help them finish the task. Given two integers that indicate the number of blocks in Alice's and then Bob's sets N and M. The following N lines contain the numerical color value for each cube in Alice's set. Then the last M rows contain the numerical color value for each cube in Bob's set. Find three sets: the numerical colors of cubes in both sets, the numerical colors of cubes only in Alice's set, and the numerical colors of cubes only in Bob's set. For each set, print the number of elements in the set, followed by the numerical color elements, sorted in ascending order. def print_set(some_set): print(len(some_set)) print(*[str(item) for item in sorted(some_set)]) N, M = [int(s) for s in input().split()] A_colors, B_colors = set(), set() for i in range(N): A_colors.add(int(input())) for i in range(M): B_colors.add(int(input())) print_set(A_colors & B_colors) print_set(A_colors - B_colors) print_set(B_colors - A_colors)
195
for _ in range(int(input())): words.update(input().split())
Statement Given a number n, followed by n lines of text, print the number of distinct words that appear in the text. For this, we define a word to be a sequence of non-whitespace characters, separated by one or more whitespace or newline characters. Punctuation marks are part of a word, in this definition. words = set() for _ in range(int(input())): words.update(input().split()) print(len(words))
196
all_nums = set(range(1, n + 1)) possible_nums = all_nums while True:
Statement Augustus and Beatrice play the following game. Augustus thinks of a secret integer number from 1 to n. Beatrice tries to guess the number by providing a set of integers. Augustus answers YES if his secret number exists in the provided set, or NO, if his number does not exist in the provided numbers. Then after a few questions Beatrice, totally confused, asks you to help her determine Augustus's secret number. Given the value of n in the first line, followed by the a sequence Beatrice's guesses, series of numbers separated by spaces and Agustus's responses, or Beatrice's plea for HELP. When Beatrice calls for help, provide a list of all the remaining possible secret numbers, in ascending order, separated by a space. n = int(input()) all_nums = set(range(1, n + 1)) possible_nums = all_nums while True: guess = input() if guess == 'HELP': break guess = {int(x) for x in guess.split()} answer = input() if answer == 'YES': possible_nums &= guess else: possible_nums &= all_nums - guess print(' '.join([str(x) for x in sorted(possible_nums)]))
197
print(len(known_by_everyone), *sorted(known_by_everyone), sep='\n')
Statement Each student at a certain school speaks a number of languages. We need to determine which languges are spoken by all the students, which languages are spoken by at least one student. Given, the number of students, and then for each student given the number of languages they speak followed by the name of each language spoken, find and print the number of languages spoken by all the students, followed by a list the languages by name, then print the number of languages spoken by at least one student, followed by the list of the languages by name. Print the languages in alphabetical order. students = [{input() for j in range(int(input()))} for i in range(int(input()))] known_by_everyone, known_by_someone = set.intersection(*students), set.union(*students) print(len(known_by_everyone), *sorted(known_by_everyone), sep='\n') print(len(known_by_someone), *sorted(known_by_someone), sep='\n')
198
Dictionaries
207
for word in input().split(): counter[word] = counter.get(word, 0) + 1
Statement The text is given in a single line. For each word of the text count the number of its occurrences before it. A word is a sequence of non-whitespace characters. Two consecutive words are separated by one or more spaces. Punctuation marks are a part of a word, by this definition. counter = {} for word in input().split(): counter[word] = counter.get(word, 0) + 1 print(counter[word] - 1, end=' ')
208
first, second = input().split() d[first] = second d[second] = first
Statement You are given a dictionary consisting of word pairs. Every word is a synonym the other word in its pair. All the words in the dictionary are different. After the dictionary there's one more word given. Find a synonym for him. n = int(input()) d = {} for i in range(n): first, second = input().split() d[first] = second d[second] = first print(d[input()])
209
for _ in range(int(input())): candidate, votes = input().split()
Statement As you know, the president of USA is elected not by direct vote, but through a two-step voting. First elections are held in each state and determine the winner of elections in that state. Thereafter, the state election is going: in this election, every state has a certain the number of votes — the number of electors from that state. In practice, all the electors from the state of voted in accordance with the results of the vote within a state. The first line contains the number of records. After that, each entry contains the name of the candidate and the number of votes they got in one of the states. Count the total results of the elections: sum the number of votes for each candidate. Print candidates in the alphabetical order. num_votes = {} for _ in range(int(input())): candidate, votes = input().split() num_votes[candidate] = num_votes.get(candidate, 0) + int(votes) for candidate, votes in sorted(num_votes.items()): print(candidate, votes)
210
for i in range(int(input())): line = input().split() for word in line:
Statement Given the text: the first line contains the number of lines, then given the lines of words. Print the word in the text that occurs most often. If there are many such words, print the one that is less in the alphabetical order. counter = {} for i in range(int(input())): line = input().split() for word in line: counter[word] = counter.get(word, 0) + 1 max_count = max(counter.values()) most_frequent = [k for k, v in counter.items() if v == max_count] print(min(most_frequent))
211
Statement The virus attacked the filesystem of the supercomputer and broke the control of access rights to the files. For each file there is a known set of operations which may be applied to it: • write W, • read R, • execute X. The first line contains the number N — the number of files contained in the filesystem. The following N lines contain the file names and allowed operations with them, separated by spaces. The next line contains an integer M — the number of operations to the files. In the last M lines specify the operations that are requested for files. One file can be requested many times. You need to recover the control over the access rights to the files. For each request your program should return OK if the requested operation is valid or Access denied if the operation is invalid. OPERATION_PERMISSION = { 'read': 'R', 'write': 'W', 'execute': 'X', } file_permissions = {} for i in range(int(input())): file, *permissions = input().split() file_permissions[file] = set(permissions) operation, file = input().split() if OPERATION_PERMISSION[operation] in file_permissions[file]: print('OK') else: print('Access denied')
212
for i in range(int(input())): country, *cities = input().split()
Statement Given a list of countries and cities of each country. Then given the names of the cities. For each city specify the country in which it is located. motherland = {} for i in range(int(input())): country, *cities = input().split() for city in cities: motherland[city] = country print(motherland[input()])
213
Statement Given a number n, followed by n lines of text, print all words encountered in the text, one per line. The words should be sorted in descending order according to their number of occurrences in the text, and all words with the same frequency should be printed in lexicographical order. Hint. After you create a dictionary of the words and their frequencies, you would like to sort it according to the frequencies. This can be achieved if you create a list whose elements are tuples of two elements: the frequency of occurrence of a word and the word itself. For example, [(2, 'hi'), (1, 'what'), (3, 'is')]. Then the standard list sort will sort a list of tuples, with the tuples compared by the first element, and if these are equal, by the second element. This is nearly what is required in the problem. from collections import Counter words = [] for _ in range(int(input())): words.extend(input().split()) counter = Counter(words) pairs = [(-pair[1], pair[0]) for pair in counter.most_common()] words = [pair[1] for pair in sorted(pairs)] print('\n'.join(words)) # You can also solve this problem without Counter: # # n = int(input()) # counts = {} # for _ in range(n): # for word in input().split(): # counts[word] = counts.get(word, 0) + 1 # freqs = [(-count, word) for (word, count) in counts.items()] # for c, word in sorted(freqs): # print(word)
214
Statement One day, going through old books in the attic, a student Bob found English-Latin dictionary. By that time he spoke English fluently, and his dream was to learn Latin. So finding the dictionary was just in time. Unfortunately, full-fledged language studying process requires also another type of dictionary: Latin-English. For lack of a better way he decided to make a second dictionary using the first one. As you know, the dictionary consists of words, each of which contains multiple translations. For each Latin word that appears anywhere in the dictionary, Bob has to find all its translations (that is, all English words, for which our Latin word is among its translations), and take them and only them as the translations of this Latin word. Help him to create a Latin-English. The first line contains a single integer N — the number of English words in the dictionary. Followed by N dictionary entries. Each entry is contained on a separate line, which contains first the English word, then a hyphen surrounded by spaces and then comma-separated list with the translations of this English word in Latin. All the words consist only of lowercase English letters. The translations are sorted in lexicographical order. The order of English words in the dictionary is also lexicographic. Print the corresponding Latin-English dictionary in the same format. In particular, the first word line should be the lexicographically minimal translation of the Latin word, then second in that order, etc. Inside the line the English words should be sorted also lexicographically. from collections import defaultdict latin_to_english = defaultdict(list) for i in range(int(input())): english_word, latin_translations_chunk = input().split(' - ') latin_translations = latin_translations_chunk.split(', ') for latin_word in latin_translations: latin_to_english[latin_word].append(english_word) print(len(latin_to_english)) for latin_word, english_translations in sorted(latin_to_english.items()): print(latin_word + ' - ' + ', '.join(english_translations))
Similar presentations
© 2023 SlidePlayer.com Inc.
All rights reserved.