SlideShare a Scribd company logo
1 of 29
Exercise: simple list creation
1 Ask the user to enter an integer, n
Create a list of integers from 0 to n-1
Print this list
2
3
Solution
n =int(input())
x =list(range(n))
print(x)
Exercise: more list creation
1 Ask the user to enter an integer, n
Store the square of all the odd numbers less than
n in a list
Print this list
2
3
Solution
n =int(input())
result = []
for i in range(1, n, 2):
result.append(i*i)
print(result)
Exercise: tuple creation
1 Ask the user to enter an integer, n
Store the square of all the odd numbers less than
n
Print a tuple of this list
2
3
Solution
n =int(input())
result = []
for i in range(1, n, 2):
result.append(i*i)
print(tuple(result))
Hint: string to list/tuple
Here is an easy way to convert a string to a list of
characters.
Try this:
In []: x =’hello’
In []:print(list(x))
In []:print(tuple(x))
Exercise: list of Fibonacci
1 Ask the user to enter an integer, n(≥ 1)
2 Store the first n numbers of the Fibonnaci series in
a list
Print this list
3
Solution
n =int(input()) a, b = 0,
1
result = [0]
for I in range(n-1):
result.append(b)
a, b = b, a+b
print(result)
Exercise: square a list of integers
1 Ask the user to enter a list of integers separated by
spaces
Convert this into a list of integers but square each
element
Print this list
2
3
For example, if the user enters 1 2 3 4, print:
[1, 4, 9, 16]
Solution
text =input()
result = []
for item in text.split():
x =int(item)
result.append(x*x)
print(result)
Exercise: list of tuples
1 Ask the user to enter a list of integers separated by
spaces
Convert this into a list of integers but square each
element
Store the integer and its square in a tuple, put this
into a list
Print this list
2
3
4
For example, if the user enters 1 2 3 4, print:
[(1, 1), (2, 4), (3, 9), (4, 16)]
Solution
text =input()
result = []
for item in text.split():
x =int(item)
result.append((x, x*x))
print(result)
Hint: iterating over a list of tuples
Consider the following code:
In []: data = [(1, 1), (2, 4), (3, 9), (4,
16)]
We can iterate over this as follows:
In []:for x, y in data:
.....:print(x, y)
Exercise: list methods
1 Ask the user to enter a string
Convert this into a list of characters
Sort this list in ascending order
Now eliminate any repeated values in this list
Print this list
2
3
4
5
For example, if the user enters hello, print:
[’e’,’h’,’l’,’o’]
Solution
text =input()
chars =list(text)
chars.sort()
result = []
for c in chars:
if c not in result:
result.append(c)
print(result)
Another solution
text =input()
chars =set(text)
chars =list(chars)
chars.sort()
print(chars)
Another solution
chars =set(input())
print(sorted(chars))
Exercise: simple dictionaries
1 Ask the user for a list of integers separated by
spaces
For each integer, store the string version as the
key and the square of the integer value as the
value in a dictionary.
Print the resulting dictionary
2
3
For example if the user enters "1 3 5", print:
{’1’: 1,’3’: 9,’5’: 25}
Hint: simply print the resulting dictionary
Solution
text =input()
d = {}
for item in text.split():
x =int(item)
d[item] = x*x
print(d)
Exercise: mapping using dicts
1 Create a mapping from 3 character month name to
month number
2 Hint: for example {’jan’: 1, ’dec’: 12}
Ask the user for a 3 character month code
lower/upper mixed
Print the month number corresponding to the
month the user entered.
3
4
For example if the user enters "Jul", print:
7
Solution
months = (’janfebmaraprmayjunjul’+
’augsepoctnovdec’).split()
month2mm = {}
for i in range(len(months)):
month2mm[months[i]] = i + 1
text =input()
mon = text[:3].lower()
print(month2mm[mon])
Aside: using enumerate example
for i, char in enumerate(’hello’):
print(i, char)
Aside: using enumerate
months = (’janfebmaraprmayjunjul’+
’augsepoctnovdec’).split()
month2mm = {}
for i, month in enumerate(months):
month2mm[month] = i + 1
#Is easier/nicer than this:
for I inrange(len(months)):
month2mm[months[i]] = i + 1
Exercise: dictionaries
1 Ask the user to enter a string
Convert this to lower case
Count the number of occurrences of each
character in the string
Hint: use a dict
Print the result in sorted order of the characters
2
3
4
5
For example, if the user enters helloo, print:
e 1
h 1
l 2
o 2
Solution
text =input().lower()
result = {}
for char in text:
if char in result:
result[char] += 1
else:
result[char] = 1
for char in sorted(result):
print(char, result[char])
Problem: datestring to date tuple
You are given date strings of the form “29 Jul, 2009”, or
“4 January 2008”. In other words a number, a string
and another number, with a comma sometimes
separating the items.
Write a program that takes such a string as input and
prints a tuple (yyyy, mm, dd) where all three elements
are ints.
Solution
months = (’janfebmaraprmayjunjul’+
’augsepoctnovdec’).split()
month2mm = {}
for i, month in enumerate(months):
month2mm[month] = i + 1
date =input()
date = date.replace(’,’,’’) day, month,
year = date.split()
dd, yyyy =int(day),int(year)
mon = month[:3].lower()
mm = month2mm[mon] print((yyyy,
mm, dd))
FOSSEE Team (FOSSEE – IITB) Basic Python 30 / 31
That’s all folks!
FOSSEE Team (FOSSEE – IITB) Basic Python 31 / 31

More Related Content

Similar to Practice_Exercises_Data_Structures.pptx

Similar to Practice_Exercises_Data_Structures.pptx (20)

Pytho lists
Pytho listsPytho lists
Pytho lists
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Data Handling
Data Handling Data Handling
Data Handling
 
Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHON
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
 
Function Analysis v.2
Function Analysis v.2Function Analysis v.2
Function Analysis v.2
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
 

More from Rahul Borate

Unit 4_Introduction to Server Farms.pptx
Unit 4_Introduction to Server Farms.pptxUnit 4_Introduction to Server Farms.pptx
Unit 4_Introduction to Server Farms.pptx
Rahul Borate
 
Unit 3_Data Center Design in storage.pptx
Unit  3_Data Center Design in storage.pptxUnit  3_Data Center Design in storage.pptx
Unit 3_Data Center Design in storage.pptx
Rahul Borate
 
UNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptxUNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptx
Rahul Borate
 
Practice_Exercises_Files_and_Exceptions.pptx
Practice_Exercises_Files_and_Exceptions.pptxPractice_Exercises_Files_and_Exceptions.pptx
Practice_Exercises_Files_and_Exceptions.pptx
Rahul Borate
 

More from Rahul Borate (20)

PigHive presentation and hive impor.pptx
PigHive presentation and hive impor.pptxPigHive presentation and hive impor.pptx
PigHive presentation and hive impor.pptx
 
Unit 4_Introduction to Server Farms.pptx
Unit 4_Introduction to Server Farms.pptxUnit 4_Introduction to Server Farms.pptx
Unit 4_Introduction to Server Farms.pptx
 
Unit 3_Data Center Design in storage.pptx
Unit  3_Data Center Design in storage.pptxUnit  3_Data Center Design in storage.pptx
Unit 3_Data Center Design in storage.pptx
 
Fundamentals of storage Unit III Backup and Recovery.ppt
Fundamentals of storage Unit III Backup and Recovery.pptFundamentals of storage Unit III Backup and Recovery.ppt
Fundamentals of storage Unit III Backup and Recovery.ppt
 
UNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptxUNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptx
 
Confusion Matrix.pptx
Confusion Matrix.pptxConfusion Matrix.pptx
Confusion Matrix.pptx
 
Unit 4 SVM and AVR.ppt
Unit 4 SVM and AVR.pptUnit 4 SVM and AVR.ppt
Unit 4 SVM and AVR.ppt
 
Unit I Fundamentals of Cloud Computing.pptx
Unit I Fundamentals of Cloud Computing.pptxUnit I Fundamentals of Cloud Computing.pptx
Unit I Fundamentals of Cloud Computing.pptx
 
Unit II Cloud Delivery Models.pptx
Unit II Cloud Delivery Models.pptxUnit II Cloud Delivery Models.pptx
Unit II Cloud Delivery Models.pptx
 
QQ Plot.pptx
QQ Plot.pptxQQ Plot.pptx
QQ Plot.pptx
 
EDA.pptx
EDA.pptxEDA.pptx
EDA.pptx
 
Module III MachineLearningSparkML.pptx
Module III MachineLearningSparkML.pptxModule III MachineLearningSparkML.pptx
Module III MachineLearningSparkML.pptx
 
Unit II Real Time Data Processing tools.pptx
Unit II Real Time Data Processing tools.pptxUnit II Real Time Data Processing tools.pptx
Unit II Real Time Data Processing tools.pptx
 
2.2 Logit and Probit.pptx
2.2 Logit and Probit.pptx2.2 Logit and Probit.pptx
2.2 Logit and Probit.pptx
 
UNIT I Streaming Data & Architectures.pptx
UNIT I Streaming Data & Architectures.pptxUNIT I Streaming Data & Architectures.pptx
UNIT I Streaming Data & Architectures.pptx
 
UNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptxUNIT I Introduction to NoSQL.pptx
UNIT I Introduction to NoSQL.pptx
 
Practice_Exercises_Files_and_Exceptions.pptx
Practice_Exercises_Files_and_Exceptions.pptxPractice_Exercises_Files_and_Exceptions.pptx
Practice_Exercises_Files_and_Exceptions.pptx
 
blog creation.pdf
blog creation.pdfblog creation.pdf
blog creation.pdf
 
Chapter I.pptx
Chapter I.pptxChapter I.pptx
Chapter I.pptx
 
Polygon Mesh.ppt
Polygon Mesh.pptPolygon Mesh.ppt
Polygon Mesh.ppt
 

Recently uploaded

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Practice_Exercises_Data_Structures.pptx

  • 1. Exercise: simple list creation 1 Ask the user to enter an integer, n Create a list of integers from 0 to n-1 Print this list 2 3
  • 3. Exercise: more list creation 1 Ask the user to enter an integer, n Store the square of all the odd numbers less than n in a list Print this list 2 3
  • 4. Solution n =int(input()) result = [] for i in range(1, n, 2): result.append(i*i) print(result)
  • 5. Exercise: tuple creation 1 Ask the user to enter an integer, n Store the square of all the odd numbers less than n Print a tuple of this list 2 3
  • 6. Solution n =int(input()) result = [] for i in range(1, n, 2): result.append(i*i) print(tuple(result))
  • 7. Hint: string to list/tuple Here is an easy way to convert a string to a list of characters. Try this: In []: x =’hello’ In []:print(list(x)) In []:print(tuple(x))
  • 8. Exercise: list of Fibonacci 1 Ask the user to enter an integer, n(≥ 1) 2 Store the first n numbers of the Fibonnaci series in a list Print this list 3
  • 9. Solution n =int(input()) a, b = 0, 1 result = [0] for I in range(n-1): result.append(b) a, b = b, a+b print(result)
  • 10. Exercise: square a list of integers 1 Ask the user to enter a list of integers separated by spaces Convert this into a list of integers but square each element Print this list 2 3 For example, if the user enters 1 2 3 4, print: [1, 4, 9, 16]
  • 11. Solution text =input() result = [] for item in text.split(): x =int(item) result.append(x*x) print(result)
  • 12. Exercise: list of tuples 1 Ask the user to enter a list of integers separated by spaces Convert this into a list of integers but square each element Store the integer and its square in a tuple, put this into a list Print this list 2 3 4 For example, if the user enters 1 2 3 4, print: [(1, 1), (2, 4), (3, 9), (4, 16)]
  • 13. Solution text =input() result = [] for item in text.split(): x =int(item) result.append((x, x*x)) print(result)
  • 14. Hint: iterating over a list of tuples Consider the following code: In []: data = [(1, 1), (2, 4), (3, 9), (4, 16)] We can iterate over this as follows: In []:for x, y in data: .....:print(x, y)
  • 15. Exercise: list methods 1 Ask the user to enter a string Convert this into a list of characters Sort this list in ascending order Now eliminate any repeated values in this list Print this list 2 3 4 5 For example, if the user enters hello, print: [’e’,’h’,’l’,’o’]
  • 16. Solution text =input() chars =list(text) chars.sort() result = [] for c in chars: if c not in result: result.append(c) print(result)
  • 17. Another solution text =input() chars =set(text) chars =list(chars) chars.sort() print(chars)
  • 19. Exercise: simple dictionaries 1 Ask the user for a list of integers separated by spaces For each integer, store the string version as the key and the square of the integer value as the value in a dictionary. Print the resulting dictionary 2 3 For example if the user enters "1 3 5", print: {’1’: 1,’3’: 9,’5’: 25} Hint: simply print the resulting dictionary
  • 20. Solution text =input() d = {} for item in text.split(): x =int(item) d[item] = x*x print(d)
  • 21. Exercise: mapping using dicts 1 Create a mapping from 3 character month name to month number 2 Hint: for example {’jan’: 1, ’dec’: 12} Ask the user for a 3 character month code lower/upper mixed Print the month number corresponding to the month the user entered. 3 4 For example if the user enters "Jul", print: 7
  • 22. Solution months = (’janfebmaraprmayjunjul’+ ’augsepoctnovdec’).split() month2mm = {} for i in range(len(months)): month2mm[months[i]] = i + 1 text =input() mon = text[:3].lower() print(month2mm[mon])
  • 23. Aside: using enumerate example for i, char in enumerate(’hello’): print(i, char)
  • 24. Aside: using enumerate months = (’janfebmaraprmayjunjul’+ ’augsepoctnovdec’).split() month2mm = {} for i, month in enumerate(months): month2mm[month] = i + 1 #Is easier/nicer than this: for I inrange(len(months)): month2mm[months[i]] = i + 1
  • 25. Exercise: dictionaries 1 Ask the user to enter a string Convert this to lower case Count the number of occurrences of each character in the string Hint: use a dict Print the result in sorted order of the characters 2 3 4 5 For example, if the user enters helloo, print: e 1 h 1 l 2 o 2
  • 26. Solution text =input().lower() result = {} for char in text: if char in result: result[char] += 1 else: result[char] = 1 for char in sorted(result): print(char, result[char])
  • 27. Problem: datestring to date tuple You are given date strings of the form “29 Jul, 2009”, or “4 January 2008”. In other words a number, a string and another number, with a comma sometimes separating the items. Write a program that takes such a string as input and prints a tuple (yyyy, mm, dd) where all three elements are ints.
  • 28. Solution months = (’janfebmaraprmayjunjul’+ ’augsepoctnovdec’).split() month2mm = {} for i, month in enumerate(months): month2mm[month] = i + 1 date =input() date = date.replace(’,’,’’) day, month, year = date.split() dd, yyyy =int(day),int(year) mon = month[:3].lower() mm = month2mm[mon] print((yyyy, mm, dd)) FOSSEE Team (FOSSEE – IITB) Basic Python 30 / 31
  • 29. That’s all folks! FOSSEE Team (FOSSEE – IITB) Basic Python 31 / 31