100% found this document useful (1 vote)
208 views56 pages

Competitive Programming in Python: 128 Algorithms To Develop Your Coding Skills 1st Edition Christoph Dürr PDF Download

Ebook download

Uploaded by

tqvwwbx7012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
208 views56 pages

Competitive Programming in Python: 128 Algorithms To Develop Your Coding Skills 1st Edition Christoph Dürr PDF Download

Ebook download

Uploaded by

tqvwwbx7012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Competitive Programming in Python: 128

Algorithms to Develop your Coding Skills 1st


Edition Christoph Dürr install download

https://textbookfull.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-edition-
christoph-durr/

Download more ebook instantly today - get yours now at 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!

Algorithmic Thinking. Learn Algorithms...Your Coding


Skills 2ed 2024 Zingaro D.

https://textbookfull.com/product/algorithmic-thinking-learn-
algorithms-your-coding-skills-2ed-2024-zingaro-d/

Good Habits for Great Coding: Improving Programming


Skills with Examples in Python Michael Stueben

https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-michael-
stueben/

Good Habits for Great Coding: Improving Programming


Skills with Examples in Python 1st Edition Michael
Stueben

https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-1st-edition-
michael-stueben/

Algorithms For Competitive Programming 1st Edition


David Esparza Alba

https://textbookfull.com/product/algorithms-for-competitive-
programming-1st-edition-david-esparza-alba/
Basic Exercises for Competitive Programming Python 1st
Edition Jan Pol

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

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/

Guide to Competitive Programming: Learning and


Improving Algorithms Through Contests (Undergraduate
Topics in Computer Science) Antti Laaksonen

https://textbookfull.com/product/guide-to-competitive-
programming-learning-and-improving-algorithms-through-contests-
undergraduate-topics-in-computer-science-antti-laaksonen/

Python: 3 books in 1: Beginner’s guide, Data science


and Machine learning. The easiest guide to start Python
programming. Unlock your programmer potential and
develop your project in just 30 days First Edition
William Dimick
https://textbookfull.com/product/python-3-books-in-1-beginners-
guide-data-science-and-machine-learning-the-easiest-guide-to-
start-python-programming-unlock-your-programmer-potential-and-
develop-your-project-in-just-30-d/

Coding Games in Python 1st Edition Carol Vorderman

https://textbookfull.com/product/coding-games-in-python-1st-
edition-carol-vorderman/
Competitive Programming in Python

Want to kill it at your job interview in the tech industry? Want to win that coding
competition? Learn all the algorithmic techniques and programming skills you need
from two experienced coaches, problem-setters, and judges for coding competitions.
The authors highlight the versatility of each algorithm by considering a variety of
problems and show how to implement algorithms in simple and efficient code. What
to expect:
* Master 128 algorithms in Python.
* Discover the right way to tackle a problem and quickly implement a solution of low
complexity.
* Understand classic problems like Dijkstra’s shortest path algorithm and
Knuth–Morris–Pratt’s string matching algorithm, plus lesser-known data structures
like Fenwick trees and Knuth’s dancing links.
* Develop a framework to tackle algorithmic problem solving, including: Definition,
Complexity, Applications, Algorithm, Key Information, Implementation, Variants,
In Practice, and Problems.
* Python code included in the book and on the companion website.

Christoph Dürr is a senior researcher at the French National Center for Scientific
Research (CNRS), affiliated with the Sorbonne University in Paris. After a PhD in
1996 at Paris-Sud University, he worked for one year as a postdoctoral researcher at
the International Computer Science Institute in Berkeley and one year in the School
of Computer Science and Engineering in the Hebrew University of Jerusalem in
Israel. He has worked in the fields of quantum computation, discrete tomography and
algorithmic game theory, and his current research activity focuses on algorithms and
optimisation. From 2007 to 2014, he taught a preparation course for programming
contests at the engineering school École Polytechnique, and acts regularly as a
problem setter, trainer, or competitor for various coding competitions. In addition, he
loves carrot cake.

Jill-Jênn Vie is a research scientist at Inria in machine learning. He is an alumnus


from École normale supérieure Paris-Saclay, where he founded the algorithmic club
of Paris-Saclay (CAPS) and coached several teams for the International Collegiate
Programming Contest (ICPC). He published a book in theoretical computer science
to help students prepare for prestigious French competitive exams such as Grandes
Écoles or agrégation, and directed a television show “Blame the Algorithm” about
the algorithms that govern our lives. He is part of the advisory board of the French
Computer Science Society (SIF), itself a member of the International Federation for
Information Processing (IFIP).
Competitive Programming
in Python
128 Algorithms to Develop Your Coding Skills

CHRISTOPH DÜRR
CNRS, Sorbonne University

JILL-JÊNN VIE
Inria

Translated by Greg Gibbons and Danièle Gibbons


University Printing House, Cambridge CB2 8BS, United Kingdom
One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314–321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi – 110025, India
79 Anson Road, #06–04/06, Singapore 079906

Cambridge University Press is part of the University of Cambridge.


It furthers the University’s mission by disseminating knowledge in the pursuit of
education, learning, and research at the highest international levels of excellence.

www.cambridge.org
Information on this title: www.cambridge.org/9781108716826
DOI: 10.1017/9781108591928
© Cambridge University Press 2021
Translation from the French language edition:
Programmation efficace - 128 algorithmes qu’il faut avoir compris et codés en Python au cour de sa vie
By Christoph Dürr & Jill-Jênn Vie
Copyright © 2016 Edition Marketing S.A.
www.editions-ellipses.fr
All Rights Reserved
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2021
Printed in the United Kingdom by TJ Books Limited, Padstow Cornwall
A catalogue record for this publication is available from the British Library.
Library of Congress Cataloging-in-Publication Data
Names: Dürr, Christoph, 1969– author. | Vie, Jill-Jênn, 1990– author. |
Gibbons, Greg, translator. | Gibbons, Danièle, translator.
Title: Competitive programming in Python : 128 algorithms to develop your
coding skills / Christoph Dürr, Jill-Jênn Vie ; translated by Greg
Gibbons, Danièle Gibbons.
Other titles: Programmation efficace. English
Description: First edition. | New York : Cambridge University Press, 2020.
| Includes bibliographical references and index.
Identifiers: LCCN 2020022774 (print) | LCCN 2020022775 (ebook) |
ISBN 9781108716826 (paperback) | ISBN 9781108591928 (epub)
Subjects: LCSH: Python (Computer program language) | Algorithms.
Classification: LCC QA76.73.P98 D8713 2020 (print) | LCC QA76.73.P98
(ebook) | DDC 005.13/3–dc23
LC record available at https://lccn.loc.gov/2020022774
LC ebook record available at https://lccn.loc.gov/2020022775
ISBN 978-1-108-71682-6 Paperback
Cambridge University Press has no responsibility for the persistence or accuracy of
URLs for external or third-party internet websites referred to in this publication
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Contents

Preface page ix

1 Introduction 1
1.1 Programming Competitions 1
1.2 Python in a Few Words 5
1.3 Input-Output 13
1.4 Complexity 17
1.5 Abstract Types and Essential Data Structures 20
1.6 Techniques 28
1.7 Advice 37
1.8 A Problem: ‘Frosting on the Cake’ 39

2 Character Strings 42
2.1 Anagrams 42
2.2 T9—Text on 9 Keys 43
2.3 Spell Checking with a Lexicographic Tree 46
2.4 Searching for Patterns 48
2.5 Maximal Boundaries—Knuth–Morris–Pratt 49
2.6 Pattern Matching—Rabin–Karp 56
2.7 Longest Palindrome of a String—Manacher 59

3 Sequences 62
3.1 Shortest Path in a Grid 62
3.2 The Levenshtein Edit Distance 63
3.3 Longest Common Subsequence 65
3.4 Longest Increasing Subsequence 68
3.5 Winning Strategy in a Two-Player Game 70

4 Arrays 72
4.1 Merge of Sorted Lists 73
4.2 Sum Over a Range 74
4.3 Duplicates in a Range 74
4.4 Maximum Subarray Sum 75
vi Contents

4.5 Query for the Minimum of a Range—Segment Tree 75


4.6 Query the Sum over a Range—Fenwick Tree 77
4.7 Windows with k Distinct Elements 80

5 Intervals 82
5.1 Interval Trees 82
5.2 Union of Intervals 85
5.3 The Interval Point Cover Problem 85

6 Graphs 88
6.1 Encoding in Python 88
6.2 Implicit Graphs 90
6.3 Depth-First Search—DFS 91
6.4 Breadth-First Search—BFS 93
6.5 Connected Components 94
6.6 Biconnected Components 97
6.7 Topological Sort 102
6.8 Strongly Connected Components 105
6.9 2-Satisfiability 110

7 Cycles in Graphs 113


7.1 Eulerian Tour 113
7.2 The Chinese Postman Problem 116
7.3 Cycles with Minimal Ratio of Weight to Length—Karp 117
7.4 Cycles with Minimal Cost-to-Time Ratio 120
7.5 Travelling Salesman 120
7.6 Full Example: Menu Tour 121

8 Shortest Paths 124


8.1 Composition Property 124
8.2 Graphs with Weights 0 or 1 126
8.3 Graphs with Non-negative Weights—Dijkstra 127
8.4 Graphs with Arbitrary Weights—Bellman–Ford 130
8.5 All Source–Destination paths—Floyd–Warshall 132
8.6 Grid 133
8.7 Variants 135

9 Matchings and Flows 138


9.1 Maximum Bipartite Matching 139
9.2 Maximal-Weight Perfect Matching—Kuhn–Munkres 145
9.3 Planar Matching without Crossings 151
9.4 Stable Marriages—Gale–Shapley 153
Contents vii

9.5 Maximum Flow by Ford–Fulkerson 155


9.6 Maximum Flow by Edmonds–Karp 158
9.7 Maximum Flow by Dinic 159
9.8 Minimum s − t Cut 162
9.9 s − t Minimum Cut for Planar Graphs 163
9.10 A Transport Problem 165
9.11 Reductions between Matchings and Flows 165
9.12 Width of a Partial Order—Dilworth 167

10 Trees 171
10.1 Huffman Coding 172
10.2 Lowest Common Ancestor 174
10.3 Longest Path in a Tree 178
10.4 Minimum Weight Spanning Tree—Kruskal 179

11 Sets 182
11.1 The Knapsack Problem 182
11.2 Making Change 184
11.3 Subset Sum 185
11.4 The k-sum Problem 187

12 Points and Polygons 189


12.1 Convex Hull 190
12.2 Measures of a Polygon 193
12.3 Closest Pair of Points 195
12.4 Simple Rectilinear Polygon 198

13 Rectangles 200
13.1 Forming Rectangles 200
13.2 Largest Square in a Grid 201
13.3 Largest Rectangle in a Histogram 202
13.4 Largest Rectangle in a Grid 204
13.5 Union of Rectangles 205
13.6 Union of Disjoint Rectangles 212

14 Numbers and Matrices 214


14.1 GCD 214
14.2 Bézout Coefficients 214
14.3 Binomial Coefficients 215
14.4 Fast Exponentiation 216
14.5 Prime Numbers 217
14.6 Evaluate an Arithmetical Expression 218
viii Contents

14.7 System of Linear Equations 221


14.8 Multiplication of a Matrix Sequence 225

15 Exhaustive Search 227


15.1 All Paths for a Laser 227
15.2 The Exact Cover Problem 231
15.3 Problems 237
15.4 Sudoku 238
15.5 Enumeration of Permutations 240
15.6 Le Compte est Bon 243

16 Conclusion 245
16.1 Combine Algorithms to Solve a Problem 245
16.2 For Further Reading 245
16.3 Rendez-vous on tryalgo.org 246

Debugging tool 247


References 248
Index 251
Preface

Algorithms play an important role in our society, solving numerous mathematical


problems which appear in a broad spectrum of situations. To give a few examples,
think of planning taxi routes given a set of reservations (see Section 9.12); assigning
students to schools in a large urban school district, such as New York (see Section
9.4); or identifying a bottleneck in a transportation network (see Section 9.8). This
is why job interviews in the IT (Information Technology) industry test candidates for
their problem-solving skills. Many programming contests are organised by companies
such as Google, Facebook and Microsoft to spot gifted candidates and then send
them job offers. This book will help students to develop a culture of algorithms and
data structures, so that they know how to apply them properly when faced with new
mathematical problems.
Designing the right algorithm to solve a given problem is only half of the work;
to complete the job, the algorithm needs to be implemented efficiently. This is why
this book also emphasises implementation issues, and provides full source code for
most of the algorithms presented. We have chosen Python for these implementations.
What makes this language so enticing is that it allows a particularly clear and refined
expression, illustrating the essential steps of the algorithm, without obscuring things
behind burdensome notations describing data structures. Surprisingly, it is actually
possible to re-read code written several months ago and even understand it!
We have collected here 128 algorithmic problems, indexed by theme rather than
by technique. Many are classic, whereas certain are atypical. This work should
prove itself useful when preparing to solve the wide variety of problems posed in
programming contests such as ICPC, Google Code Jam, Facebook Hacker Cup,
Prologin, France-ioi, etc. We hope that it could serve as a basis for an advanced
course in programming and algorithms, where even certain candidates for the
‘agrégation de mathématiques option informatique’ (French competitive exam for
the highest teacher’s certification) will find a few original developments. The website
tryalgo.org, maintained by the authors, contains links to the code of this book, as
well as to selected problems at various online contests. This allows readers to verify
their freshly acquired skills.
This book would never have seen the light of day without the support of the
authors’ life partners. Danke, Hương. Merci, 智子. The authors would also like to
thank the students of the École polytechnique and the École normale supérieure
of Paris-Saclay, whose practice, often nocturnal, generated a major portion of the
x Preface

material of this text. Thanks to all those who proofread the manuscript, especially
René Adad, Evripidis Bampis, Binh-Minh Bui-Xuan, Stéphane Henriot, Lê Thành
Dũng Nguyễn, Alexandre Nolin and Antoine Pietri. Thanks to all those who improved
the programs on GitHub: Louis Abraham, Lilian Besson, Ryan Lahfa, Olivier Marty,
Samuel Tardieu and Xavier Carcelle. One of the authors would especially like to thank
his past teacher at the Lycée Thiers, Monsieur Yves Lemaire, for having introduced
him to the admirable gem of Section 2.5 on page 52.
We hope that the reader will pass many long hours tackling algorithmic problems
that at first glance appear insurmountable, and in the end feel the profound joy when
a solution, especially an elegant solution, suddenly becomes apparent.
Finally, we would like to thank Danièle and Greg Gibbons for their translation of
this work, even of this very phrase.
Attention, it’s all systems go!
1 Introduction

You, my young friend, are going to learn to program the algorithms of this book,
and then go on to win programming contests, sparkle during your job interviews,
and finally roll up your sleeves, get to work, and greatly improve the gross national
product!

Mistakenly, computer scientists are still often considered the magicians of modern
times. Computers have slowly crept into our businesses, our homes and our machines,
and have become important enablers in the functioning of our world. However, there
are many that use these devices without really mastering them, and hence, they do not
fully enjoy their benefits. Knowing how to program provides the ability to fully exploit
their potential to solve problems in an efficient manner. Algorithms and programming
techniques have become a necessary background for many professions. Their mastery
allows the development of creative and efficient computer-based solutions to problems
encountered every day.
This text presents a variety of algorithmic techniques to solve a number of classic
problems. It describes practical situations where these problems arise, and presents
simple implementations written in the programming language Python. Correctly
implementing an algorithm is not always easy: there are numerous traps to avoid and
techniques to apply to guarantee the announced running times. The examples in the
text are embellished with explanations of important implementation details which
must be respected.
For the last several decades, programming competitions have sprung up at every
level all over the world, in order to promote a broad culture of algorithms. The prob-
lems proposed in these contests are often variants of classic algorithmic problems,
presented as frustrating enigmas that will never let you give up until you solve them!

1.1 Programming Competitions

In a programming competition, the candidates must solve several problems in a


fixed time. The problems are often variants of classic problems, such as those
addressed in this book, dressed up with a short story. The inputs to the problems
are called instances. An instance can be, for example, the adjacency matrix of a graph
for a shortest path problem. In general, a small example of an instance is provided,
along with its solution. The source code of a solution can be uploaded to a server via
2 Introduction

a web interface, where it is compiled and tested against instances hidden from the
public. For some problems the code is called for each instance, whereas for others the
input begins with an integer indicating the number of instances occurring in the input.
In the latter case, the program must then loop over each instance, solve it and display
the results. A submission is accepted if it gives correct results in a limited time, on the
order of a few seconds.

Figure 1.1 The logo of the ICPC nicely shows the steps in the resolution of a problem.
A helium balloon is presented to the team for each problem solved.

To give here a list of all the programming competitions and training sites is quite
impossible, and such a list would quickly become obsolete. Nevertheless, we will
review some of the most important ones.

ICPC The oldest of these competitions was founded by the Association for
Computing Machinery in 1977 and supported by them up until 2017. This
contest, known as the ICPC, for International Collegiate Programming Contest,
is organised in the form of a tournament. The starting point is one of the regional
competitions, such as the South-West European Regional Contest (SWERC),
where the two best teams qualify for the worldwide final. The particularity of
this contest is that each three-person team has only a single computer at their
disposal. They have only 5 hours to solve a maximum number of problems
among the 10 proposed. The first ranking criterion is the number of submitted
solutions accepted (i.e. tested successfully against a set of unknown instances).
The next criterion is the sum over the submitted problems of the time between
the start of the contest and the moment of the accepted submission. For each
erroneous submission, a penalty of 20 minutes is added.
There are several competing theories on what the ideal composition of a
team is. In general, a good programmer and someone familiar with algorithms
is required, along with a specialist in different domains such as graph theory,
dynamic programming, etc. And, of course, the team members need to get along
together, even in stressful situations!
For the contest, each team can bring 25 pages of reference code printed in an
8-point font. They can also access the online documentation of the Java API and
the C++ standard library.
Google Code Jam In contrast with the ICPC contest, which is limited to students
up to a Master’s level, the Google Code Jam is open to everyone. This more
recent annual competition is for individual contestants. Each problem comes in
1.1 Programming Competitions 3

general with a deck of small instances whose resolution wins a few points, and
a set of enormous instances for which it is truly important to find a solution
with the appropriate algorithmic complexity. The contestants are informed of
the acceptance of their solution for the large instances only at the end of the
contest. However, its true strong point is the possibility to access the solutions
submitted by all of the participants, which is extremely instructive.
The competition Facebook Hacker Cup is of a similar nature.
Prologin The French association Prologin organises each year a competition
targeted at students up to twenty years old. Their capability to solve algorithmic
problems is put to test in three stages: an online selection, then regional
competitions and concluding with a national final. The final is atypically an
endurance test of 36 hours, during which the participants are confronted with a
problem in Artificial Intelligence. Each candidate must program a “champion”
to play a game whose rules are defined by the organisers. At the end of the
day, the champions are thrown in the ring against each other in a tournament to
determine the final winner.
The website https://prologin.org includes complete archives of past
problems, with the ability to submit algorithms online to test the solutions.
France-IOI Each year, the organisation France-IOI prepares junior and senior
high school students for the International Olympiad in Informatics. Since
2011, they have organised the ‘Castor Informatique’ competition, addressed at
students from Grade 4 to Grade 12 (675,000 participants in 2018). Their website
http://france-ioi.org hosts a large number of algorithmic problems (more
than 1,000).

Numerous programming contests organised with the goal of selecting candidates


for job offers also exist. The web site www.topcoder.com, for example, also includes
tutorials on algorithms, often very well written.
For training, we particularly recommend https://codeforces.com, a well-
respected web site in the community of programming competitions, as it proposes
clear and well-prepared problems.

1.1.1 Training Sites


A number of websites propose problems taken from the annals of competitions, with
the possibility to test solutions as a training exercise. This is notably the case for
Google Code Jam and Prologin (in French). The collections of the annals of the ICPC
contests can be found in various locations.
Traditional online judges The following sites contain, among others, many
problems derived from the ICPC contests.
uva http://uva.onlinejudge.org
icpcarchive http://icpcarchive.ecs.baylor.edu, http://livearchive
.onlinejudge.org
4 Introduction

Chinese online judges Several training sites now exist in China. They tend to
have a purer and more refined interface than the traditional judges. Nevertheless,
sporadic failures have been observed.
poj http://poj.org
tju http://acm.tju.edu.cn (Shut down since 2017)
zju http://acm.zju.edu.cn
Modern online judges Sphere Online Judge http://spoj.com and Kattis
http://open.kattis.com have the advantage of accepting the submission
of solutions in a variety of languages, including Python.
spoj http://spoj.com
kattis http://open.kattis.com
zju http://acm.zju.edu.cn
Other sites
codechef http://codechef.com
codility http://codility.com
gcj http://code.google.com/codejam
prologin http://prologin.org
slpc http://cs.stanford.edu/group/acm
Throughout this text, problems are proposed at the end of each section in rela-
tion to the topic presented. They are accompanied with their identifiers to a judge
site; for example [spoj:CMPLS] refers to the problem ‘Complete the Sequence!’ at
the URL www.spoj.com/problems/CMPLS/. The site http://tryalgo.org contains
links to all of these problems. The reader thus has the possibility to put into practice
the algorithms described in this book, testing an implementation against an online
judge.
The languages used for programming competitions are principally C++ and Java.
The SPOJ judge also accepts Python, while the Google Code Jam contest accepts
many of the most common languages. To compensate for the differences in execution
speed due to the choice of language, the online judges generally adapt the time limit
to the language used. However, this adaptation is not always done carefully, and it is
sometimes difficult to have a solution in Python accepted, even if it is correctly written.
We hope that this situation will be improved in the years to come. Also, certain judges
work with an ancient version of Java, in which such useful classes as Scanner are
not available.

1.1.2 Responses of the Judges


When some code for a problem is submitted to an online judge, it is evaluated via a set
of private tests and a particularly succinct response is returned. The principal response
codes are the following:
1.2 Python in a Few Words 5

Accepted Your program provides the correct output in the allotted time. Congrat-
ulations!
Presentation Error Your program is almost accepted, but the output contains
extraneous or missing blanks or end-of-lines. This message occurs rarely.
Compilation Error The compilation of your program generates errors. Often,
clicking on this message will provide the nature of the error. Be sure to compare
the version of the compiler used by the judge with your own.
Wrong Answer Re-read the problem statement, a detail must have been over-
looked. Are you sure to have tested all the limit cases? Might you have left
debugging statements in your code?
Time Limit Exceeded You have probably not implemented the most efficient
algorithm for this problem, or perhaps have an infinite loop somewhere. Test
your loop invariants to ensure loop termination. Generate a large input instance
and test locally the performance of your code.
Runtime Error In general, this could be a division by zero, an access beyond the
limits of an array, or a pop() on an empty stack. However, other situations can
also generate this message, such as the use of assert in Java, which is often not
accepted.
The taciturn behaviour of the judges nevertheless allows certain information to be
gleaned from the instances. Here is a trick that was used during an ICPC / SWERC
contest. In a problem concerning graphs, the statement indicated that the input con-
sisted of connected graphs. One of the teams doubted this, and wrote a connectivity
test. In the positive case, the program entered into an infinite loop, while in the negative
case, it caused a division by zero. The error code generated by the judge (Time Limit
Exceeded ou Runtime Error) allowed the team to detect that certain graphs in the input
were not connected.

1.2 Python in a Few Words

The programming language Python was chosen for this book, for its readability and
ease of use. In September 2017, Python was identified by the website https://
stackoverflow.com as the programming language with the greatest growth in high-
income countries, in terms of the number of questions seen on the website, notably
thanks to the popularity of machine learning.1 Python is also the language retained
for such important projects as the formal calculation system SageMath, whose critical
portions are nonetheless implemented in more efficient languages such as C++ or C.
Here are a few details on this language. This chapter is a short introduction to
Python and does not claim to be exhaustive or very formal. For the neophyte reader
we recommend the site python.org, which contains a high-quality introduction as
well as exceptional documentation. A reader already familiar with Python can profit

1 https://stackoverflow.blog/2017/09/06/incredible-growth-python/
6 Introduction

enormously by studying the programs of David Eppstein, which are very elegant and
highly readable. Search for the keywords Eppstein PADS.
Python is an interpreted language. Variable types do not have to be declared, they
are simply inferred at the time of assignment. There are neither keywords begin/end
nor brackets to group instructions, for example in the blocks of a function or a loop.
The organisation in blocks is simply based on indentation! A typical error, difficult
to identify, is an erroneous indentation due to spaces used in some lines and tabs
in others.

Basic Data Types


In Python, essentially four basic data types exist: Booleans, integers, floating-point
numbers and character strings. In contrast with most other programming languages,
the integers are not limited to a fixed number of bits (typically 64), but use an arbi-
trary precision representation. The functions—more precisely the constructors: bool,
int, float, str—allow the conversion of an object to one of these basic types. For
example, to access the digits of a specific integer given its decimal representation,
it can be first transformed into a string, and then the characters of the string can be
accessed. However, in contrast with languages such as C, it is not possible to directly
modify a character of a string: strings are immutable. It is first necessary to convert to
a list representation of the characters; see below.

Data Structures
The principal complex data structures are dictionaries, sets, lists and n-tuples. These
structures are called containers, as they contain several objects in a structured manner.
Once again, there are functions dict, set, list and tuple that allow the conversion of
an object into one of these structures. For example, for a string s, the function list(s)
returns a list L composed of the characters of the string. We could then, for example,
replace certain elements of the list L and then recreate a string by concatenating the ele-
ments of L with the expression ‘’.join(L). Here, the empty string could be replaced
by a separator: for example, ‘-’.join([’A’,’B’,’C’]) returns the string “A-B-C”.

1.2.1 Manipulation of Lists, n-tuples, Dictionaries


Note that lists in Python are not linked lists of cells, each with a pointer to its successor
in the list, as is the case in many other languages. Instead, lists are arrays of elements
that can be accessed and modified using their index into the array. A list is written by
enumerating its elements between square brackets [ and ], with the elements separated
by commas.

Lists The indices of a list start with 0. The last element can also be accessed with
the index −1, the second last with −2 and so on. Here are some examples of
operations to extract elements or sublists of a list. This mechanism is known as
slicing, and is also available for strings.
1.2 Python in a Few Words 7

The following expressions have a complexity linear in the length of L, with


the exception of the first, which is in constant time.
L[i] the ith element of L
L[i:j] the list of elements with indices starting at i and up to
(but not including) j
L[:j] the first j elements
L[i:] all the elements from the ith onwards
L[-3:] the last three elements of L
L[i:j:k] elements from the ith up to (but not including) the jth,
taking only every kth element
L[::2] the elements of L with even indices
L[::-1] a reverse copy of L
The most important methods of a list for our usage are listed below. Their
complexity is expressed in terms of n, the length of the list L. A function has
constant amortised complexity if, for several successive calls to it, the average
complexity is constant, even if some of these calls take a time linear in n.
len(L) returns the number of elements of the list L O(1)
sorted(L) returns a sorted copy of the list L O(n log n)
L.sort() sorts L in place O(n log n)
L.count(c) the number of occurrences of c in L O(n)
c in L is the element c found in L? O(n)
L.append(c) append c to the end of L amortised O(1)
L.pop() extracts and returns the last element of L amortised O(1)
Thus a list has all the functionality of a stack, defined in Section 1.5.1 on
page 20.
n-tuple An n-tuple behaves much like a list, with a difference in the usage
of parentheses to describe it, as in (1, 2) or (left, ’X’, right). A 1-tuple,
composed of only one element, requires the usage of a comma, as in (2,).
A 0-tuple, empty, can be written as (), or as tuple(), no doubt more readable.
The main difference with lists is that n-tuples are immutable, just like strings.
This is why an n-tuple can serve as a key in a dictionary.
Dictionaries Dictionaries are used to associate objects with values, for example
the words of a text with their frequency. A dictionary is constructed as
comma-separated key:value pairs between curly brackets, such as {’the’: 4,
’bread’: 1, ’is’: 6}, where the keys and values are separated by a colon.
An empty dictionary is obtained with {}. A membership test of a key x in a
dictionary dic is written x in dic. Behind a dictionary there is a hash table,
hence the complexity of the expressions x in dic, dic[x], dic[x] = 42
is in practice constant time, even if the worst-case complexity is linear,
a case obtained in the improbable event of all keys having the same hash
value.
If the keys of a dictionary are all the integers between 0 and n − 1, the use of
a list is much more efficient.
8 Introduction

A loop in Python is written either with the keyword for or with while. The nota-
tion for the loop for is for x in S:, where the variable x successively takes on the
values of the container S, or of the keys of S in the case of a dictionary. In contrast,
while L: will loop as long as the list L is non-empty. Here, an implicit conversion of
a list to a Boolean is made, with the convention that only the empty list converts to
False.
At times, it is necessary to handle at the same time the values of a list along with
their positions (indices) within the list. This can be implemented as follows:

for index in range(len(L)):


value = L[index]
# ... handling of index and value

The function enumerate allows a more compact expression of this loop:

for index, value in enumerate(L):


# ... handling of index and value

For a dictionary, the following loop iterates simultaneously over the keys and
values:

for key, value in dic.items():


# ... handling of key and value

1.2.2 Specificities: List and Dictionary Comprehension, Iterators


List and Dictionary Comprehension
The language Python provides a syntax close to the notation used in mathematics for
certain objects. To describe the list of squares from 0 to n2 , it is possible to use a list
comprehension:

>>> n = 5
>>> squared_numbers = [x ** 2 for x in range(n + 1)]
>>> squared_numbers
[0, 1, 4, 9, 16, 25]

which corresponds to the set {x 2 |x = 0, . . . ,n} in mathematics.


This is particularly useful to initialise a list of length n:

>>> t = [0 for _ in range(n)]


>>> t
[0, 0, 0, 0, 0]
1.2 Python in a Few Words 9

or to initialise counters for the letters in a string:

>>> my_string = "cowboy bebop"


>>> nb_occurrences = {letter: 0 for letter in my_string}
>>> nb_occurrences
{’c’: 0, ’o’: 0, ’w’: 0, ’b’: 0, ’y’: 0, ’ ’: 0, ’e’: 0, ’p’: 0}

The second line, a dictionary comprehension, is equivalent to the following:

nb_occurrences = {}
for letter in my_string:
nb_occurrences[letter] = 0

Ranges and Other Iterators


To loop over ranges of integers, the code for i in range(n): can be used to run over
the integers from 0 to n − 1. Several variants exist:

range(k, n) from k to n − 1
range(k, n, 2) from k to n − 1 two by two
range(n - 1, -1, -1) from n − 1 to 0 (−1 excluded) in decreasing order.

In early versions of Python, range returned a list. Nowadays, for efficiency, it


returns an object known as an iterator, which produces integers one by one, if and
when the for loop claims a value. Any function can serve as an iterator, as long
as it can produce elements at different moments of its execution using the keyword
yield. For example, the following function iterates over all pairs of elements of a
given list:.

def all_pairs(L):
n = len(L)
for i in range(n):
for j in range(i + 1, n):
yield (L[i], L[j])

1.2.3 Useful Modules and Packages


Modules
Certain Python objects must be imported from a module or a package with the
command import. A package is a collection of modules. Two methods can be used;
the second avoids potential naming collisions between the methods in different
modules:
10 Introduction

>>> from math import sqrt


>>> sqrt(4)
2
>>> import math
>>> math.sqrt(4)
2

math This module contains mathematical functions and constants such as log,
sqrt, pi, etc. Python operates on integers with arbitrary precision, thus there
is no limit on their size. As a consequence, there is no integer equivalent to
represent −∞ or +∞. For floating point numbers on the other hand, float(’-
inf’) and float(’inf’) can be used. Beginning with Python 3.5, math.inf (or
from math import inf) is equivalent to float(’inf’).
fractions This module exports the class Fraction, which allows computations
with fractions without the loss of precision of floating point calculations. For
example, if f is an instance of the class Fraction, then str(f) returns a string
similar to the form “3/2”, expressing f as an irreducible fraction.
bisect Provides binary (dichotomous) search functions on a sorted list.
heapq Provides functions to manipulate a list as a heap, thus allowing an element
to be added or the smallest element removed in time logarithmic in the size of
the heap; see Section 1.5.4 on page 22.
string This module provides, for example, the function ascii_lowercase, which
returns its argument converted to lowercase characters. Note that the strings
themselves already provide numerous useful methods, such as strip, which
removes whitespace from the beginning and end of a string and returns the
result, lower, which converts all the characters to lowercase, and especially
split, which detects the substrings separated by spaces (or by another separa-
tor passed as an argument). For example, “12/OCT/2018”.split(“/”) returns
[“12”, “OCT”, “2018”].

Packages
One of the strengths of Python is the existence of a large variety of code packages.
Some are part of the standard installation of the language, while others must be
imported with the shell command pip. They are indexed and documented at the web
site pypi.org. Here is a non-exhaustive list of very useful packages.

tryalgo All the code of the present book is available in a package called tryalgo
and can be imported in the following manner: pip install tryalgo.

>>> import tryalgo


>>> help(tryalgo) # for the list of modules
>>> help(tryalgo.arithm) # for a particular module

collections To simplify life, the class from collections import Counter can
be used. For an object c of this class, the expression c[x] will return 0 if x is not
1.2 Python in a Few Words 11

a key in c. Only modification of the value associated with x will create an entry
in c, such as, for example, when executing the instruction c[x] += 1. This is
thus slightly more practical than a dictionary, as is illustrated below.

>>> c = {} # dictionary
>>> c[’a’] += 1 # the key does not exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ’a’
>>> c[’a’] = 1
>>> c[’a’] += 1 # now it does
>>> c
{’a’: 2}
>>> from collections import Counter
>>> c = Counter()
>>> c[’a’] += 1 # the key does not exist, so it is created
Counter({’a’: 1})
>>> c = Counter(’cowboy bebop’)
Counter({’o’: 3, ’b’: 3, ’c’: 1, ’w’: 1, ’y’: 1, ’ ’: 1, ’e’: 1, ’p’: 1})

The collections package also provides the class deque, for double-ended
queue, see Section 1.5.3 on page 21. With this structure, elements can be added
or removed either from the left (head) or from the right (tail) of the queue. This
helps implement Dijkstra’s algorithm in the case where the edges have only
weights 0 or 1, see Section 8.2 on page 126.
This package also provides the class defaultdict, which is a dictionary that
assigns default values to keys that are yet in the dictionary, hence a generalisa-
tion of the class Counter.

>>> from collections import defaultdict


>>> g = defaultdict(list)
>>> g[’paris’].append(’marseille’) # ’paris’ key is created on the fly
>>> g[’paris’].append(’lyon’)
>>> g
defaultdict(<class ’list’>, {’paris’: [’marseille’, ’lyon’]})
>>> g[’paris’] # behaves like a dict
[’marseille’, ’lyon’]

See also Section 1.3 on page 13 for an example of reading a graph given as
input.
numpy This package provides general tools for numerical calculations involving
manipulations of large matrices. For example, numpy.linalg.solve solves
a linear system, while numpy.fft.fft calculates a (fast) discrete Fourier
transform.

While writing the code of this book, we have followed the norm PEP8, which
provides precise recommendations on the usage of blanks, the choice of names for
variables, etc. We advise the readers to also follow these indications, using, for exam-
ple, the tool pycodestyle to validate the structure of their code.
12 Introduction

1.2.4 Interpreters Python, PyPy, and PyPy3


We have chosen to implement our algorithms in Python 3, which is already over
12 years old,2 while ensuring backwards compatibility with Python 2. The principal
changes affecting the code appearing in this text concern print and division between
integers. In Python 3, 5 / 2 is equal to 2.5, whereas it gives 2 in Python 2. The integer
division operator // gives the same result for both versions. As for print, in Python 2
it is a keyword, whereas in Python 3 it is a function, and hence requires the parameters
to be enclosed by parentheses.
The interpreter of reference is CPython, and its executable is just called python.
According to your installation, the interpreter of Python 3 could be called python or
python3. Another much more efficient interpreter is PyPy, whose executable is called
pypy in version 2 and pypy3 in version 3. It implements a subset of the Python
language, called RPython, with quite minimal restrictions, which essentially allow the
inference of the type of a variable by an analysis of the source code. The inconvenience
is that pypy is still under development and certain modules are not yet available. But
it can save your life during a contest with time limits!

1.2.5 Frequent Errors


Copy
An error often made by beginners in Python concerns the copying of lists. In the
following example, the list B is in fact just a reference to A. Thus a modification of
B[0] results also in a modification of A[0].

A = [1, 2, 3]
B = A # Beware! Both variables refer to the same object

For B to be a distinct copy of A, the following syntax should be used:

A = [1, 2, 3]
B = A[:] # B becomes a distinct copy of A

The notation [:] can be used to make a copy of a list. It is also possible to make a
copy of all but the first element, A[1 :], or all but the last element, A[: −1], or even
in reverse order A[:: −1]. For example, the following code creates a matrix M, all of
whose rows are the same, and the modification of M[0][0] modifies the whole of the
first column of M.

M = [[0] * 10] * 10 # Do not write this!

2 Python 3.0 final was released on 3 December, 2008.


1.3 Input-Output 13

A square matrix can be correctly initialised using one of the following expressions:

M1 = [[0] * 10 for _ in range(10)]


M2 = [[0 for j in range(10)] for i in range(10)]

The module numpy permits easy manipulations of matrices; however, we have cho-
sen not to profit from it in this text, in order to have generic code that is easy to translate
to Java or C++.

Ranges
Another typical error concerns the use of the function range. For example, the follow-
ing code processes the elements of a list A between the indices 0 and 9 inclusive, in
order.

for i in range(0, 10): # 0 included, 10 excluded


process(A[i])

To process the elements in descending order, it is not sufficient to just swap the
arguments. In fact, range(10, 0, -1)—the third argument indicates the step—is the
list of elements with indices 10 (included) to 0 (excluded). Thus the loop must be
written as:

for i in range(9, -1, -1): # 9 included, -1 excluded


process(A[i])

1.3 Input-Output

1.3.1 Read the Standard Input


For most problems posed by programming contests, the input data are read from
standard input, and the responses displayed on standard output. For example, if the
input file is called test.in, and your program is prog.py, the contents of the input
file can be directed to your program with the following command, launched from a
command window:

python prog.py < test.in

In general, under Mac OS X, a command window can be obtained


by typing Command-Space Terminal, and under Windows, via
>_
Start → Run → cmd.
If you are running Linux, the keyboard shortcut is generally Alt-
F2, but that you probably already knew. . .
14 Introduction

If you wish to save the output of your program to a file called test.out, type:

python prog.py < test.in > test.out

A little hint: if you want to display the output at the same time as it is being written
to a file test.out, use the following (the command tee is not present by default in
Windows):

python prog.py < test.in | tee test.out

The inputs can be read line by line via the command input(), which returns the
next input line in the form of a string, excluding the end-of-line characters.3 The
module sys contains a similar function stdin.readline(), which does not suppress
the end-of-line characters, but according to our experience has the advantage of being
four times as fast!
If the input line is meant to contain an integer, we can convert the string with the
function int (if it is a floating point number, then we must use float instead). In
the case of a line containing several integers separated by spaces, the string can first be
cut into different substrings using split(); these can then be converted into integers
with the method map. For example, in the case of two integers height and width to be
read on the same line, separated by a space, the following command suffices:

import sys

height, width = map(int, sys.stdin.readline().split())

If your program exhibits performance problems while reading the inputs, our expe-
rience shows that a factor of two can be gained by reading the whole of the inputs with
a single system call. The following code fragment assumes that the inputs are made
up of only integers, eventually on multiple lines. The parameter 0 in the function
os.read means that the read is from standard input, and the constant M must be an
upper bound on the size of the file. For example, if the file contains 107 integers,
each between 0 and 109 , then as each integer is written with at most 10 characters
and there are at most 2 characters separating the integers (\n and \r), we can choose
M = 12 · 107 .

3 According to the operating system, the end-of-line is indicated by the characters \r, \n, or both, but this
is not important when reading with input(). Note that in Python 2 the behaviour of input() is
different, so it is necessary to use the equivalent function raw_input().
1.3 Input-Output 15

import os

instance = list(map(int, os.read(0, M).split()))

Example – Read a Graph on Input


If the inputs are given in the form:

3
paris tokyo 9471
paris new-york 5545
new-york singapore 15344

where 3 is the number of edges of a graph and each edge is represented by


<departure> <arrival> <distance>, then the following code, using defaultdict
to initialise the new keys in an empty dictionary, allows the construction of
the graph:

from collections import defaultdict

nb_edges = int(input())

g = defaultdict(dict)
for _ in range(nb_edges):
u, v, weight = input().split()
g[u][v] = int(weight)
# g[v][u] = int(weight) # For an undirected graph

Example—read three matrices A,B,C and test if AB = C


In this example, the inputs are in the following form: the first line contains a single
integer n. It is followed by 3n lines each containing n integers separated by spaces,
coding the values contained in three n × n matrices A,B,C, given row by row. The
goal is to test if the product A times B is equal to the matrix C. A direct approach
by matrix multiplication would have a complexity O(n3 ). However, a probabilistic
solution exists in O(n2 ), which consists in randomly choosing a vector x and testing
whether A(Bx) = Cx. This is the Freivalds test (1979). What is the probability that
the algorithm outputs equality even if AB = C? Whenever the computations are
made modulo d, the probability of error is at most 1/d. This error probability can
be made arbitrarily small by repeating the test several times. The following code has
an error probability bounded above by 10−6 .
Another Random Scribd Document
with Unrelated Content
The text on this page is estimated to be only 19.01%
accurate

Names. Fi^un- . Names. Figureb. I o In roman character.


be W lu ronifin character £ W nawassi nauwe ikkya'nwe nwe ^~j$
te'ranwe » ^ chauranwe pachchanwe chhiyanwe 91^ sattanwe'
atthanwe ninnanwe' 89 90 91 92 93 94 95 96 97 98 99 CLJ NOTE.—
The numbers above sau do sau X tin sau char sau pan sau chha sau
sat sau ath sau nan sau lakh 100 200 300 400 500 600 700 800
9009 1,000 1,00,000 one hundred proceed somewhat like the
English ones, with the exception that the conjunction is not generally
expressed, as 6k sau dlh, one hundred (and) eight etc., etc.
ORDINALS. lift pahli ^ first ^^ panchwan =fifth dusra ^ second
i^fchhataor tisra ^ third C''^ chhatwan ^gixth chautha = fourth
GtPl*' »twan ^ seventh
The text on this page is estimated to be only 21.18%
accurate

( 72 ) NOTE. —The remaining numbers are regularly


formed by adding //lj wan to the cardinals. FRACTIONAL NUMBERS.
t / / 1 pao or \ }^ * t sawa * one and a quartchauthai/= quarter. er
tihai _ one-third /&/) derh — one and a half s * adha ^ half (jk^
paun or| -. three- yl) " ' I ^1 pauna J quarters fH^j^ w // . arhai or
1 dhai J ' sarhe two and a half one half more paune — a quarter less
NOTE. — It should be pointed out ih&tpaune 9 sawd and xarhe,
fractional numbers, have a peculiar use which will be useful for
students to mention here, namely, paune, when prefixed to a •+ V
number, signifies " a quarter less " than that number, sawa, " a
quarter more, '' and sarhe, one half more. As pavnc-do' means orjpe
quarter less than two, i.e., one and three quarters ; sawa ath means
eight and-a- quarter ; safhe ath means eight and-a-half etc.^ etc.
The fractional number sarhe, signifying one half more, will always he
prefixed to a number after three and never to one or two. For
instance, u one quarter and-a-half" means derh and not sarke-ek
etc. etc. * Distributives are formed by doubling the number, as af/t
ath eight by eight. A doubtful number is expressed by adding ^ilefc
to the number, & ek ddmi, means " about twenty men."
The text on this page is estimated to be only 15.17%
accurate

( 73 ) .SYNONYMS. Urdi word The same in roman character.


English meaning. Synonyms in roman character. V' Khuda Qod allah,
ilahi, khaliq, haq, khudawand, kirdigar, ban, and parwairdigar <£% j
aim at aeaven firdaus^ bahisht^ baikunth, surag 7 j9) dozakh hell
jahannam^ narakh ^ £uraj chand • sun moon shamsj aftab,
khurshid, naiyar qamar, mah, mahtab, O*t barq lightning bijU u^
ba'dal clouds. * V / abr, ghata V** patthar stone sang ji Li origin
bekh, jar, bunyad £p ehakb branch * / / / tahni, dali ^ baghban r /
sirhi gardener ladder mali / * zina gali street > kucha £ shaakat bafiz
pomp watchman shan, dabdaba, martaba, ra^b nigahban, talaya^
pasban :t/f/ .%/<, *• daulat wealth sarwat, hashmat, mal J& r&qim
writer katib, moha*irir, dabir, DRwesinda <-r ..r, / /. / hkhnewala.
The text on this page is estimated to be only 14.56%
accurate

(74 ) Urdu word. The same in roman character. English


meaning. Synonyms in romau character. >* kh£t letter morasala,
ruqqa, shuqqa, navishta, arzi, ariza, nama, chitthi, , . maktub &j
'urqat separation judai, duri, hijrat. fira'q />$ /, ." zahir known. ayan,
fash, ashkar, shae & ihmaq fool kaudan, sadahlauh, bewaquf, jahil,
be-saliqa, ghabi, beshaur, ul-jalul, bangru nasarnajh, betamiz J* Sql
wisdom danai, fahm, firasat, danish, hosh, ziraki, hiya f* sitam
oppression zulm, bedardi, bedad, jaur, taaddi, jabr, jafaX J$ bakhil
miser khasis, laim, kanjus, shum *^» dost friend munis, anis, rafiq,
ya'r, "ghamk^war, muhib, muwafiq, mehrban, mu'qa^ratb, shafiq,
mashuq, sathi A gnr»ah, sin jufrn, isyaB, khata, qasur, taqsir. ilzam '
r
The text on this page is estimated to be only 14.81%
accurate

Urd wore The aam in roma characte English meaning


Synonyms in roman character. » *4* shujaat, bravery bahadaifi,
dileri, dilawari, marda^igi, jasarat, jurat ufc marz sickness bimari,
ranjuri, kasl-mandi, rog, •'i juda ajezi separate humility alalat,
mandgi alehda, alag, niyara , / , / / r ^ /, J r.~/.' bechargi, farotni,
inkisari, majburi, hilm, nachari, bekasi, minnat fc*s I charwah'a
shephard gadarya, gal le ban, chaupan, shaban ^»- ^^* mofena
inspection mulaheza^ mushahida, dekhna .. 44 sabqat surpassing
peshqadmi, bartari, fiuqiyat, ^ / tarjih * X ijazat permission rukhsat,
chhutti, parwangi /•£, mashhur famous namwar^ nami, maaruf " 'r '
J^ ^ moti mahfil pearl meeting gauhar, dur, murwarid, lulu rnajlis,
anjuman, panchayat, mausuf celebrated bazm, majmaa mamduh,
mahmud, muttasif mash- "I warah^ advice • / ./ / • / salah, tadbir,
tajwiz,
The text on this page is estimated to be only 14.95%
accurate

Urdu word. The same in roman character, English meaning.


Synonyms in roman character. maqsad iradah nafarmani taqat •*
itaat dosti bura lalach / *» ftkhir, tobfa chhati mazbufc design
intention insubordination power obedience friendship matlab,
muracl, mansiiba azm, qasd, himmat baghawat, sarkashi, balwa
quwwat, qudrat, rnajal, zor, tawanai, daetras, tab, bal tabedari,
farmanbardari, bandagi, parastish, ibadat bad avarice end gift chest
strong ulfat, mua'feqat, sadaqat, mohabbat, ittehad, ikhlas, ikhtalat /
/ - . . / / / yan, uns, yaganagi kari'h, khabis, shaita'n, sharir, bad,
badzat, badmash^, badcbalau hirs, ha was, tamaa, laawa ikhtatam^
khatam, arjjam, khate^ ma ^ . / 8augha% hadya, peshl<5sh^ atiya
paedar, iDUstahkamj qawj, sakbt
The text on this page is estimated to be only 13.41%
accurate

Urdu word. The same in roman character. English meaning.


Synonyms in roman character. £ • - •' ' kaunoa mean „ / -V ' razil,
sifta, kamin * ** L?^ ghussa anger qahr, atab, libashm^ ghaiz,
ghazab, kiiafgi, narazi, taTsh tj/ gharana dynasty qabila, kha'ndan,
qaum J\f hal condition kaifyat, majra, waqe'a, hadsa. sarguzasbt (ft j
an gal forest sahra, bayaban, dasht, wadi, besba tf mewah fruit bar,
samar (SV. Hba's clothes paushak, pairahan, poshish, v' taur way
qaeda, watira', tarz, ahewa, rab . J dastur J> malul sad ghamgin^
udas^ magbmooin, ranjida' v de'r delay tawaqquf, dhil, ta'^bir,
waqfa' # bairan perplexed shashdar, hakka-bakka, beqarar.
muztarab. / gbar bouse maaknu. makan, tnahal^ dauUtkhana,
ghnrib-khana, khana, *< qa T) iwan
The text on this page is estimated to be only 13.44%
accurate

Urdu word* The same in roman character. English meaning.


Synonyms in roman character^ c*£ mashuq beloved mahbub,
sanam, naznin, janoo9 • dila'ram, dilbar, mahwash, mahroo,
ara'mjan, mehpara »&f bads hah kirjg shah, shahr-yar, jahandar,
sliahai^shah, tajdar, khusro, khaqait. qahrman s/ tahrir writing
nawisht, kitabat, ., qalmi, {" ^ / qalil small * / tastir thora,
mukhtasar, juzwi, qadre shimma J£^ jhuth falsehood kizb, narast,
darogh, khilaf, lagbve ^f/ khauf fear dar, haul, khatr, dahshat,
haibat, , * / *• »»* *y/ hiras, daghdagha, waswasa && ifcayat k
indness Dnehibani, atefat, lutf, altaf, nawa = • • zish, shafqat
The text on this page is estimated to be only 16.10%
accurate

Urdu word. The same in roman character English meaning.


Synonyms in roman character t \f\ fath ajal conquest death jit,
riusrat, kamyabi, firozi, zafar maut, intiqal, marg, wafat, rehlat 1 *
parhez abstinence ehtaraz. ijtinab, hazar 9 gf • Ijti gharat ruin lut,
taraj, barbadi £ subuk light halka, khafif, thora >' bSkhl misery
khisasat, khjssat, kanjusi jfr majnun mad diwana, pagal, shaida,
shefta ,{JI maldar wealthy mutamauval, tawangar, amir, j ' •/**//
ghani, fareghulbal |£j ." .r ' mtiqam revenge badla, qasa«, talafij
ewaz, maawezaj pada sh, jaza -2* v »» rauqim resident rahne-wala,
sakin, sakna s \r hawa air saba, nasim jtt hakim officer rais, salar,
mehtar, wali, sardar nr chaplusi flattery tamalluq, khushamad ijy*
surakh hole chhed rozan, darar ^ khusar [husband's or sauhra ,
susra' wife's ^ father is arz request iltimas. gu/arish \*x tfuUt story
kahaDi. da^rau. hikayat uaqT
The text on this page is estimated to be only 13.11%
accurate

Urdu word. The same in rornan character. English meaning.


Synonyms in roman character* £ / / bon :arzand, pisar^ pur s ft pur
bad-bu full bad-smell jhara-him^ Jabrez, labalab i darakht tree
shttjar, nihal ^ cafs sensuality sarisht, tinat, tabiat rij^u qasid
messingar harkara, rasul, safir, jafiu^ elchi, V lasbkar army pail fauj,
sipah, jaishj hashm, jarraV A«
The text on this page is estimated to be only 11.79%
accurate

- character. bahut many khush glad roshni light khusurnat


enmity Synonyms in roman character. diasa kasir, ziyadah, nihayat,
baghayat bfsyaV, bekra'n, beqaya^ behiaob, beshumar, beendaza,
behad, kasrat, an boh shadman, razi, khursand, khurram, khushnud,
bashshash, masroor partau, shoa, ziya, tajalli, lama mukhalfat,
adawat, dashmani, hasad, nafiaiq, kina^ bughz, bad/ / khwahi
satisfaction tamaniyat, itminan, tassali, dilachchha good madndgar
helper qabi sehat grave health * " dahi, diljamai v' v ^ * / * ' »»
said, saad, munasib, thik, behtar, khub, pasindidah, afzal, ahsan
nasir, maawin, moin, dastgir, yawar got, lahad, maz^r, turbat,
mirqad tandrusti, afyat^ shife
The text on this page is estimated to be only 13.80%
accurate

( 82 Urdu word. The same in roman character. English


meaning. Synonyms in roman character. <& baseen beautiful
khubsurat, jamil, kj^ubru, wajih, basin ah Ja justice 4-1 / / insaf,
dad ur-i *•• t pidri hereditary abai, kbta^dan/, mafurusi
The text on this page is estimated to be only 15.78%
accurate

Urdu word. The same in rorimn character. English meaning.


Synonyms in roman character. * bacbcba child balak, shir-khwar,
baba V • bap father pidar, abba, bawa', pita, walid ^ bat matter
muamela, mazmuu %t badsahat kingdom shahi, saltanat, raj,
hukumat. j riyasat, badshahi ^ banjh barren aqima, bephal, usar
#*> bandi male-servant w / *• v ; / kanizak^ laundi, chhokri tit
banda tail-less be-dum, ponchh-kata, landura. (a bird) ^ bansri fife
bansli, aighoza t*$ ** / / lungara scoundrel luchcha, shohda,
badmash, badzat 9 duiL lihaza tail therefore ponchhar, ponchb isliye,
iswaste' y^ lahr wave mauj JU khayal thought wahm, soch £ nafa
profit, iaida
The text on this page is estimated to be only 18.57%
accurate

Urdu word. for* *>/ The same in rotnan character. English


Urdu The same in roman character. English meaning. utha-dena to
set up • -jana ban>ana suddenly to succeed % to become ** pi-
jana-i to drink 'r /\ i-lenaj on or up rakk-lena to lay by rakh-dena to
place to go to sleep so-rahaa C to contiso-jana c6/ o-rahaa f j
COMPOUND VERBS. lag-rahna C o continue to come 1 fixed' y-jana
to be formed sath ho-1 to go along ,/ / J lena * ra-le'na (to clasp, to
em^ brace ja-sakna' to be able to go Jtiba-chukna fto have done
nue sleept# 1 ' i " ' /I aya-karna I to ing kat-dalna to cut off kah-
dena |to speak [ out kha~}aua to eat up eating come frequently
kyft-karna /to do frequentlikha- ^ to write frekarna J quently jaji-
karna fto go frequentI'y
The text on this page is estimated to be only 14.81%
accurate

Urd wore The same „ ,. , TT , English Urdu in rornan . i ,


meaning, word. The8ame ,.. . luli in roman IJieabni character. ^^ y
9^ kho-dena fto squand- t*/i/y L er away bola-karna fto speak frrL
quently ^^j*SO Jv/ gar-den a to bury Cl^tf gir-pajna j to fall • M v
down L^>^ ^*j '• f / / / ^ gate-ana (to come singrote-rahna (to
remain weet»btf i gira-dena |^to throw l ing 1 down '^0, likba- "1 to
wish to write Clf, . sikhne- ^j to begin learn*f le-l^na fto take l^tfj^
J L bold off i^^J^m^ mar-dalna fto kill Jagna'j ing sone-dena (to
give leave v to sleep ^r ^ • ) outright ralme- ^ to leave to re±>Jt
nikal-dena to turn out denaj main w^*iy J^ ^6-jana oi\ ^J"* y y \ ^
x id-rahna | to become U/Lf dekhua- "j to see bhalnaj w ^ff -jSjJ*
baith-jana to sit down ft fa JM bolna- ^l to converse nTinlnA 1
The text on this page is estimated to be only 16.62%
accurate

Urdu word. The same in romau character English meaning.


Urdu word. The same in roman character. English meaning. &x
bujha- *> dena J bal-dena to extinguish to twist 0&JP9 n f i ihona-
^ jtx ' i dhana J to wash #¥ kahla* *| bhejna > to send word Ctytf
3hul-jana rah-jana to forget to remain be&%< V j ' / pila-dena to
give to ^ hind drink (&4 i i ~ • t ' cohip-jana to conceal .-•A
jalnabecome 'j*fCJ* bhunna enflamed (?/*"/ koshish- *J to try 'W
chhor-jani to leave Cr/ karna ^ £*&» utha-lena chun-lena to pick up
to pick up * shuru- <\ karna / to begin tyj< y ,/ / gin-lena to add up
£,$ • to remove £/*$ J ' i " f taza-karna to refresh a* maiiqui- ^
karna > to abolish. adrniyatpakarna to become civilized fa fkhJas- 1
karna j to esteem H • /, / , / / abru-lena (to take j away one's abru-
utir to diegracf honor ^ rm
The text on this page is estimated to be only 15.82%
accurate

Tnlu word The same in roman character English meaning


Urdu word The sam< in rornan character English meaning. fr chalas-
^J karna J to leave b* •* * ' -\ |tt,faq-j hona ^ to happen *\' " /W
imtiyaz -\ karna 1 to discrimi nate :& bamla- ^j W to attack again- "j
dena J i , , / / e-bhagna to comforl to run *^«f «*. r / pet-girna
pardakarnaJ. O' to miscarry x> conceal ' e-ebalna away c with 1 to
take efe • i-jalna lisab- i lena J to perplex to take an account *•
along ^M )l ) dad-lena to take revenge e-jana to carry C *' dagh- i
to brand 1s* at-parna 'o have a **}&•} j/ / i de.na J i bad ha$0>, U-
deaa to give the heart :*$ w / / / aga-dena " bit ;o put to 7j
The text on this page is estimated to be only 16.16%
accurate

Urdu word. tffc The same in Ionian character. mea Urdu


word. sbor-karna' f£o make » < L noise •fpunnat "\ karnaj to
circumcise fazul-bak- (to talk- . > „ ^t" na ^ nonsense • f khafa- *j
to become (l^J^l dant-pisna h' 'I hona J angry qubul- *) to accept
karnaj *] khara- -\ to stand Dn.'i J a jama- 1 to collect karna iaga-
rahna to be busy ^ sapurd japurd to tiand (rp^l karn'aj over £[o£ m
langar- "j to weigh ^ uthaWJ anchor *»W «* luka-lagi-J to inflame tl
The same in roman character. -r, ,. . EnShsh meanlngdam- 1 to feign
death churanaj ant-pisna fto I arhnaj -gfra-1 to ,X J gnash the te^th
dam- '\ to respire charhnaf mar-ira- to knock down uth-baith- to sit
up na J lf chhin-lena to bereave bang-dena to crow jatn-jana to
freeze phansi- \ to hang thair-jana to forbear laga-rakhna to put by
The text on this page is estimated to be only 23.56%
accurate

( 89 ) CHAPTER V. GRAMMAR. A brief, very brief, synopsis


of grammatical forms in nov needful. The student will riot, if
possible, be worried by exceptions and complexities, the motive of
this book being simply u» supply an Urdu Primer, which will readily
enable any one not conversant with the language to read and write
it with a fair degree of efficiency. All the appended items should be
committed to memory, as the words themselves, and the changes
they undergo, are parts of every day speech of the people. THE
NOUN, As in French the Urdu noun ha& no neuter gender. It is either
Masculine or Feminine. Most of them are known at once to be
Masculine or Femenine from their meaning, ae (ghora)a horse,
/^y/fghori,) a mare, etc. It is very difSculttor a foreigner to find out
the gender of inanimate things in Urdu, we may, however, lay down
a few general rules for the guidance of the student to distinguish the
gender of an Urdu noun : — All nouns that end in I or(a)are
masculine, as ^/ fata,) 6 (tukra,) a piece, etc. la,; calamity, ^*' * a,)
world ; (*>(doa.) prayer; ^>(dawa,) medicine] I flour, /P (kapra,)
cloth, fy (tukra,) a piece, etc. Exceptions to the above rule :— |£
(bala,; calamity,
The text on this page is estimated to be only 18.52%
accurate

( 90 ) (haVa,) air; (j^; (parwa,) care and ^y(p4i*»)


worship. These nouns, though end in, /or (a) are feminine. • All
nouns that terminate in (£ ^ and (JT are mostly Feminine, as /If
(choti,) curl, ^^(haldi,) turmeric ; ^ J» (maut,) death; t£t (mat,)
defeat. &lf (zat,) caste; r*?/ (kosbJsb,)endeavour ^/l/U-£(sifarish,)
recommendation, etc. The following woi ds, though, end in (£ A and
(Jf » * . < ft are of the Masculine Gender : — £Jy(moti,) pearl, /y*
(£*}*) clarified-butter, if^\s (qazi,) judge ; /£/^y Cpujari,)
worshipper, t (panij water; /? (ji,) heart ; ^/(dahi,) curdled-milk ;
Cdant,) tooth; ^J^/Ckhe't,) field ; 4^(l)akht,) destiny; jJ^C^
(darakht,) tree; J^> (dast,) hand ; £+5 ^ * (takht,) throne \(J*$)
(do$hj) shoulder; //^ (farsh,) floor; • ^ ' y^^y^ (khargoshj) hare ;
/yy (josh,)pa€3ion. The gender of nouns that terminate in other
letters must be learnt by practice. THE CASE. In English the case of
a noun is denoted by its position either before or after a verb or it is
governed by a preposition. In Urdu the cases are based more upon
the Latin and Greek methods of declension, and the inflected cases
are shown by syllables added to the end of the noun itself. Thus :—
The text on this page is estimated to be only 20.56%
accurate

SINGULAR. Nominative >/* mard man Genenitive IT*/*


mard k£ of man Dative •))* mard ko to man Accusative >/* fmaid
>/• tma Ablative Locative jnard KOJ man mard se from man mard
men • in man mard par on man mard tak up to man mard ne by
man Three of the above cases require some distinctive notes. The "
/ " genetive formed by adding ka to the root is also very freu t» K i »
quintly inflected into ke and ki because the genetive case in Urdu
agrees with the gender or case of the noun which follows it. Henoe
ghora, a horse ; being mascubne, if you wish to say. " the man's
horse, " (the horse of the man) it will be (mard kaghoraj But "the
man's book" will be w (mard ki kitab^becauae " kitab" is feminine.
Again " The woman's house," is JTp w/y' aurat kax ghar, because
"ghar " is masculine. The remaining particle is ke. This is used when
the ma$. ouline noun governed is inflected, thus :— " to man's son "
(to the son of the man) becomes /^^ « .» mard ke be'te ko'. •» • Jr
ll
The text on this page is estimated to be only 21.25%
accurate

( 92 ) / When the second or governed noun is feminine in


all cases " ki" ie need, thus : — (from the man's daughter) is ^ ^
/<~[ tl *S mard ki beii se. Keis a]go used when the governed noun
is plural, thus :•— -(the man's horses) is ^^>y» £^ (iy\ admi ke
ghore. The accusative case may have the forms of the nominative or
dative. It is difficult to state simply the exact usage in this matter,
which rnusfc be learnt only by practice. The accusative case
generally has the nominative form, because "kow is not flow
oommooly used, as \£) /£ )\ ^J[l ^~if* main-ne ek , S «* ** to *S*
admi dekha, or^/^/^^j^/r4 mafn-ne ek admi ko dekha. I saw a
man. The former is the conversational form, and the latter is not a
geoeral manner of speaking. The foregaicg sentence biings us to the
third important case namely, the Agentive. This is so frequently u«ed
in speech and writing by the Datives of India that it largely usurps
the place of the EugHsh nominative* It cannot be used in the
present tense, but is the almost invariable form in trie Past, Peifect,
Pluperfect and Past Dubious, tenses. For instance, I struck him,
reads, main ne use rnara or inverted " He was struck by me." This,
however, must not be allowed & lead to confusion. Ifc will be easier
far the students to (t « ,* 0 „ /> " , " regard main, ham, wuh. I, we,
he, she, it (nominatives) as the correct forms in the present and
future tenses, and main-ne, ham 
The text on this page is estimated to be only 18.13%
accurate

ne, unhon-ne by me, by u^ by them (Agentives) as having


the same significance in the Past, Perfect, Pluperfect, and Past
Dubious tenses. Other examples :— )?? l
The text on this page is estimated to be only 18.53%
accurate

( 94 ) Singular nouns ending in / or 9 form the nominative


plural (( ,jj , u^S „ x by changing these letters into £***' ye
or(e)thus IP kutta, _ kutte, dogs, a bandah, slave, £-~f bande,
slaves. The nominative plural of feminine nouns is formed by adding
en to the singular, thus : — £^f aiirat, woman ; (J* j? -"/ »/ ' * f */ -
/ „ auraten, women ; wLf kitab, book ; /yt Lf ( kitaben, books. ^ S
^^* '^ * Feminine nouns ending iii^/or " i " form their nominativ^
plurals by adding £)lsian to the singular, as /A/ larki, girl There are,
however, several exceptions, but the foregoing rules will suffice for
this primary work. THE ADJECTIVE. Adjectives ending in jor a agree
with their nouns in number and gender, thus, //?/ 4zC^! <*k
achchha admi ; a good man, */« * ** (jy\&J achche admi ; good
men, w$/Cj bari kitab, a large book, ^i^Y^ bari kita'be'n ; large
books. It must be borne in mind that only adjectives ending, in| or a
form their plurals into ^L~~ or e, the others remain same when
used with both numbers, as $ *J(* s»f larka^ a clean boy, saf larke^
clean boys, etc., etc.
The text on this page is estimated to be only 20.38%
accurate

PRONOUNS. The Pronouns, being such important and


commonly used parts of speech, must be set forth at some length.
In common with the methods of most languages they are irregularly
declined, and must be learat accurately. PERSONAL PRONOUNS. The
personal pronouns which are main; I ; tu, thou ; and wub, he, she
or it ; with their plurals ham, we ; turn, you ; and we, ttiey. . They
are declined thus : — FIRST PERSON. Singular. X Lj£ main , j^
mujhe, me . jfclC mujhko, to me -,&• mujh-se, from me j f^/%tff
mujhme'n, in me Loc I /*& m«jn Par, on me L T .f i* Plural. ham, we
hainara', ha mare', our hamari, 4/ / hamen, us or hamko', to us ham
se', from us bam meX ic us ham par, on us
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