(PDF Download) Basic Exercises For Competitive Programming Python 1st Edition Jan Pol Fulll Chapter
(PDF Download) Basic Exercises For Competitive Programming Python 1st Edition Jan Pol Fulll Chapter
com
https://textbookfull.com/product/basic-
exercises-for-competitive-programming-
python-1st-edition-jan-pol/
textbookfull
More products digital (pdf, epub, mobi) instant
download maybe you interests ...
https://textbookfull.com/product/basic-communication-for-
competitive-exams-rony-parvez/
https://textbookfull.com/product/python-programming-for-
beginners-python-mastery-in-7-days-top-secret-coding-tips-with-
hands-on-exercises-for-your-dream-job-1st-edition-oswald-
thornton/
https://textbookfull.com/product/algorithms-for-competitive-
programming-1st-edition-david-esparza-alba/
https://textbookfull.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-edition-
christoph-durr/
Hydrochemistry basic concepts and exercises 1st Edition
Eckhard Worch
https://textbookfull.com/product/hydrochemistry-basic-concepts-
and-exercises-1st-edition-eckhard-worch/
https://textbookfull.com/product/python-programming-for-data-
analysis-1st-edition-jose-unpingco/
https://textbookfull.com/product/python-workout-50-essential-
exercises-1st-edition-reuven-m-lerner/
https://textbookfull.com/product/programming-with-python-for-
social-scientists-1st-edition-phillip-brooker/
https://textbookfull.com/product/python-workout-50-ten-minute-
exercises-1st-edition-reuven-m-lerner/
The following book shows a compilation of more than 20
basic exercises for competitive programming, all of them
are written in Python. In addition, desktop tests are added
to observe the operation of each algorithm.
Hoping you can take knowledge of the pages of this book,
my best wishes.
Jan Pol
Exercise 1
Write a program that reads a string S, and prints that line
on the standard output in reverse, that is, flipped right-to-
left.
Input
The only input has a string S.
Output
Print the string in reverse
Example
Input
1 2 3 hello
Output
olleh 3 2 1
Solution
One way to easily solve this task is to use a loop to print the
characters from the last position to the first. This avoids the
need to save the reverse list, just print each character.
The code for the solution written in Python is shown below.
1 l = input()
2 i = len(l)
3 while i > 0:
4 i = i - 1
5 print(l[i], end='')
6 print()
Desktop Testing
Doing a desktop testing, it is observed how in each iteration
each character is added inversely.
Exercise 2
Given of input a positive integer n. If n is even, the
algorithm divides it by two, and if n is odd, the algorithm
multiplies it by three and adds one. The algorithm repeats
this, until n is one. For example, the sequence for n=5 is as
follows:
5→16→8→4→21
Your task is to simulate the execution of the algorithm for a
given value of n.
Input
The only input line contains an positive integer n.
Output
Print a line that contains all values of n separated with
spaces.
Example
Input
5
Output
5 16 8 4 21
Solution
To solve this task, a cycle is used to verify that the number
is not yet 1. Within the cycle it is checked if the number is
even, it is divided by two, otherwise the number is multiplied
by 3 and 1 is added to it. the number is printed, like this
until the number is 1.
The code for the solution written in Python is shown below.
1 n = int(input())
2 print(n, end= ' ')
3 while n > 1:
4 if n % 2 == 0:
5 n //= 2
6 else:
7 n = 3 * n + 1
8 print(n, end=' ')
Desktop Testing
Doing a desktop testing, it shows if the number is odd or
even and the operation is performed.
Exercise 3
Write a program that reads a list of non-negative numbers
from the standard input, with one number per line, and
prints a histogram corresponding to those numbers. In this
histogram, each number N is represented by a line of N
characters "#"
Input
The only line contains n non-negative integers.
Output
Print the histogram result.
Example
Input
10 15 7 9 1 3
Output
##########
###############
#######
#########
#
###
Solution
To solve this task, it is taken into account that a list of non-
negative integers will be received so that they are saved
using a “map” of integers for the input, removing the
spaces. Then '#' is printed as many times as the value of the
number.
The code for the solution written in Python is shown below.
1 arr = map(int, input().split())
2
3 for a in arr:
4 print('#' * a)
Desktop Testing
Doing a desktop testing, it is shown how in the next line of
each iteration as many '#' as the value of the number are
added.
Exercise 4
You are given all numbers between 1,2,…,n except one.
Your task is to find the missing number.
Input
The first input line contains an integer n.
The second line contains n−1 numbers. Each number is
distinct and between 1 and n (inclusive).
Output
Print the missing number.
Example
Input
10
2 8 10 6 5 1 3 7 4
Output
9
Solution
To solve this task, the integer n is saved. Then the integer
line is saved. A sum is initialized, each integer is added. At
the end, the Gauss sum formula is used: n * (n + 1) / 2.
The previously made sum is subtracte it to obtain the
missing number. This works because the Gauss sum gets
the real total sum based on the total of numbers, if the sum
of the provided numbers is subtracted, the result will show
the missing value to get the real total sum.
The code for the solution written in Python is shown below.
1 n = int(input())
2 arr = map(int, input().split())
3 s = 0
4
5 for a in arr:
6 s += a
7
8 print(n * (n + 1) // 2 - s)
Desktop Testing
Doing a desktop testing, it is shown how in each iteration
the respective number is added. At the end the operation is
printed.
The final result is:
10 * (10 + 1) // 2 – 46
10 * 11 // 2 – 46
110 // 2 – 46
55 – 46
Result: 9
Exercise 5
Given a sequence of integers A, a maximal identical
sequence is a sequence of adjacent identical values of
maximal length k. Write a program that reads an input
sequence A, with one or more numbers per line, and
outputs the value of the first (leftmost) maximal identical
sequence in A.
Input
The first input line contains an integer n.
The second line contains n integers.
Output
Print one integer: the length of the longest repetition
Example
Input
24622
Output
2
Solution
To solve this task, an efficient way to know which number is
the most repeated is to use variables that help us in the
process. In this case, 'k' is used to determine how much a
number is repeated, 'i' saves the previous index, 'j' saves
the current index and 'v' stores the number that is repeated
the most sequentially.
At the beginning of the cycle, the previous and current
values are compared, if they are different, the indices are
exchanged. The index 'j' increases and is compared if the
numbers that are repeated is greater than 'k', if so, 'v' takes
the value of the number and 'k' takes the value of how
much that number was repeated.
The code for the solution written in Python is shown below.
1 A = list(map(int, input().split()))
2
3 v = A[0]
4k = 1
5i = 0
6j = 1
7 while j < len(A):
8 if A[j] != A[i]:
9i = j
10 j += 1
11 if j - i > k:
12 v = A[i]
13 k = j - i
14
15 print(v)
Desktop Testing
Doing a desktop testing, it is observed how in each cycle
the previous number and the current number are compared,
as well as the increase or exchange in the indexes according
to whether the sequential number is different. When the
numbers compared are equal, the index 'j' increases more
than the 'i', when not, the indexes go hand in hand.
Below is the sequence of integers 'A' and the desk test.
Exercise 6
You are given a DNA sequence: a string consisting of
characters A, C, G, and T. Your task is to find the longest
repetition in the sequence. This is a maximum-length
substring containing only one type of character.
Input
The only input line contains a string of n characters.
Output
Print one integer: the length of the longest repetition.
Example
Input
ATTGCCCA
Output
3
Solution
To solve this task, the input string is taken, using the
variables 'ans' stores the response, 'count' counts the
repetitions and 'l' contains the character to compare. A loop
is used to go through each character in the string, if the
character is repeated, add the counter and replace 'ans'
with the maximum between 'count' and 'ans', otherwise 'l'
becomes the new character and the counter is reset.
The code for the solution written in Python is shown below.
1 s = input()
2 ans = 1
3 count = 0
4 l = 'A'
5 for cha in s:
6 if cha == l:
7 count += 1
8 if count > ans:
9 ans = count
10 else:
11 l = cha
12 count = 1
13 print(ans, end=' ')
Desktop Testing
Doing a desktop testing, it shows how each character of the
sequence is compared, each that is equal increases the
counter and the maximum between the response is verified,
when the values are not reset.
Exercise 7
Write a program that takes a number N (a positive integer)
in decimal notation from the console, and prints its value as
a roman numeral.
Input
The only input line has an integer n.
Output
Print the value as a roman numeral.
Example
Input
2021
Output
MMXXI
Solution
To solve this task, the predefined characters of the Roman
numerals are listed, separated by groups, from one to nine,
from ten to 90 and from 100 to 900, each one with the
number zero. It is checked if the quantity is greater than or
equal to 1000, if so, the symbol 'M' is added as many times
as thousands it contains. Then the hundreds are extracted
and replaced by their respective symbols, in the same way
the tens and units, printing the result at the end.
The code for the solution written in Python is shown below.
1 ten_zero = ['', 'I', 'II', 'III', 'IV', 'V', 'VI',
'VII', 'VIII', 'IX']
2 ten_one = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX',
'LXX', 'LXXX', 'XC']
3 ten_two = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC',
'DCC', 'DCCC', 'CM']
4
5 n = int(input())
6
7 r = ''
8 while n >= 1000:
9 r += 'M'
10 n -= 1000
11
12 c = n // 100
13 r += ten_two[c]
14 n -= c*100
15
16 d = n // 10
17 r += ten_one[d]
18 n -= d*10
19
20 r += ten_zero[n]
21
22 print(r)
Desktop Testing
Doing a desktop testing, it is shown how each thousand is
subtracted from the quantity and the symbol 'M' is added, in
the same way the hundreds, tens and units are extracted to
obtain the result.
Exercise 8
You are given an array of n integers. You want to modify the
array so that it is increasing. Every element is at least as
large as the previous element.
On each move, you may increase the value of any element
by one. Your task is find the minimum number of moves
required.
Input
The first input line contains an integer n, the size of the
array.
Then, the second line contains n integers, the contents of
the array.
Output
Print the minimum number of moves.
Example
Input
5
21415
Output
4
Solution
To solve this task, we must find the least amount of
movements necessary to increase the values of an array so
that the list increases. After reading the input data, the
variables 'mx' are initialized, the maximum and 'ans' are
stored with a value of zero, each one of the data in the
array is traversed, the maximum is searched and the value
of the number is subtracted, the result is saved in response.
This works because it is looking for if the number before the
current one is greater, it obtains the difference between
current and previous, in other words it obtains the increase
that is needed so that both values are equal.
The code for the solution written in Python is shown below.
1 n = int(input())
2 arr = map(int, input().split())
3 mx = 0
4 ans = 0
5
6 for x in arr:
7 mx = max(x, mx)
8 ans += mx - x
9
10 print(ans)
Desktop Testing
Doing a desktop testing, it is shown how the maximum value
is obtained, at the moment in which the value of x
decreases, it obtains the necessary value to be equal to the
previous one.
Exercise 9
A ‘beautiful’ permutation is a permutation of integers
1,2,…,n, if there are no adjacent elements whose difference
is 1.
Given n, construct a beautiful permutation if such a
permutation exists. If there are no solutions, print “NO
SOLUTION”
Input
The only input line contains an integer n.
Output
Print a beautiful permutation of integers 1,2,…,n. If there
are several solutions, you may print any of them. If there
are no solutions, print "NO SOLUTION".
Example
Input
5
Output
24135
Solution
To solve this task, the difference between elements is
required to be different than 1. When n is equal to 1, 1 is
printed, if it is less than 4 there is no solution, in all other
cases, it will be enough to print 2 by 2 starting at 2 up to
the value of n + 1 and in another cycle the same strategy
but starting at 1.
The code for the solution written in Python is shown below.
1 n = int(input())
2 if n == 1:
3 print(1, end=' ')
4 elif n < 4:
5 print('NO SOLUTION')
6
7 else:
8 for i in range(2, n+1, 2):
9 print(i, end=' ')
10
11 for i in range(1, n+1, 2):
12 print(i, end=' ')
Desktop Testing
Doing a desktop testing, it is easy to observe that it is only
enough to print numbers from 2 to 2 with different start, in
this way it ensures that the difference between the numbers
is not 1.
Another random document with
no related content on Scribd:
CHAPTER IX
THE SHELL, ITS FORM, COMPOSITION AND GROWTH—DESIGNATION OF
ITS VARIOUS PARTS
Fig. 148.—Aplustrum
aplustre L. Mauritius,
showing the partly
internal shell (S); F,
foot; LL, cephalic
lappets; TT, double
set of tentacles. (After
Quoy and Gaimard.)
Fig. 149.—Sigaretus
laevigatus Lam.,
showing shell partially
immersed in the foot;
F, anterior
prolongation of the
foot. (After Souleyet.)
(3) Internal; e.g. Philine, Gastropteron, Pleurobranchus, Aplysia,
Limax, Arion, Hyalimax, Parmacella, Lamellaria, Cryptochiton, and,
among bivalves, Chlamydoconcha.
(4) Absent; e.g. all Nudibranchiata and Aplacophora, many
Cephalopoda, a few land Mollusca, e.g. all Onchidiidae, Philomycus,
and Vaginula.
The Univalve Shell.—In univalve Mollusca the normal form of the
shell is an elongated cone twisted into a spiral form round an axis,
the spiral ascending to the left. Probably the original form of the shell
was a simple cone, which covered the vital parts like a tent. As these
parts tended to increase in size, their position on the dorsal side of
the animal caused them gradually to fall over, drawing the shell with
them. The result of these two forces combined, the increasing size of
the visceral hump, and its tendency to pull the shell over with it,
probably resulted in the conversion of the conical into the spiral shell,
which gradually came to envelop the whole animal. Where the
visceral hump, instead of increasing in size, became flattened, the
conical shape of the shell may have been modified into a simple
elliptical plate (e.g. Limax), the nucleus representing the apex of the
cone. In extreme cases even this plate dwindles to a few calcareous
granules, or disappears altogether (Arion, Vaginula).
Varieties of the Spiral.—Almost every conceivable modification
of the spiral occurs, from the type represented by Gena, Haliotis,
Sigaretus, and Lamellaria, in which the spire is practically confined to
the few apical whorls, with the body-whorl inordinately large in
proportion, to a multispiral form like Terebra, with about twenty
whorls, very gradually increasing in size.
Fig. 151.—Examples of
shells with
disconnected whorls;
A, Cyathopoma cornu
Mf., Philippines; B,
Cylindrella hystrix
Wright, Cuba. (Both ×
4.)
Fig. 152.—Example of a
shell whose apical
whorls alone are
coiled, and the
remainder produced in
a regular curve.
(Cyclosurus Mariei
Morel., Mayotte.)
In some cases the regularly spiral form is kept, but the whorls are
completely disconnected; e.g. some Scalaria, Spirula; among fossil
Cephalopoda, Gyroceras, Crioceras, and Ancyloceras; and, among
recent land Mollusca, Cylindrella hystrix and Cyathopoma cornu (Fig.
151). Sometimes only the last whorl becomes disconnected from the
others, as in Rhiostoma (see Fig. 180, p. 266), Teinostoma, and in
the fossil Ophidioceras and Macroscaphites. Sometimes, again, not
more than one or two whorls at the apex are spirally coiled, and the
rest of the shell is simply produced or coiled in an exceedingly
irregular manner, e.g. Cyclosurus, Lituites, Orygoceras, Siliquaria
(Fig. 153), Vermetus. In Coecum (Fig. 170, p. 260) the spiral part is
entirely lost, and the shell becomes simply a cylinder. In a few cases
the last whorl is coiled irregularly backwards, and is brought up to
the apex, so that the animal in crawling must carry the shell with the
spire downwards, as in Anostoma (Fig. 154), Opisthostoma (Fig.
208, p. 309), Strophostoma, and Hypselostoma (Fig. 202 A, p. 302).
Fig. 153.—Siliquaria anguina Lam.,
showing scalariform coil of upper
whorls and irregular extension of
the lower.
Fig. 156.—Fulgur
perversum L., Florida. ½.
Fig. 161.—Cornucopia-
shaped monstrosity of
Helix aspersa, from
Ilfracombe. (British
Museum.)
Composition of the Shell.—The shell is mainly composed of
pure carbonate of lime, with a very slight proportion of phosphate of
lime, and an organic base allied to chitin, known as conchiolin. The
proportion of carbonate of lime is known to vary from about 99 p.c. in
Strombus to about 89 p.c. in Turritella. Nearly 1 p.c. of phosphate of
lime has been obtained from the shell of Helix nemoralis, and nearly
2 p.c. from that of Ostrea virginica. The conchiolin forms a sort of
membranous framework for the shell; it soon disappears in dead
specimens, leaving the shell much more brittle than it was when
alive. Carbonate of magnesia has also been detected, to the extent
of ·12 p.c. in Telescopium and ·48 p.c. in Neptunea antiqua. A trace
of silica has also occasionally been found.
When the shell exhibits a crystalline formation, the carbonate of
lime may take the form either of calcite or aragonite. The calcite
crystals are rhombohedral, optically uniaxal, and cleave easily, while
the aragonite cleave badly, belong to the rhombic system, and are
harder and denser, and optically biaxal. Both classes of crystal may
occur in the same shell.
Two main views have been held with regard to the formation and
structure of the shell—(1) that of Bowerbank and Carpenter, that the
shell is an organic formation, growing by interstitial deposit, in the
same manner as the teeth and bones of the higher animals; (2) that
of Réaumur, Eisig, and most modern writers, that the shell is of the
nature of an excretion, deposited like a cuticle on the outside of the
skin, being formed simply of a number of calcareous particles held
together by a kind of ‘animal glue.’ Leydig’s view is that the shell of
the Monotocardia is a secretion of the epithelium, but that in the
Pulmonata it originates within the skin itself, and afterwards
becomes free.[335]
According to Carpenter, when a fragment of any recent shell is
decalcified by being placed in dilute acid, a definite animal basis
remains, often so fine as to be no more than a membranous film, but
sometimes consisting of an aggregation of ‘cells’ with perfectly
definite forms. He accordingly divides all shell structure into cellular
and membranous, according to the characteristics of the animal
basis. Cellular structure is comparatively rare; it occurs most notably
in Pinna, where the shell is composed of a vast multitude of tolerably
regular hexagonal prisms (Fig. 162 B). Membranous structure
comprises all forms of shell which do not present a cellular tissue.
Carpenter held that the membrane itself was at one time a
constituent part of the mantle of the mollusc, the carbonate of lime
being secreted in minute ‘cells’ on its surface, and afterwards
spreading over the subjacent membrane through the bursting of the
cells.
The iridescence of nacreous shells is due to a peculiar lineation of
their surface, which can be readily detected by a lens. According to
Brewster, the iridescence is due to the alternation of layers of
granular carbonate of lime and of a very thin organic membrane, the
layers very slightly undulating. Carpenter, on the other hand, holds
that it depends upon the disposition of a single membranous layer in
folds or plaits, which lie more or less obliquely to the general surface,
so that their edges show as lines. The nacreous type of shell occurs
largely among those Mollusca which, from other details in their
organisation, are known to represent very ancient forms (e.g.
Nucula, Avicula, Trigonia, Nautilus). It is also the least permanent,
and thus in some strata we find that only casts of the nacreous shells
remain, while those of different constitution are preserved entire.
Porcellanous shells (of which the great majority of Gasteropoda
are instances) usually consist of three layers, each of which is
composed of a number of adjacent plates, like cards on edge. The
inclination of the plates in the different layers varies, but that of the
plates in the inner and outer layer is frequently the same, thus if the
plates are transverse in the middle stratum, they are longitudinal in
the inner and outer strata, and, if longitudinal in the middle, they are
transverse in the other two. Not uncommonly (Fig. 163 B) other
layers occur. In bivalves the disposition and nature of the layers is
much more varied.
Fig. 162.—A, Section of shell of Unio: a, periostracal layer; b, prismatic layer; c,
nacreous layer. B, Horizontal section of shell of Pinna, showing the hexagonal
prisms.
Fig. 165.—Neritina
longispina Récl., Mauritius.
(Operculum removed.)
The various details of sculpture on the exterior surface of the
shell, the striae, ribs, nodules, imbrications, spines, and other forms
of ornamentation are all the product of similar and corresponding
irregularities in the mantle margin, and have all been originally
situated at the edge of the lip. Spines, e.g. those of Murex and
Pteroceras, are first formed as a hollow thorn, cleft down its lower
side, and are afterwards filled in with solid matter as the mantle edge
withdraws. What purpose is served by the extreme elaboration of
these spiny processes in some cases, can hardly be considered as
satisfactorily ascertained. Possibly they are a form of sculptural
development which is, in the main, protective, and secures to its
owners immunity from the attacks of predatory fishes.
‘Attached’ genera (e.g. Chama, Spondylus) when living on smooth
surfaces have a flat shell, but when affixed to coral and other uneven
surfaces they become very irregular in shape. The sculpture of the
base on which they rest is often reproduced in these ‘attached’
shells, not only on the lower, but also on the upper valve, the
growing edge of which rests on the uneven surface of the base.
Oysters attached to the branches of the mangrove frequently display
a central convex rib, modelled on the shape of the branch, from
which the plaits of sculpture radiate, while specimens fixed to the
smooth trunk have no such rib. Crepidula, a genus which is in the
habit of attaching itself to other shells, varies in sculpture according
to that of its host. Sometimes the fact may be detected that a
specimen has lived on a ribbed shell when young, and on a smooth
one when old, or vice versâ. A new genus was actually founded by
Brown for a Capulus which had acquired ribs through adhesion to a
Pecten. A specimen of Hinnites giganteus in the British Museum
must at one period of its growth have adhered to a surface on which
was a Serpula, the impression of which is plainly reproduced on the
upper valve of the Hinnites.[339]
Fig. 166.—A specimen of Anomia
ephippium L., Weymouth,
taken upon Pecten maximus,
the sculpture of which is
reproduced on the upper
valve of the Anomia, and
even on a young Anomia
attached to the larger
specimen.
Growth of the Shell.—Nothing very definite is known with regard
to the rate of growth of the shell in marine Mollusca. Under
favourable conditions, however, certain species are known to
increase very rapidly, especially if the food supply be abundant, and
if there is no inconvenient crowding of individuals. Petit de la
Saussaye mentions[340] the case of a ship which sailed from
Marseilles for the west coast of Africa, after being fitted with an
entirely new bottom. On arriving at its destination, the vessel spent
68 days in the Gambia River, and took 86 days on its homeward
voyage. On being cleaned immediately on its return to Marseilles, an
Avicula 78 mm. and an Ostrea 95 mm. long (both being species
peculiar to W. Africa) were taken from its keel. These specimens had
therefore attained this growth in at most 154 days, for at the period
of their first attachment they are known to be exceedingly minute. P.
Fischer relates[341] that in 1862 a buoy, newly cleaned and painted,
was placed in the basin at Arcachon. In less than a year after, it was
found to be covered with thousands of very large Mytilus edulis, 100