Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
17 views

Basic Exercises for Competitive Programming Python 1st Edition Jan Pol pdf download

The document provides a collection of basic exercises for competitive programming using Python, including detailed solutions and desktop testing for each exercise. It covers various programming concepts such as string manipulation, number sequences, and array modifications. Each exercise is accompanied by input/output examples and corresponding Python code solutions.

Uploaded by

emrandirirz0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
17 views

Basic Exercises for Competitive Programming Python 1st Edition Jan Pol pdf download

The document provides a collection of basic exercises for competitive programming using Python, including detailed solutions and desktop testing for each exercise. It covers various programming concepts such as string manipulation, number sequences, and array modifications. Each exercise is accompanied by input/output examples and corresponding Python code solutions.

Uploaded by

emrandirirz0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Basic Exercises for Competitive Programming

Python 1st Edition Jan Pol download

https://textbookfull.com/product/basic-exercises-for-competitive-
programming-python-1st-edition-jan-pol/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Basic Communication for Competitive Exams Rony Parvez

https://textbookfull.com/product/basic-communication-for-
competitive-exams-rony-parvez/

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/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/

Algorithms For Competitive Programming 1st Edition


David Esparza Alba

https://textbookfull.com/product/algorithms-for-competitive-
programming-1st-edition-david-esparza-alba/

Competitive Programming in Python: 128 Algorithms to


Develop your Coding Skills 1st Edition Christoph Dürr

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/

Python Programming for Data Analysis 1st Edition José


Unpingco

https://textbookfull.com/product/python-programming-for-data-
analysis-1st-edition-jose-unpingco/

Python Workout: 50 Essential Exercises 1st Edition


Reuven M. Lerner

https://textbookfull.com/product/python-workout-50-essential-
exercises-1st-edition-reuven-m-lerner/

Programming with Python for Social Scientists 1st


Edition Phillip Brooker

https://textbookfull.com/product/programming-with-python-for-
social-scientists-1st-edition-phillip-brooker/

Python Workout 50 ten minute exercises 1st Edition


Reuven M Lerner

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.
Random documents with unrelated
content Scribd suggests to you:
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like