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

207 Python Programming Exercises Volume 1 - Become A Pro Python Developer

Uploaded by

vietthai09012008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

207 Python Programming Exercises Volume 1 - Become A Pro Python Developer

Uploaded by

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

207 Python

Programming Exercises
Volume 1
207 Python
Programming Exercises
Volume 1

Edcorner Learning
Table of Contents
Module 1 Print Functions
Module 2 Calculations
Module 3 Slicing
Module 4 Data types in Python
Module 5 Strings
Module 6 Sets
Module 7: Tuples
Module 8 Lists
Module 9 Dictionaries
Module 10 – IF statements
Module 11 For loops
Module 12 Break Statements
Module 13 Continue Statements
Module 14 While loops
Module 15 Exception Handling
Module 16 Built-in functions
Module 17 Define Functions
Module 18 Lambda Expression
Module 19 Generators
Module 20 Set Comprehensive
Module 21 List Comprehension
Module 22 Dict Comprehension
Module 23 Built In Packages
Module 24 Final Mixed Exercises
Introduction
Python is a general-purpose interpreted, interactive, object- oriented, and a powerful programming
language with dynamic semantics. It is an easy language to learn and become expert. Python is one
among those rare languages that would claim to be both easy and powerful. Python's elegant syntax and
dynamic typing alongside its interpreted nature makes it an ideal language for scripting and robust
application development in many areas on giant platforms.
Python helps with the modules and packages, which inspires program modularity and code reuse. The
Python interpreter and thus the extensive standard library are all available in source or binary form for
free of charge for all critical platforms and can be freely distributed. Learning Python doesn't require
any pre- requisites. However, one should have the elemental understanding of programming languages.
This Book consist of 24 modules to practise different Python exercises on different topics.
In each exercise we have given the exercise coding statement you need to complete and verify your
answers. We also attached our own input output screen of each exercise and their solutions.
Learners can use their own python compiler in their system or can use any online compilers available.
We have covered all level of exercises in this book to give all the learners a good and efficient Learning
method to do hands on python different scenarios.
Module 1 Print Functions
1. Using the print () function, print to the console: 'Learn Python!'

Expected result:

'Learn Python!

print('Learn Python!')

2. Assign to the variable age number 20. Using the age variable and the
print() function print to the console the following text:

I am 20 years old.
3. Create two variables (you can freely choose the names) and assign to
them following values:
• ' Python’
• ’3.8'
Using these variables and the print () function, print to the console the
following text:
I am learning Python version 3.8

4. Assign 199.99 to the price variable and check the solution.

Expected result:
This costs 199.99
5. Assign 69.99 to the price variable and check the solution.

Expected result:
This costs 199.99

Coding :

price = 69.99
print(f'This costs {price}')
6. Assign two variables that store the following values:
• $ 34.99 - product price (float)
• 20 lbs - product weight (int)
Using the f-string formatting style print to the console the following message:
Price: $34.99. Weight: 20 lbs.
7. Below is an approximation of pi:
pt = 3.1415926535
Using f-string formatting, print the approximation of pi to two decimal places as shown below.
Expected result:
Pt: 3.14

8. Using three print () function (one line- one function) print the following text:
-------------------------------------------
VERSION: 1-0-1
-------------------------------------------
Tip: The lines consist of 40 dash characters ‘_’
9. Using the four print () function (one line - one function) print the following text:
==========================
author: edcorner learning
date: 01-01-2021
===========================
10. Using the print() function and the sep argument set to '#' print the following text:
‘summer#time#holiday’
Module 2 Calculations
11. Write a program that calculates the area of a circle with a radius = 5. Use an approximate
value of pi:
pt = 3.14
Print the result to the console as shown below.
Expected result:
Area: 78.5

12. Write a program that calculates the future value of 1000 USD with an annual interest rate of
3%, annual capitalization and a 5-year investment period. Round the result to the nearest
cent.
Tip: Use compound capitalization of interest.
Print the result to the console as shown below.
Expected result:
The future value of the investment: 1159.27 USD
13. Write a program that calculates the delta for the quadratic equation:

3x2 — 4x + 1 = 0
Print the result to the console as shown below.
Expected result:

Delta:
4
14. The arithmetic sequence is given with the following formula:
an = 10 + 4n

Calculate the sum of the first ten elements of this sequence. Print the result to the console as
shown below.
Expected result:

The sum
of the first 10 elements tn a sequence: 320.0

15. The geometric sequence is given with the following formula:


an = 8- 2n-1
Calculate the sum of the first six elements of this sequence. Print the result to the console as

shown below.
Expected result:

The sum of the first 6 elements of the sequence is: 504.0

16. Calculate the midpoint of the segment with ends at the points: A = (2,4), B = (-4,6) and
print
result to the console as shown below.
Expected result:
The middle point: (-1.0, 5.0)
Module 3 Slicing
17. From the given file name:
filename = 'view.jpg'
extract extension and print it to the console.
Expected result:
Jpg

18. From the following text:


string = 'PKV-89415-PLN'
extract the code containing the first three and last three characters. Print the result to the
console.
Expected result:
PKVPLN
19. From the following text:
string = '100101'
remove spaces using slicing. Then convert the result to decimal notation and print to the
console as shown below.
Expected result:
Number found: 37
20. Using the slicing, reverse the order of the characters in the following text:
text = 'Python'
Print the result to the console as shown below.
Expected Result:
nohtyP
Module 4 Data types in Python
21. The following variables are given (var! - empty string, var2 - space, var3 - newline
character):
varl =''
var2 =''
var3 = '\n'
Print each type of variable on a separate line to the console as shown below.

Expected result:
<class 'str'>
<class 'str'>

<class 'str'>

22. The following variables are given:


Var1 = None
var2 = False
var3 = 'True'
Print each type of variable on a separate line to the console as shown below.
Expected result:

<class ‘ NoneType'>

<class 'bool1>

<class 'str'>

23. Check if the following variable:


flag = False

is an instance of the bool class and print the result to the console.
Expected result:
True
Module 5 Strings
24. The following text is given:
text = 'python is a popular programming language.'
Use the appropriate method to replace the first letter of the text with uppercase. Print the result
to the console.

Expected result:
python is a popular programming language.

25. The following text is given:


text = 'python is a popular programming language.'
Using the appropriate method count the number of occurrences of the letter 'p’ and print the
result to the console as shown below.
Expected result:
Number of occurrences: 4

26. The following codes are given:


Code1 = 'FVNISJND-XX-2020'
code2 = 'FVNISJND-XY-2019'
Using the appropriate method check if the codes end in ' 2020 ‘ . Print the result to the console
as shown below.

Expected result:
code1: True
code2: False
27. The following paths are given:
Path1 = 'youtube.com/watch’
path2 = 'google.com/search?q=car'
Using the appropriate method check if the paths refer to YouTube (e.g. start with ' youtube’).
Print the result to the console as shown below.
Expected result:
Path1: True

path2 : False
28. The following codes are given:
code1 = 'FVNISJND-20'
code2 = 'FVNISJND20'
Using the appropriate method, check whether the codes consist only of alphanumeric characters
(numbers + letters).
Print the result to the console as shown below.
Expected result:

Code1: False
code2 : True

29. The following text is given:


text = 'Amazon Web Services'
Using the appropriate method convert all letters to lowercase. Print the result to the console.
Expected Result:
'amazon web services'

30. The following text is given:


text = 'Amazon Web Services'
Using the appropriate method convert all letters to uppercase. Print the result to the console.
Expected Result:
AMAZON WEB SERVICES

31. The following text is given:


text = ' Google Colab ’
Using the appropriate method remove whitespace characters around the
text.
Print the result to the console.
Expected result:
Google Colab
32. The following code is given:
code = 'FVNISJND-XX'
Using the appropriate method replace the dash with a space. Print the
result to the console.
Expected result:
FVNISJND XX
33. The following text is given:
text = '340-23-245-235'
Using the appropriate method remove all dashes from the text.
Print the result to the console.
Expected result:
34023245235

34. The following text is given:


text = 'Open,High,Low,Close’
Using the appropriate method split the text by comma.
Print the result as a list to the console as shown below.
Expected result:
[‘Open’, ‘High’, ‘Low’, ‘Close’]
35. The following text is given:
text = """Python is a general-purpose language.
Python is popular."""
Using the appropriate method, split the text into sentences.
Print the result as a list to the console.
Expected result:
['Python is a general-purpose language.', 'Python is popular.']
36. The following variable is given:
num = 34
Using the appropriate method for an object of type str, print the variable
num preceded by four zeros to the console as shown below.
Expected result:
000034

37. From the given url-

https://www.edcredibly.com/s/store/courses/description/Programming-
and-Analytics-Courses-Yearly-Subscription
extract the slug after the last character ‘/’. Then replace all dashes with
spaces and print the result to the console as shown below.
Programming and Analytics Courses Yearly Subscription
Module 6 Sets

38. The following set is given:


subjects = {'mathematics', 'biology'}
Using the appropriate method add ‘english’ to this set. In response print
subjects set to the
console.
Expected result:
{'biology', 'mathematics', 'english'}
Note: Remember that the set is an unordered data structure. You may get
a different order of

items than the expected result

39. The following text is given:


text = 'Programming in python’
Follow the next steps:
1. Change all letters to lowercase.
2. Delete spaces and period.
3. Create a set consisting of all letters in the text and assign to letters
variable
4. Using the appropriate method for sets, remove all vowels from
letters set:
vowels = {'a', 'e', 'i, 'o', 'u'}
5. Print the number of items in the letters set as shown below.
Expected result:
Number of items: 8
40. In mathematics, the symmetric difference of two sets is the set of
elements which are in either of the sets, but not in their intersection.
Two following sets are given:
A = {2, 4, 6, 8}
B = {4, 10}
Using the appropriate method, extract the symmetrical difference of
sets A and B and print the result to the console as shown below.
Expected result:

Symmetric difference: {2, 6, 8, 10}


41. We have two sets of customer IDs:
adl_td = {'001', '002', '003'}
ad2_td = {'002', '003', '007'}
Each set stores the id of the customers who made the purchase based on
the specific ad. We have two ads. Each customer can use the offer only
twice in campaign. Choose the ID of the customers to whom you can
send another ad (or ids that only appeared once in both sets).
Expected result:
Selected ID: { '007', '001'}
Note: Remember that the set is an unordered data structure.

You may get a different order of items than the expected result.

42. Two customer ID sets are given. The first one tells you whether a
person clicked on the banner ad. Second, whether the person
purchased the product:
ts_clicked = {'9001', '9002', '9005'}
ts_bought = {'9002', '9004', '9005'}
Return the ID of those customers who clicked on the ad and bought the
product.
Expected result:
Customer ID: { '9002', '9005'}
Note: Remember that the set is an unordered data structure. You may get a
different order of

items than the expected result. You don't have to worry about it.
Module 7: Tuples

43. Two following tuples are given:


djil = ('AAPL-US' , 'IBM-US' , 'MSFT-US')
djiZ = ('HD.US' , 'GS.US' , 'NKE-US')
Combine these tuples into one as shown below and print the result to the console.
Expected result:

('AAPL-US', 'IBI‘LUS', 'MSFT.US', 'HD-Uh, 'GS.US', 'NKE-US')

44. The following tuples are given:

djii ('AAPL. US, 'IBM. US’, ‘MSFT. US’)


dji2 = ("HD.US, GS.US, 'NKE. US")

Nest these tuples into one tuple as shown below and print the result to the console.
Expected result:
(AAPL. US', 'IBM.US’, 'MSFT.US'). ('HD.US', 'Gs.US', 'NKE.US '))

45. Tuples are immutable. The following tuple is given:


members = (('Kate', 23), ('Tom', 19))
Insert a tuple ( ' john‘, 26) between Kate and Tom as shown below. Print the result to
the console.

Tip: You have to create a new tuple.


Expected result:

(('Kate', 23), ('John', 26), ('Ton', 19))


46. The following tuple is given:
default = ('YES', 'NO', 'NO', 'YES', 'NO')
Using the appropriate method return the number of occurrences of the
string ' yes ' and print the result to the console as shown below.
Expected result:
Number of occurrences: 2
47. Sort the given tuple (from A to Z):
names = ('Monica', 'Ton', 'John', 'Michael')
Print the sorted tuple to the console as shown below.
Expected result:
('John', 'Michael', 'Monica', 'Tom')
48. The following tuple is given (name, age):
info = (('Monica1, 19), ('Ton', 21), ('John', 18))
Sort this tuple:
ascending by age
descending by age
And print the result to the console as shown below.
Expected result:
Ascending: (('John', 18), ('Monica', 19), ('Ton', 21))
Descending: (('Ton', 21), ('Monica', 19), ('John', 18))

49. The following tuple is given:


stocks = (('Amazon Inc', ('AMAZ.US', 310)), ('Microsoft Corp',
('MSFT.US', 184)))
Extract a ticker for Apple and print the result to the console.
Expected result:
AAPL.US
Module 8 Lists

50. To the given list:


cities = ['Los Angeles', 'New York', 'Chicago']
append the city: 'Houston' and print the list to the console.
Expected result:
['Los Angeles', 'New York', 'Chicago', 'Houston']

51. The following list is given:


idx = ['001', '002', '001', '003', '001']
Using the appropriate method count the occurrences of ‘001 ' . Print the
result to the console as shown below.
Expected result:
Number of occurrences: 3

52. The following text is given:


text = 'Python programming'
Standardize the text (replace uppercase letters with lowercase). Then
create a list of unique characters in the text. Remove the space from this
list and sort from a to z. After all print the list to the console.
Tip: You can use a set to generate unique characters.
Expected result:

['a', 'g', 'h', 'i', 'm', 'n', 'o', 'p', 'r', 't', 'y']
53. The following list is given:
filenames = ['vlew.jpg', 'bear.jpg', 'ball.png']
Add the file 'phone.jpg' to this list at the beginning. Then delete the file
'ball.png' . response, print the filenames list to the console.
Expected result:
['phone.jpg', 'view.jpg', 'bear.jpg']
54. The following list represents order ids for a given day:
dayl = ['3984', '9042', '4829', '2380']
Using the appropriate method, extend this list to the next day:
day2 = ['4231', '5234', '1345', '2455']
Print the result to the console.
Expected result:

['3984', '9042', '4829', '2380', '4231', '5234', '1345', '2455']

55. The following tuple is given:


techs = ('python', 'java', 'sql', 'aws')
Sort this tuple from a to z and print it to the console.
Tip: Tuples are immutable. You have to create a new one.
Expected result:

('aws', 'java', 'python', 'sql')

56. The following list is given:


hashtags = ['summer', 'time', ’vibes']
Using the appropriate method, combine the elements of the list with the
'#' character. Also add this sign to the beginning of the text and print the
result to the console as shown below.
Expected result:
‘#summer#time#vibes'
Module 9 Dictionaries

57. Create a dictionary from the following pairs (key, value):


'USA': 'Washington' 'Germany': 'Berlin' 'Austria': 'Vienna'
and print it to the console.
Expected result:

{'USA': 'Washington', 'Germany': 'Berlin', 'Austria’: ‘Vienna'}

58. The following dictionary is given:


capitals = {
'USA': 'Washington',
'Germany': 'Berlin',
'Austria': 'Vienna'
}
Use the appropriate method to extract all keys from the capitals
dictionary and print to the console.
Expected result:

dict_keys([‘USA', 'Germany', 'Austria'])

59. The following dictionary is given:


capitals = {
'USA': 'Washington',
'Germany': 'Berlin',
'Austria': 'Vienna'
}
Use the appropriate method to extract all values from the capitals
dictionary and print to the console.
Expected result:
dict_values(['Washington', 'Berlin’,’ Vienna'])

60. The following dictionary is given:


capitals = {
'USA': 'Washington',
'Germany': 'Berlin',
'Austria': 'Vienna'
}
Using the appropriate method, extract the list containing tuple objects
(key, value) from the capitals dictionary and print to the console as
shown below.
Expected result:

dict_items([('USA', 'Washington'), ('Germany', 'Berlin'), ('Austria',


'Vienna')])
61. The following dictionary is given:
capitals = {
'USA': 'Washington',
'Germany': 'Berlin',
'Austria': 'Vienna'
Using the dict.get() method, extract the value for the key 'Austria'
and print it to the console.

Expected result:
Vienna
62. The following dictionary is given:
stocks = {
'MSFT.US': {'Microsoft Corp': 184}, ' AMAZ.US': {'Amazon Inc':
310},
'MMM.US': {'3M Co': 148}
Extract the value for the key 'amaz.us' and print it to the console.
Expected result:
{'Amazon Inc': 310}
63. The following dictionary is given:
stocks = {
'MSFT.US': {'Microsoft Corp': 184}, 'AAPL.US ' : {'Apple Inc': 310},
'MMM.US': {'3M Co': 148}
Get the price for Microsoft (value for the 'Microsoft corp' key) and print
it to the console.
Expected result:
184

64. The following dictionary is given:


stocks = {
'MSFT.US': {'Microsoft Corp': 184}, 'AAPL.US': {'Apple Inc': 310},
'MMM.US': {'3M Co': 148}
Update the price for Microsoft to 190 and print the value for the ' msft.
us ' key to the console.
Expected result:
{'Microsoft Corp': 190}

65. The following dictionary is given:


stocks = {
'MSFT.US': {'Microsoft Corp': 184}, 'AAPL.US': {'Apple Inc': 310},
'MMM.US': {'3M Co': 148}
Add a fourth pair to this dictionary with the key 'v.us' and the value:
{'Visa Inc': 185} .
Print the values of the stocks dictionary to the console.
Expected result:
dict_values([{'Microsoft Corp': 184}, {'Apple Inc': 310}, {'3M Co':
148}, {'Visa Inc': 185}])

66. The following dictionary is given:


project_ids = {
'01': 'open',
'03': 'in progress'
'05': 'in progress'
'04': 'completed'
}
Extract a list of unique values (sorted alphabetically) from the
projectjds dictionary and print it to the console.
Expected result:
[1 completed1, 'in progress', 'open']
67. The following dictionary is given:
stats = {'site': 'edcredibly.com', 'traffic': 100, 'type': 'organic'}
Delete the ' traffic1 key pair from this dictionary and print it to the
console.
Expected result:
{'site': 'edcredibly.com', 'type': 'organic'}

68. The following dictionary is given:


users = {'001': 'Hark', '002': 'Monica', '003':'Jacob'}
Try to print value for key '004’
In this exercise use the dict. get () method. When the key is not in the
dictionary set default value to the string 'indefinite’.
Expected result:
‘indefinite'
Module 10 – IF statements

69. The following filename is given:


filename = '01012020 sales.xlsx'
Check if the file has the 'xlsx1 extension. Print to the console 'yes' if
true, 'no' if false.
Expected result:
YES

70. The following code is given:


code = 'DSVNDOICSN'
Check if the code variable has only uppercase letters. If so, print 'yes '
to the console.
Expected result:
YES

71. The following variable is given:


number = 1.0
Test whether the variable is an instance of the built-in class/ni. Print
'yes' if true, 'no’ if false.
Expected result:
NO

72. The following password is given:


password = 'cskdnjcasa#!'
Check if the password has 11 characters.
If SO, print 'Password correct’, Otherwise 'Password too short'
Expected result:
Password correct
73. The following password is given:
password = 1cskdnjcasa#!'
Check if the password has at least 11 characters and contains the
special character If SO, print 'Password correct’, Otherwise 'Password
incorrect’.
Expected result:
Password correct
74. The following list is given:
project_ids = ['02134', '24253']
Check if the following project id:
projected = '02135'
is in the projectjds list. If not, add this projecüd to the list and print this
list to the console.
Expected result:
['02134', '24253, '02135']
75. The following dictionary is given:
project_lds = {
'01': 'open',
'02': 'new',
'03': 'in progress',
'04': 'completed'
Using the conditional statement, check if the project status with id =
' 02 ' is set to ' new’. If so, change its status to ' open ' and print the
dictionary to the console.
Expected result:
{'01': 'open', '02': 'open', '03': 'in progress', '04': 'completed'}
76. Write a program that checks if the given item:
item = '001'
is in the list:
items = ['001', '0O0', '003', '0O5', 100613
If so, remove this item from the list and print this list to the console.
Expected result:
['000', '003, '005', '006']
Module 11 For loops
77. Write a program that finds all two-digit numbers divisible by 11
(use a for loop). Print the result to the console as comma-separated
values as shown below.
Expected result:
11,22,33,44,55,66,77,88,99

78. Write a program that finds all two-digit numbers divisible by 11


and indivisible by 3 (use a for loop). Print the result to the console as
comma-separated values as shown below.

Expected result:
11,22,44,55,77,88
79. The following list of numbers is given:
items = [1, 3, 4, 5, 6, 9, 10, 17, 23, 24]
Write a program that removes odd numbers and returns the remaining
ones. Print the result to the console.
Expected results:

[4, 6, 10, 24]


80. The following list is given:
items = [1, 5, 3, 2, 2, 4, 2, 4]
Write a program that removes duplicates from the list (the order must
be kept) and print the list to the console.
Expected result:

[1, 5, 3, 2, 4]
81. The following text is given:
text = 'Python is a very popular programming language'
Write a program which extracts exactly the first four words as a list.
Standardize each word, i.e. replace uppercase letters with lowercase.
Present the result in a list and print to the console as shown below.
Expected result:

[‘python',' is', 'a', 'very']


82. Write a program that returns a list of values above the given
threshold = 0.5 from the following list:
probabilities = [0.21, 0.91, 0.34, 0.55, 0.76, 0.02]
Expected result:
[0.91, 0.55, 0.76]
83. Consider the problem of binary classification in machine
learning. The machine learning model returns the probability of
belonging to the class. If it's less than 0.5, the sample is assigned to
class 0, otherwise to class 1.
A list of probabilities from the machine learning model is given:
probabilities = [0.21, 0.91, 0.34, 0.55, 0.76, 0.02]
Write a program that assigns class 0 for values less than 0.5 and 1 for
values greater than or equal to 0.5. Print the result to the console as
shown below.
Expected result:

[0, 1, 0, 1, 1, 0]
84. Write a program that creates a histogram as a dictionary of the
following values:
items = ['x’, 'z’, ‘y’, 'x', 'y’, 'y’,' z’, 'x']
In response print histogram to the console.
Expected result:
{'X': 3, 'y': 4, ‘z’: 2}

85. The following text is given:


text = """Python is powerful... and fast plays well with others runs
everywhere is friendly & easy to learn is Open
These are some of the reasons people who use Python would rather not
use anything else""
Create a list of words from the given text. Then standardize this text
(change uppercase letters to lowercase, remove punctuation marks).
Extract words longer than six characters and print the result to the
console.

Expected result:
['powerful', 'everywhere', 'friendly', 'reasons', 'anything']

86. The list of stock indexes is given:


indexes = [
'BOVESPA', 'DOW JONES COMP', 'DOW JONES INDU', 'DOW
JONES TRANS', 'DOW JONES UTIL', 'IPC, 'IPSA', 'MERVAL',
'NASDAQ COMP', 'NASDAQ100',
'S&P500', 'S&P/TSX COMP'
]
Iterate through the indexes list and print to the console only those
indexes containing ‘ dow ‘ or 'S&P' .
Expected result:
DOW JONES COMP
DOW JONES INDU
DOW JONES TRANS
DOW JONES UTIL
S&P500
S&P/TSX COMP
87. A dictionary of companies from the WIG.GAMES index is given.
The key is the 3-letter company ticker and value - close price:
gaming = {
'11B’: 362.5,
'CDR': 297.0,
'CIG': 0.85,
'PLW: 318.0,
'TEN': 300.0
}
Iterate through this dictionary and print the tickers of those
companies where closing price is greater than 100.00 PLN.
Expected result:
11B
CDR
PLW
TEN
88. A list of names entered by users into the system is given below
(without
validation process):
names = ['Jack', 'Leon', 'Alice', '32-3c', 'Bob']
Iterate through the names list and check if each name is correct
(contains only letters).
If so, print to the console following message: f ■ Hello {name} !1
otherwise do nothing.
Tip: Use the str.isaipha() method.
Expected result:
Hello Jack!
Hello Leon!
Hello Alice!

Hello Bob!
Module 12 Break Statements
89. Write a program that compares two lists and returns True if the
lists contain at least one of the same element. Otherwise, it will
return False.
Use break statement in the solution and print result to the console.
Lists:
Listl = [1, 2, 0]
List2 = [4, 5, 6, 1]
Expected result:

True

90. The following list of hashtags is given:


hashtags = ['holiday', 'sport', 'fit'. None, 'fashion']
Check if all objects in the list are of str type. If so, print True, otherwise
print False. Use the break statement in your solution.
Expected result:
False

91. Write a program that checks if the given number is a prime


number (use the break statement):
number = 13
Print one of the following to the console depends on the result:
13 - prime number
13 - not a prime number
Expected result:
13 - prime number
Module 13 Continue Statements

92. The list of companies from the WIG.GAMES index is given with
the closing price and currency:
gaming = {
'11B’: [362.5, 'PLN1],
'CDR': [74.25, 'USD'],
'CIG': [0.85, 'PLN'],
'PLW: [79.5, 'USD'],
'TEN1: [300.0, 'PLN']
}
Using the continue statement, create a for loop that will change the
closing price from USD to PLN in this dictionary. Take USDPLN =
4.0.
In response, print the gaming dictionary to the console.

Expected result:

{'11B': [362.5, 'PLN'], 'CDR': [297.0, 'PLN'], 'CIG': [0.85,


'PLN'], 'PLW': [318.0, 'PLN'], 'TEN': [300.0, 'PLN']}
93. The list of names is given (one is missing):
names = ['Jack', 'Leon', 'Alice', None, 'Bob']
Using the continue statement, print only the correct names to the
console as shown below.
Expected result:
Jack
Leon
Alice
Bob
Module 14 While loops

94. Write a program that prints to the console the first ten prime numbers separated by a
comma.
Tip: Use a while loop with break statement.

Expected result:

2,3,5,7,11,13,17,19,23,29

95. Using the while loop, calculate how many years you have to wait
for the return on the investment described below to at least double
your money (we only take into account full periods).
Description:
n - number of periods (In years)
pv - present value
r - interest rate (annual)
fV - future value
Investment parameters:
pv = 1000
r = 0.04
Print result to the console as shown below.
Expected result:
Future value: 2025.82 USD. Number of periods: 18 years
96. Use the stochastic gradient descent algorithm to find the
minimum ot the loss function given by the formula: L(w) = vv2 - 4w
The derivative of function L: 4^ = 2 * w—4
dw
Algorithm:
1. We start from the starting point, let's take:
W_0 = -1
2. We define in advance the maximum number of iterations:
max iters = 10000
3. We define a variable that will help us control the size of the step
towards the minimum, let’s set this value to 1:
previous_step_size = 1
4. We define the learning rate:
learning_rate = 0.01
5. We define the precision that is enough to find the minimum:
precision = 0.000001
6. We define the derivative of a function:
derivative = lambda w: 2 * w - 4
To find the minimum of the L function, move along the opposite
direction to the direction of the gradient by updating the value w_0
as follows:
w_0 = w_0 - learnlng_rate * derlvatlve(w_prev)
where w_prev is the point from the previous iteration. For the first
point is just w_0.
Create a while loop that will stop the algorithm when the minimum
is found with the precision we assumed or if we exceed the
maximum number of iterations. Print the result to the console as
shown below.
Tip: Conditions in a while loop:
while previous_step_size > precision and iters < max_iters:
Expected result:
A local minimum in point: 2.00
97. Write a program that checks if the given element (target) is in the
sorted list (numbers). We have given:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] target = 7
Algorithm:
1. We set the start and end index as well as the flag = None .
2. As long as the start index is not greater than the end index, select
the middle index (mid) of the list (arithmetic average of the start and
end index -> remember to convert the result with the int ( ) function). If
the start index is greater than the end index, we end the algorithm.
3. Check if the element for the index calculated in this way is our
target. If so, we set the flag to True and terminate the algorithm. If not -
> step 4.
4. We check if the element of the list for the index mid is less than the
target. If so, we increase the start index by 1. If not, we reduce the end
index by 1 and go to step 2.
After while loop, depending on the value of the flag, print to the
console:
'Found' Or 'Not found' .
Expected result:
Found
Module 15 Exception Handling
98. Two variables defined below are given:
sum = 3000
counter = 0
We want to divide the variable sum by the counter variable. Using the
try... except... clause handle the ZeroDivisionError. If the division is
done correctly, print the result to the console, otherwise print to the
console the following message:
Expected Solution:

Division by zero.

99. Sometimes we need to open a file without knowing if such a file


exists. When file doesn't exist the FileNotFoundError is raised.
Using the try... except... clause, handle with this problem.
Use this code snippet to read the content of the file:
with open('file.txt1, 'r') as file: content = file.readQ
Try to open file.txt using the above code. If the file.txt does not exist, print to
the console following message:

File not found.

100. The following dictionary is given:


users = {'001': 'Hark', '002': 'Monica', 'O03':
Try printing the value for the key:
user id = '004'
'Jacob'}
In case of a KeyError, print to the console the following message:
The 004 key Is not in the dictionary. Adding key '
Then add this key to the dictionary with the value None and print the
users dictionary to the console.
Expected result:

The 004 key is not in the dictionary. Adding key ...


{'001': 'Hark', '002': 'Monica', '003': 'Jacob', 'O04': None}
Module 16 Built-in functions
101. The variable x:
X = -1.5 and the following expression are given: expression = 'x**2 +
x'
Using the appropriate function, calculate the value of this expression
and print the result to the console.
Tip: Use the evai() function.
Expected result:
0.75

102. The following variables are given:


Var1 = 'Python'
var2 = ('Python')
var3 = ('Python',)
var4 = ['Python']
var5 = {'Python'}
Using the appropriate function, check if the variables are instances of
tuple class. Print the result to the console as shown below.
Tip: Use the isinstanceQ built-in function.
Expected result:
False
False
True
False
False
103. The following list is given:
characters = ['k’, 'b', 'c’ '3', 'z', 'w']
Using the built-in functions, return the first and the last letter in
alphabetical order from this list and print the result to the console as
shown below.
Tip: Use the min() and max() functions.
Expected result:
First: b
Last: z
104. Two tuples are given:
ticker = ('TEN', 'PLW, ' CDR ' )
full_name = ('Ten Square Games', 'Playway', 'CD Projekt')
Using the appropriate built-in function, create a list consisting of tuples
(ticker, full_name) and print the result to the console as shown below.
Tip: Use the zip() function.
Expected result:

[('TEN', 'Ten Square Games'), ('PLW, 'Playway'), ('CDR', 'CD


Projekt')]

105. Using the appropriate built-in function, verify if all elements of


the following tuple return the logical value True:
itens = (' ‘ , '0', 0.1, True)
Print the result to the console.
Expected result:

True.

106. Using the appropriate built-in function, verify if any element of


the following tuple returns the boolean value True:
items = (‘ ‘ , 0.0, 0, False)
Print the result to the console.
Expected result:
False.

107. Count the number of ones in the binary representation of number:


number = 234
Print the result to the console.
Tip: Use the bin() built-in function.
Expected result:
5
Module 17 Define Functions

108. Implement a function called maximum( ) that returns the


maximum of two numbers. Use conditional statement.
Example:
[IN]: Maximum(4, 2)
[OUT]: 4
[IN]: Maximum (-4, 2)
[OUT]: 2
Note! You only need to define the function.
Solution :
def maximum(x, y):
if x >= y:
return x
else:
return y

109. Implement a function called maximum( ) that returns the


maximum of three numbers. Use conditional statement.
Example:
[IN]: Maximum(4, 2, 1)
[OUT]: 4
[IN]: Maximum (-3, 2, 5)
[OUT]: 5

Note! You only need to define the function.

Solutions:

def maximum(x, y, z):


if x >= y and x >= z:
return x
elif y >= z:
return y
else:
return z

110. Implement a function called multi() , which accepts an iterable


object (list, tuple) as an argument and returns the product of all
elements of this iterable object.
Example:
[IN]: multi((-4, 6, 2)) [OUT]: -48
[IN]: nulti([4, 2, -5])
[OUT]: -40
Note! You only need to define the function.

Solution:

def multi(numbers):
result = 1
for number in numbers:
result *= number
return result

111. Implement a function map_longest( ) that accepts the list of words


and return the length of the longest word in this list.
Example:
[IN]: map_longest([1 python', 'sql']) [OUT]: 6
[IN]: map_longest([1 java1, 'sql', 'r’])
[OUT]: 4
Note! You only need to define the function.
Solution:
def map_longest(words):
length = []
for word in words:
length.append(len(word))
return max(length)

112. Implement a function called fiiter_ge_6() that takes a list of words


and returns list of words with the length greater than or equal to 6
characters.
Example:
[IN]: filter_ge_6(‘programming’, 'python', 'java', 'sql'])
[OUT]: ['programming', 'python']
[IN]: filter_ge_6(['java', 'sql'])
[OUT]: []
Note! You only need to define the function.
Solution:
def filter_ge_6(words):
result = []
for word in words:
if len(word) >= 6:
result.append(word)
return result

113. Implement a function called factorial) that calculates the factorial


for a given number.
Example:
[IN]: factorial(6)
[OUT]: 720
[IN]: factorial(lO)
[OUT]: 3628800
Note! You only need to define the function.
Solution:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
114. Implement a function count_str( ) , which returns the number of
str objects (list, tuple, set).
Example:
[IN]: count_str(['p', 2, 4.3, None])
[OUT]: 1
[IN]: count_str({'p', 2, 4.3, True, 'True', None})
[OUT]: 2
Note! You only need to define the function.
Solution:
def count_str(items):
total = 0
for item in items:
if isinstance(item, str):
total += 1
return total

115. Implement a function count_str( ) , which returns the number of


sfr objects with a length more than 2 characters from an iterable
object (list, tuple, set).
Example:
[IN]: count_str([l, 'hello', ", 'python', 'go'])
[OUT]: 2
[IN]: count_str([l, 2, 3, 'python'])
[OUT]: 1
Note! You only need to define the function.
Solution:
def count_str(items):
total = 0
for item in items:
if isinstance(item, str):
if len(item) > 2:
total += 1
return total

116. Implement a function remove_duplicates( ) that removes


duplicates from the list (the order of the items in the list does not
have to be kept).
Example:
[IN]: remove_duplicates([1, 5, 3, 2, 2, 4, 2, 4])
[OUT]: [1, 2, 3, 4, 5]
[IN]: remove_dupllcates([1, i, 1, 1])
[OUT]: [1]
Note! You only need to define the function.
Solution:

def remove_duplicates(items):

return list(set(items))

117. Implement a function is_distinct( ) to check if the list contains


unique values.
Example:
[IN]: \s_distlnct([l, 2, 3])
[OUT]: True
[IN]: \s_distlnct([l, 2, 3, 3])
[OUT]: False
Note! You only need to define the function.
Solution:

def is_distinct(items):
return len(items) == len(set(items))
118. The following function is defined:
def function(idx, l=[]): for i in range(idx):
l.append(i ** 3) print(l)
Call the function three times as follows:
function(3)
function(5, ['a', 1b', 'c']) function(6)
Analyze the results!
Expected result:
[0, 1, 8]
['a', 'b', 'c', 0, 1, 8, 27, 64]
[0, 1, 8, 0, 1, 8, 27, 64, 125]
119. The following function is given:
def function(*args, **kwargs) print(args, kwargs)
Call the function in the order given:
function(3, 4) function(x=3, y=4)
function(l, 2, x=3, y=4)
Analyze the result!
Expected result:
(3, 4) {}
() {'x': 3, 'y': 4}

(1, 2) {'x': 3, 'y': 4}

120. Implement the function is_palindrome( ), which takes as an


argument str object and checks if this object is a palindrome
(expression that sounds the same from left to right and from right to
left).
If so, the function should return True, on the contrary False.
Example:
[IN]: is_palindrome('level')
[OUT]: True
[IN]: is_palindrome(‘python’)
[OUT]: False
Note! You only need to define the function.
Solution:
def is_palindrome(string):
inverse = string[::-1]
if string == inverse:
return True
else:
return False
Module 18 Lambda Expression
121. The following list of words is given:
stocks = ['playway', 'boombit', 'cd projekt']
Using the map( ) function and the lambda expression, transform the
given list into a list containing the lengths of each word and print it to
the console.
Expected result:
[7, 7, 10]

122. Implement the sort_iist() function that sorts a list of two-element


tuple objects according to the second element of the tuple.
Example:
[IN]: sort_list([(l, 3), (4, 1), (4, 2), (0, 7)])
[OUT]: [(4, 1), (4, 2), (1, 3), (0, 7)]
[IN]: sort_list([('a', 'b'), ('g', 'a'), ('z', 'd’)])
[OUT]: [('g', 'a'), ('a', 'b'), ('z’, 'd')]
Tip: Use the sorted () function.
Note! You only need to define the function.
Solution:
def sort_list(items):
return sorted(items, key=lambda item: item[1])

123. The func_i() function is defined below:


def func_l(x, y): return x + y + 2
Using the lambda expression, define an analogous function and assign
it to the variable func_2.
Solution:

func_2 = lambda x,y: x + y + 2


124. The following list is given:
Items = [(3, 4), (2, 5), (1, 4), (6, 1)]
Sort the list by the growing sum of squares of numbers in each tuple.
Use the sort( ) method and the lambda expression and print sorted list to
the console.

Expected result:
[(1, 4), (3, 4), (2, 5), (6, 1)]

125. Sort the given list of dictionaries by price key:


stocks = [
{'index': 'mWIG40', name': 'TEN', 'price': 304}
{'index': 'mWIG40', name': 'PLW', 'price': 309}
{'index': 'sWIG80', name': 'BBT', 'price': 22}
]
Print sorted list to the console.
Expected Result :
[{'index': 'SWIG80', 'name': 'BBT', 'price': 22},
{'index': 'nWIG40', 'name': 'TEN', 'price': 304},
{'index': 'nWIG40', 'name': ' PLW’,'price': 309}]
Solution:
stocks = [
{'index': 'mWIG40', 'name': 'TEN', 'price': 304},
{'index': 'mWIG40', 'name': 'PLW', 'price': 309},
{'index': 'sWIG80', 'name': 'BBT', 'price': 22}
]

stocks.sort(key=lambda item: item['price'])


print(stocks)

126. The following list is given:


stocks = [
{1 index': ' P1WIG401, 'name': 'TEN', 'price': 304}
{1 index': 'mWIG40', 'name': 1PLW','price': 309}
{'index': 'SWIG801, 'name': 'BBT', 'price': 22}
Extract companies from the ‘mwiG40’ index and print the result to the
console.
Expected result:
[{'index':'mWIG40', 'name': 'TEN', 'price': 304},
{'index': 'mWIG40 ', 'name' : 'PLW, 'price': 309}]
Solution:
stocks = [
{'index': 'mWIG40', 'name': 'TEN', 'price': 304},
{'index': 'mWIG40', 'name': 'PLW', 'price': 309},
{'index': 'sWIG80', 'name': 'BBT', 'price': 22}
]
print(list(filter(lambda item: item['index'] == 'mWIG40', stocks)))

127. The following list is given:


stocks = [
{'index': 'mWIG40', 'name': 'TEN', 'price': 304},
{'index': 'mWIG40', 'name': 'PLW, 'price': 309},
{'index': 'sWIG80', 'name': 'BBT', 'price': 22}
]
Convert the list to a list of boolean values (True, False). True if the
company belongs to the ‘ mwiG40 ' index, False on the contrary and
print the result to the console.
Tip: Use the map() function.
Expected result:

[True, True, False]

128. The following list is given:


items = ['P-1', ‘R-2', 'D-4', 'F-6']
Using the map( ) function and the lambda expression, get rid of the 1 - '
(dash) from each element and print items list on the console.
Expected result:
['PI', 'R2','D4', 'F6']

129. Two lists are given:


num1 = [4, 2, 6, 2, 11]
num2 = [5, 2, 3, 3, 9]
Using the map() function and lambda expression, create a list
containing the remainders of dividing the first list by the second
(elementwise).
Expected result:
[4, 0, 0, 2, 2]
Module 19 Generators

130. Implement a generator named f iie_gen ( ) , which selects only


those names of files with the ' .txt ' extension from the list.
Example:
[IN]: fnames = ['datal.txt', 'data2.txt', 'data3.txt', 'view.jpg']
[IN]: llst(file_gen(fnames))
[OUT]: ['datal.txt', 'data2.txt', 'data3.txt']
Note! All you have to do is define a generator.

Solution:
def file_gen(fnames):
for fname in fnames:
if fname.endswith('.txt'):
yield fname

131. Implement a generator called enum() that works just like the
enumerateQ built-in function. For simplicity, the function gets an
iterable object and returns a tuple (index, element).
Example:
[IN]: list(enum(['TEN', 'CDR1, 'BBT']))
[OUT]: [(0, 'TEN'), (1, 'CDR'), (2, 'BBT')]
Note! All you have to do is define a generator.

Solution:
def enum(items):
idx = 0
for item in items:
yield (idx, item)
idx += 1

132. Implement a generator named dayname( ) that accepts the index of


the element from the following list:
days = ['Hon', 'Tug', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
and allows us to iterate over 3 days (previous day, present day, next
day).
Example:
for pair in dayname(8):
[IN]:
print(pair)
[OUT]:
Sun
Mon
Tue
Solution:
def dayname(index):
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
yield days[index - 1]
yield days[index]
yield days[(index + 1) % 7]
Module 20 Set Comprehensive

133. Consider the two-roll of the dice. Create the probability space
(omega) and count the probability of getting a sum of points higher
than 10. Use set comprehension.
Expected result:
Probability: 0.08

134. The following text is given:


desc = "Playway: Playway Is a producer of computer games.
Change all characters to lowercase, remove the colon, period and then
split the text into words. Create a set of unique words and print the
length of this set to the console.
Expected result:
7

135. Consider the two-roll of the dice. Create the probability space
(omega) and calculate the probability of getting a sum of squares
higher or equal to 45. Use set comprehension. Round the result to
two decimal places and print the result to the console as shown
below.
Expected result:
Probability: 0.22
136. Consider a three-roll of the dice. Create the probability space
(omega) and calculate the probability of obtaining three values
which the sum is divisible by 7. Use set comprehension. Round the
result to two decimal places and print the result to the console as
shown below.
Expected result:
Probability: 0.14
137. Calculate the probability that in three throws of symmetrical cubic
dice, the sum of the squares of points will be divisible by 3. Use set
comprehension. Round the result to the fourth decimal place and
print the result to the console as shown below.
Expected result:
Probability: x.xxxx
138. We roll the symmetrical dice three times. Calculate the probability
of the following:
• A - odd number of points in each roll
Use set comprehension. Round the result to three decimal places and
print to the console as shown below.
Expected result:
Probability: 0.125
Module 21 List Comprehension

139. The list of product prices is given:


net_price = [5.5, 4.0, 9.0, 10.0]
The VAT for these products is equal to 23%: tax = 0.23
Using the list comprehension, calculate the gross price for each
product. Round the price to two decimal places and print result to the
console.
Expected result:

[6.76, 4.92, 11.07, 12.3]

140. The present value -pv and the investment period - n are given
below:
pv = 1000 n = 10
Depending on the interest rates given below, calculate the future value
fv of your investment:
rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
Round the result to the full cent and print the result to the console.
Expected result:

[1104.62, 1218.99, 1343.92, 1480.24, 1628.89, 1790.85, 1967.15]

141. The present value -pv and the investment period - n are given
below:
pv = 1000 n = 10
Depending on the interest rates given below, calculate the value of
interest on investments:
rate = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07]
Round the result to the full cent and print the result to the console.
Expected result:
[104.62, 218.99, 343.92, 480.24, 628.89, 790.85, 967.15]

142. The following dictionary is given:


data = dict(ztp(('a', 'b', 'c', 'd', 'e', 'f1),(1, 2, 3, 4, 5, 6)))
Convert this dictionary into the following list and print the result to the
console.
Expected Result:
[['a1, 1], ['b', 2], ['c\ 3], [-d1, 4], [’G', 5], [ 'f ', 6]]
Module 22 Dict Comprehension

143. Using diet comprehension, create a dictionary that maps the


numbers 1 to 7 into squares and print the result to the console.
Expected result:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}

144. The following list is given:


stocks = ['Playway', 'CD Projekt', 'Boombit1]
Use diet comprehension to build a dictionary that maps company names
to the number of characters of its name and print the result to the
console.
Expected result:
{'Playway1: 7, 'CD Projekt': 10, 'Boombit': 7}

145. The following dictionary is given:


stocks = {'Boombit': '001', 'CD Projekt': '0O2', 'Playway': '0O3'}
Use diet comprehension to replace values with keys and print the result
to the console.
Expected result:
{'001': 'Boombit1, 'O02': 'CD Projekt', '003': 'Playway'}
146. The following dictionary is given:
stocks = {'Boombit': 22, 'CD Projekt': 295, 'Playway': 350}
Using diet comprehension, extract a key: value pair from the dictionary
with a value greater than 100 and print the result to the console.
Expected result:
{'CD Projekt': 295, 'Playway1: 350}
147. Create a list consisting of dictionaries mapping consecutive digits
from 1 to 9 inclusive to their respective k-Xh powers, for k = 1,2,3.
Print the result to the console as shown below.

Formatted result:
[{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7:49, 8: 64, 9: 81},
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512,
9: 729}]
148. The following list of indexes is given:
indeks = ['WIG20', 'mWIG40', 'sWIG80']
and a list of properties for each index:
properties = ['number of companies', 'companies', 'cap']
Using diet comprehension, create the following dictionary:
{'WIG20': {'cap': None, 'companies': None, 'number of companies':
None}
, 'mWIG40': {'cap': None, 'companies': None, 'number of companies':
None}
, 'sWIG80': {'cap': None, 'companies': None, 'number of companies':
None}}
Set the default value of each property to None and print the result to the
console.
Expected result:
{'WIG20': {'number of companies': None, 'companies': None, 'cap':
None}, 'mWIG40': {'number of companies': None, 'companies': None,
'cap': None}, 'sWIG80': {'number of companies': None, 'companies':
None, 'cap': None}}
149. The following list is given:
indexes = ['WIG20', 'nWIG40', 'sWIG80']
Using diet comprehension, convert the above list into the following
dictionary:
{0: 'WIG201, 1: ,nWIG40', 2: 'sWIG80'}
Print the result to the console.
Module 23 Built In Packages
150. Print the calendar for 2020 to the console using the calendar built-in module.
Expected result:
2021
Solution:
import calendar
print(calendar.calendar(2020))
151. Using the calendar built-in module, print a calendar for August 2021 to the console.
152.

Solution:

import calendar
print(calendar.month(2021, 8))

152. Using the datetime built-in module, calculate the difference for dates (date 2 - date 1):
date 1:2021-06-01
date 2: 2021-07-18
Print the result to the console as shown below.
Expected Result:
47 days, 0:00:00

153. Using the built-in module for regular expressions, find all digits in the following text:
string = 'Python 3.8'
Print the result to the console.
Tip: Use the findall() function and the regular expression '\d'
Expected result:
['3', '8']
154. Using the built-in module for regular expressions, find all alphanumeric characters in the
following text:
string = '!@#$%A&45wc'
Print the result to the console.
Tip: Use the findall()function and the regular expression '\w'
Expected result:
['4', '5', 'w', ’c']
155. Using the built-in module for regular expressions, find all email
addresses in the following text:
raw_text = "Send an email to contact@edcredibly.com or
'contact@edcorner.in"
Print the result to the console.
Tip: Use the findall() function and the regular expression * [\w\.-
]+@[\w\.-]+'

Expected Result:
['contact@edcredibly.com', 'contact@edcorner.in']

156. Using the built-in module for regular expressions, split the
following text by whitespace (spaces):
text = 'Programming in Python - from A to Z'
Print the result to the console.
Tip: Use the re.split() function and the regular expression '\s+' .
Expected result:
['Programming', 'in', 'Python', 'from', 'A', 'to', 'Z']

157. Using the string built-in module, print a string of lowercase and uppercase letters to the
console.

Expected result:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
158. Using the collections built-in package, create a Counter class
object that counts the frequency of items in the following list:
items = ['YES', 'NO', 'NO', 'YES', 'EMPTY', 'YES', 'NO']
Print the result to the console.
Expected result:
Counter({1 YES' : 3, 'NO': 3, 'EMPTY1: 1})
159. Using the math built-in module, implement the function called
sigmoid() expressed by the formula:

F(x) = 1/1+e-x
Note: All you have to do is implement the function.

Solution:
import math
def sigmoid(x):
return 1 / (1 + math.exp(-x))
160. Using the random built-in module set the random seed as follows:
random.seed(12)
And select randomly (pseudo-randomly) an item from the list below:
items = ['python', 'java', 'sql', 'c++', 'c']
Print the result to the console.
Expected result:
c++
161. Using the random built-in module set the random seed as follows:
random.seed(15)
And shuffle (pseudo-randomly) items in the following list:
items = ['python', 'java', 'sql', 'c++', 'c']
In response, print the list to the console.
Expected result:
['c', 'c++', 'sql', 'python', 'java']

162. Using the pickle built-in module, save the following list to the
data.pickle file.
ids = ['001', '003', '011']
Solution:
import pickle
ids = ['001', '003', '011']
with open('data.pickle', 'wb') as file:
pickle.dump(ids, file)
163. Using the json package, dump the following dictionary:
Stocks = {1PLW1: 360.0, 'TEN': 320.0, 'CDR': 329.0}
to the string, sorted by keys with indent 4. Print the result to the
console.
Expected result:
{
"CDR": 329.0,
"PLW": 360.0,
"TEN": 320.0

}
Module 24 Final Mixed Exercises
164. Consider the problem of binary classification in machine learning.
We have the following yjrue list with classes from the test set and
the following y_pred list with classes provided by the model:
y_true = [0, 0, 1, 1, O, 1, O] , y_pred = [0, 0, 1, 0, 0, 1, O]
Our task is to implement a function called accuracy( ) \ which takes two
arguments yjrue, y-pred and calculates the accuracy of our model. The
result is rounded to four decimal places. In response, call the function
on our data and print the result to the console.
Expected result:

0.8571

165. The following list is given:


items = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Implement a function called flatten( ) , which takes the nested list and
returns the following:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Note: You only need to implement this function.

Solution:

def flatten(items):
result = []
for item in items:
result.extend(item)
return result

166. Implement a function called transfer_zeros() which takes the list


as an argument and return list with all zeros at the end.
Example:
[IN]: transfer_zeros([3, 4, 0, 2, 0, 5, 1, 6, 2])
[OUT]: [3, 4, 2, 5, 1, 6, 2, 0, 0]
Note: You only need to implement this function.
Solution:

def transfer_zeros(items):
result = []
counter = 0
for item in items:
if item == 0:
counter += 1
else:
result.append(item)
result.extend([0] * counter)
return result

167. Implement a function called arange() that takes three parameters:


start, stop, step and generates a list consisting of integers greater
than or equal to start and less than stop. The step parameter defaults
to 1 indicates the size of the step.
Example:
[IN]: arrange(0, 10)
[OUT]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[IN]: arange(0, 10, 2) [OUT]: [0, 2, 4, 6, 8]
Note: You only need to implement this function.
Solution:

def arange(start, stop, step=1):


result = []
for i in range(start, stop, step):
result.append(i)
return result

168. Implement a function called concatQ that accepts two lists in the
format given below:
u = [[1], [2]]
12 = [[3], [4]] and returns:
[[1, 3], [2, 4]]
Note: You only need to implement this function.
Solution:

def concat(l1, l2):


result = []
for i, j in zip(l1, l2):
result.append([i[0], j[0]])
return result

169. Implement a function called identityQ , which takes a natural


number as an argument and return an identity matrix (nested list).
Example:
[IN]: identity(2)
[OUT]: [[1, 0], [0, 1]]
[IN]: identlty(4)
[OUT]: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, O], [0, 0, 0, 1]]

Note: You only need to implement this function.

Solution:
def identity(n):
array = [[0]*n for i in range(n)]
for idx, item in enumerate(array):
item[idx] = 1
return array
170. Implement a function called fill_value( ) that returns a two-
dimensional array of height x width and fills it with a fixed value.
Arguments:
height - natural number, height of the array
width - natural number, width of the array
value - the value to fill the array
Example:
[IN]: fill_value(height=2, width=3, value=255)
[OUT]: [[255, 255, 255], [255, 255, 255]]
[IN]: fill_value(4, 2, 'a')
[OUT]: [['a', 'a'], ['a', 'a'], ['a', 'a'], ['a', 'a']]
Note: You onlv need to implement this function.
Solution:
def fill_value(height, width, value):
return [[value] * width for i in range(height)]
171. Implement a function called trace( ) that returns the trace of the
matrix. The matrix must be a square matrix.
Argument:
• array - nested list (two-dimensional matrix)
Example:
[IN]: trace([[l]])
[OUT]: 1
[IN]: trace([[l, 2], [4, 2]])
[OUT]: 3
[IN]: trace([[3, 4, 5], [5, 2, 1], [5, 7, 2]])
[OUT]: 7
Note: You onlv need to implement this function.

Solution:

def trace(array):
total = 0
for idx, item in enumerate(array):
total += item[idx]
return total

172. Implement a function called transposeQ that transposes the two-


dimensional matrix (nested list).
Argument:
• array - nested list (two-dimensional matrix)
Example:
Example:
[IN]: transpose([[l, 2, 3], [4, 5, 6]])
[OUT]: [[1, 4], [2, 5], [3, 6]]
[IN]: transpose([[1, 2], [3, 4], [5, 6]])
[OUT]: [[1, 3, 5], [2, 4, 6]]
[IN]: transpose([[1, 2, 3, 4], [5, 6, 7, 8]])
[OUT]: [[1, 5], [2, 6], [3, 7], [4, 8]]
Note: You onlv need to implement this function.
Solution:

def transpose(array):
width = len(array[0])
result = []

for i in range(width):
pair = []
for item in array:
pair.append(item[i])
result.append(pair)
return result

173. Implement a function called count_none() that counts all missing


values in the list.
Example:
[IN]: count_none([1, None, None, 5, None, 2])
[OUT]: 3
Note: You onlv need to implement this function.

Solution:

def count_none(items):
counter = 0
for item in items:
if not item:
counter += 1
return counter

174. Implement a function top_n() which extracts top n largest values


from the given list.
Arguments:
items - list of values
n - top n elements to extract
Example:
[IN]: top_n([4, 5, 2, 9, 5, 2, 8, 2, 8, 10], 3)
[OUT]: [10, 9, 8]
Note: You only need to implement this function.
Solution:
def top_n(items, n):
items.sort(reverse=True)
return items[:n]

175. Given the code below, insert the correct method on line 3 to get
the index at which the substring Bitcoin starts.

my_string = "In 2010, someone paid 10k Bitcoin for two pizzas."

print(my_string.)
176. Given the code below, use the correct function on line 3 in order
to obtain the distance between num1 and 0.

num1 = -11

num2 =

print(num2 == 11) #should result in True

177. Given the code below, use the correct function on line 4 in order
to raise num1 to the power of num2.
num1 = 10
num2 = 5
num3 =

print(num3 == 100000)

178. Given the code below, use the correct logical operator in between
the two expressions on line 1 in order for the final result to be False.

result = ((25 % 7 + 10 / 2) % 3 == 0) ((abs(-19) / 2 - 2) > 9)

print(result) #should return False


179. Given the code below, use the correct logical operator in between
the two expressions on line 1 in order for the final result to be True.

result = (min(pow(2, abs(3)), 9) == 3 ** 2 - 1) (66 % 20 + 2 > 2 **


3)

print(result) #should return True


180. Given the code below, use the correct code on line 3 to remove the element of mylist
located at index 5.
181.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']

my_list.

print(my_list)
182. Given the code below, use the correct method on line 3 in order to
add the element 'C++' at the end of mylist.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']

my_list.

print(my_list)
183. Given the code below, use the correct method on line 3 in order to
remove the element 30 from mylist.
my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']
my_list.
print(my_list)
184. Given the code below, use the correct method on line 3 in order to
return the index of the element 10.5 in mylist.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']

index = my_list.

print(index)
185. Given the code below, use the correct method on line 3 in order to
insert the element 77 at index 4 in mylist.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']

my_list.

print(my_list)

186. Given the code below, use the correct method on line 3 in order to
concatenate mylist with [100, 101,102], by adding the latter at the
end of mylist.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']

my_list.

print(my_list)
187. Given the code below, use the correct method on line 3 in order to
find out how many times does the element 20 occur in mylist.

my_list = [10, 10.5, 20, 30, 'Python', 'Java', 'Ruby']


howmany = my_list.
print(howmany)

188. Given the code below, use the correct function on line 3 in order
to sort the elements of mylist in ascending order.

my_list = [10, 10.5, 20, 30, 25.6, 19.25, 11.01, 29.99]

asc =

print(asc)
189. Given the code below, use the correct function (and argument) on line 3 in order to sort
the elements of mylist in descending order.
190.

my_list = [10, 10.5, 20, 30, 25.6, 19.25, 11.01, 29.99]

asc =

print(asc)
191. Given the code below, use the correct function on line 3 in order
to find out the smallest number in mylist.

my_list = [10, 10.5, 20, 30, 25.6, 19.25, 11.01, 29.99]


small =
print(small)
192. Given the code below, use the correct method on line 3 in order to
find out the number of elements in my_tup.

my_tup = ("Romania", "Poland", "Estonia", "Bulgaria", "Slovakia",


"Slovenia", "Hungary")

number =

print(number)
193. Given the code below, use the correct method on line 3 in order to
find out the index of Slovakia in my.tup.

my_tup = ("Romania", "Poland", "Estonia", "Bulgaria", "Slovakia",


"Slovenia", "Hungary")

index = my_tup.

print(index)
194. Given the code below, write code in order to perform tuple
assignment on line 3 and obtain the results below.

my_tup = ("Romania", "Poland", "Estonia")

print(ro + ", " + po + ", " + es) #returns 'Romania, Poland, Estonia'
195. Given the code below, use the correct code on line 3 in order to
delete the key-value pair associated with key 3. Do not use a method
as a solution for this exercise!

crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:


"XRP"}

print(crypto)
196. Given the code below, use the correct code on line 3 in order to
delete the key-value pair associated with key 3. This time, use a
method as a solution for this exercise!

crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:


"XRP"}

print(crypto)
197. Given the code below, use the correct code on line 3 in order to
verify that 7 is not a key in the dictionary.

crypto = {1: "Bitcoin", 2: "Ethereum", 3: "Litecoin", 4: "Stellar", 5:


"XRP"}

check =

print(check)
198. Given the code below, use the correct function on line 3 in order
to convert value to a string.

value = 10

conv =

print(type(conv))
199. Given the code below, use the correct function on line 3 in order
to convert value to an integer.

value = "10"

conv =

print(type(conv))
200. Given the code below, use the correct function on line 3 in order
to convert value to a floating-point number.

value = 10

conv =

print(type(conv))
201. Given the code below, use the correct function on line 3 to convert value to a list.
202.

value = "Hello!"

conv =

print(type(conv))
203. Given the code below, use the correct function on line 3 to convert
value to a tuple.

value = [1, 2, 3, 10, 20, 30]

conv =

print(type(conv))

204. Given the code below, use the correct function on line 3 to convert value to a frozen
set.
205.

value = (10, 20, 40, 10, 25, 30, 45)

conv =

print(type(conv))

205. Given the code below, use the correct function on line 3 to convert
value to a binary representation.

value = 10

conv =
print(conv)

206. Given the code below, use the correct function on line 3 in order to convert value to a
hexadecimal representation.
207.

value = 10

conv =

print(conv)
207 Given the code below, use the correct function on line 3 to convert
value from binary to decimal notation.

value = '0b1010'

conv =

print(conv)
ABOUT THE AUTHOR

“Edcorner Learning” and have a significant number of students on Udemy


with more than 90000+ Student and Rating of 4.1 or above.

Edcorner Learning is Part of Edcredibly.

Edcredibly is an online eLearning platform provides Courses on all trending


technologies that maximizes learning outcomes and career opportunity for
professionals and as well as students. Edcredibly have a significant number
of 100000+ students on their own platform and have a Rating of 4.9 on
Google Play Store – Edcredibly App.

Feel Free to check or join our courses on:

Edcredibly Website - https://www.edcredibly.com/

Edcredibly App –
https://play.google.com/store/apps/details?id=com.edcredibly.courses

Edcorner Learning Udemy - https://www.udemy.com/user/edcorner/

Do check our other eBooks available on Kindle Store.

You might also like