Week2
Week 2
Variables
del var1, var2
Types
String
Lists: in/append/len/remove/sort/split/max/min/sum/pop
Tuples: read-only lists/comma
Dictotionaries
Loops
for/while
else in for/while loop
break/continue
break: stop all iretations continue: skip rest and start next iretation
if-else/if-elif-else
Functions
Plotting
matplotlib: python plot package pyplot: a convenient interface to the matplotlib
plt.plot(color,linewidth,linestyle etc.) plt.xlim plt.xticks plt.yticks plt.ylim plt.show()
Exercise
1-Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
2-Write a Python program to multiplies all the items in a list.
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
3-Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Sample List : [(0, 5), (-1, 2), (4, 4), (2, 3), (3, 1)]
def last(n): return n[-1]
def sort_list_last(tuples):
return sorted(tuples, key=last)
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
4-Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
# Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color = [x for (i,x) in enumerate(color) if i not in (0,4,5)]
print(color)
5-Write a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers that are divisible by 5 in a comma separated sequence.
# Sample Data : 0100,0011,1010,1001,1100,1001
items = []
num = [x for x in input().split(',')]
for p in num:
x = int(p, 2)
if not x%5:
items.append(p)
print(','.join(items))
6-Write a Python program to get the Fibonacci series between 0 to 50.
Note : The Fibonacci Sequence is the series of numbers : 0, 1, 1, 2, 3, 5, 8, 13, 21, .... Every next number is found by adding up the two numbers before it.
while y<50:
print(y)
x,y = y,x+y
7-Write a Python program to check the validity of password input by users. Validation :
Note : PLEASE IMPORT package re and use function search • At least 1 letter between [a-z] and 1 letter between [A-Z]. • At least 1 number between [0-9]. • At least 1 character from [$#@]. • Minimum length 6 characters. • Maximum length 16 characters.
import re
p= input("Input your password")
x = True
while x:
if (len(p)<6 or len(p)>12):
break
elif not re.search("[a-z]",p):
break
elif not re.search("[0-9]",p):
break
elif not re.search("[A-Z]",p):
break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
print("Valid Password")
x=False
break
if x:
print("Not a Valid Password")
8-Write a (recursive) function which calculates the factorial of a given number. Use exception handling to raise an appropriate exception if the input parameter is not a positive integer, but allow the user to enter floats as long as they are whole numbers.
def factorial(n):
ni = int(n)
if ni != n or ni <= 0:
raise ValueError("%s is not a positive integer." % n)
if ni == 1:
return 1
return ni * factorial(ni - 1)
9-Make a program that plots the function g(y)=(e^−y)sin(4y) for y∈[0,4] using a red solid line.
Use 500 intervals for evaluating points in [0,4]. Store all coordinates and values in arrays. Set labels on the axis and use a title “Damped sine wave”. [HINT : from numpy import exp and sin both]
import numpy as np
import matplotlib.pyplot as plt
from numpy import exp, sin # avoid np. prefix in g(y) formula
def g(y):
return exp(-y)*sin(4*y)
y = np.linspace(0, 4, 501)
values = g(y)
plt.figure()
plt.plot(y, values, 'r-')
plt.xlabel('$y$'); plt.ylabel('$g(y)$')
plt.title('Damped sine wave')
plt.savefig('tmp.png'); plt.savefig('tmp.pdf')
plt.show()
10-Add a to the above (two plots), a black dashed curve for the function h(y)=(e^−1.5y)sin(4y). Include a legend for each curve.
import numpy as np
import matplotlib.pyplot as plt
from numpy import exp, sin # avoid np. prefix in g(y) and h(y)
def g(y):
return exp(-y)*sin(4*y)
def h(y):
return exp(-(3./2)*y)*sin(4*y)
y = np.linspace(0, 4, 501)
plt.figure()
plt.plot(y, g(y), 'r-', y, h(y), 'k--')
plt.xlabel('$y$'); plt.ylabel('$g(y)$')
plt.title('Damped sine wave')
plt.legend(['g', 'h'])
plt.savefig('tmp.png'); plt.savefig('tmp.pdf')
plt.show()
Last updated
Was this helpful?