Exercises on Lists,...
1 Lists, String, Dict
Write a program to add two lists index-wise ( list1[0] with list2[0], list1[1] with list2[1], and so
on... .
list1 = ["Sa", "ala", "ya ", "al"]
list2 = ["lam", "yka", "amir", "bilad"]
gives : ['Salam', 'alayka', 'ya amir', 'albilad']
Write a function which return the Concatenation of two lists in the following order
list2 = ["(x)", "(y)"]
list1 = ["sin ", "cos "]
gives : ['sin (x)', 'sin (y)', 'cos (x)', 'cos (y)']
Write a program to nd a value in the list, and if it is present, replace it with another.
list1 = [5, 10, 15, 20, 25, 50, 20]
replaces 20 by 200
gives ---> [5, 10, 15, 200, 25, 50, 200]
Convert 2 lists into a dictionary in a way that item from list1 is the key and item from list2 is
the value like this:
l1 = ['Ten', 'Twenty', 'Thirty']
l2 = [10, 20, 30]
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
Merge two Python dictionaries into one, that is:
dict1 = {'Ten': 10, 'Twenty': 20}
dict2 = {'Twenty': 20,'Thirty': 30, 'Fourty': 40}
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40}
Count the number of characters in a string and create a dictionary for it.
Sample String : google.com'
Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
Get a string made of the rst 2 and the last 2 chars from a given a string. If the string length
is less than 2, return instead of the empty string. Like :
Sample String : 'w3resource'
Expected Result : 'w3ce'
2 Calculate Expression
Read a mathematical expression from the keyboard, ( x : is the name of the variable)
Check its validity, use for example x=1 and evaluate it.
read the range for the variable (in ascending order , and the number of the step (integer positive
value). If too large or too small, use default values ( I = [−5, 5] and N = 20). We accept
10 ≤ N ≤ 50 and I=[a,b] where −10 ≤ a , b ≤ 50 and a < b
display in two columns, the value of variable and the value of the expression
use try/except block to control the inputs.
Here is an example
exp=input("give a math expression : ")
give a math expression : sin(x)+2
Replace x par a value to check it (for example 1). If error read again, else read the variable range.
Give a math expression : sin(x)
Give the interval and step -pi, pi,20
Variable x Expression Value
-3.14 -0.00
-2.83 -0.31
-2.51 -0.59
-2.20 -0.81
...................