While Loop and for Loop (2)
While Loop and for Loop (2)
while loop:
for loop:
If we want to execute some action every element present in some iterable or when we
know the number of iteration we use for loops.
iterable can be any collection data type and for loop body will execute for all the
elements or characters present in the iterable.
There is no need to keep track of number of iterationsas for loop does it implicitly.
Need a reference variable to refer every element or character of the iterable.
No need to increment or decrement reference variable manually.
Syntax:
for r_v in iterable:
Statements
range(start,end,stop):
it is used in for loop in place of iterable.
Returns a range object sequence of numbers starting from zero by default,
increments by 1, and ends at a specified number.
To loop through a set of code a specified number of times we use the
range function.
start and end index always included.
Syntax:
for rev_var in range(SI,EI,SV):
statements
Throw away variable(_):
It is used for ignoring certain values and if we just wants to keep count of
iterations we can use this.
Unpacking iterables/sequences:
Enumerate():
It returns an enumerate object.
Iterable can be passed as an argument.
Iterable can be a sequence, an iterator or some other object which supports iteration.
Returns a tuple containing a count(from start which defaults to zero)and the values
obtained from iterating over the iterable.
Syntax:
enumerate(iterable):
reversed(iterator):
zip():
the zip() class takes iterable(one or more), segregate them in a tuple and return the
output.
it returns a zip object which has list of tuples stored inside object.
if multiple iterables passed then they should have similar length else least items will
decide the length of the new iterable.
sequencial iterables only.
zip(i1,i2,i3......in)
zip_longest():
to include all the elements of iterables of different length while aggregating we can
use zip longest().
We have to import it from itertools.
It will map the extra elements with none by default.
Syntax:
zip_longest(i1,i2,i3……in, fillvalue = None)
defaultdict():
It is used when the key has to be initialised and update at the same time.
Unlike normal dictionary here there is no need to check the condition for the presence
of key.
Even if the key is not present it will create the key and initialises to its default value.
Later the default value get updated to the desired value.
It should be imported from collections module.
Syntax:
From collections import defaultdict
D = defaultdict(datatype of value of output)
Transfer statements:
1. Break:
It will break the condition depending on some condition.
2. Continue:
It will skip current iteration and continue next iteration.
3. Pass:
When its not necessary to execute some programmable blocks then we can use
pass keyword to make that code idle.
The else keyword in any loop specifies a block of code to be executed when the loop
is finished with any break.
Syntax:
for r_v in iterable:
statements
else:
statements
comprehensions in loops
1. with lists:
it is a elegant way to define and create list based on existing list.
list_var = [operation(insertion / updation /print) for loop if condition ]
2. with sets:
s_name = {operation(insertion / updation /print) for loop if condition }
3. with dict:
d_n = {key:value--operation(insertion / updation /print) for loop if condition }
drawbacks of comprehensions:
When we try to imply comprehension with strings it will consider complete statement
as normal string. And where as if we try the same with tuple it will create generator object
not tuple object.
while loop solved programs
5. wap to iterate over a string and print each character separating by ",".
str1 = input()
c=0
print(f"the string is {str1} and length of the string is {len(str1)}")
while c < len(str1):
print(str1[c], end=", ")
c += 1
8. write a program to print all the vowels present inside a given string.
print("enter any string")
str1=input()
c=0
while c<len(str1):
if str1[c] in "aeiouAEIOU":
print(str1[c])
c+=1
16. wap to merge 2 characters of 2 strings into a single string by taking characters
alternatively. (s1 = good, s2 = well o/p: gwoeoldl)
s1 = input()
s2 = input()
s3 = ""
i=0
j=0
while i < len(s1) or j < len(s2):
if i < len(s1):
s3 += s1[i]
i += 1
if j < len(s2):
s3 += s2[j]
j += 1
print(s3)
19.wap to enter name, percentage and marks in a dictionary and print information
on the screen.
print("enter name :")
name=input()
print("enter the percentage:")
percentage = float(input())
print("enter the marks:")
marks=int(input())
d={}
d.setdefault("name",name)
d.setdefault("percentage",percentage)
d.setdefault("marks",marks)
print(d)
20.wap to prompt user to enter some name until they enter "Python"
name = ""
while name != "python":
name = input()
print("prompted python")
21.wap to iterate in a list check for even numbers inside list and add them
l = [10,20,25,30,45,60]
c=0
sum = 0
while c < len(l):
if isinstance(l[c],int) and l[c] % 2 == 0:
sum = sum + l[c]
c += 1
print(sum)
23.wap to iterate inside dictionary fetch all the keys. if keys are integers multiply them
d = {'a': 100, 455:200, 'b':300, 60:400}
dkey = list(d.keys()) #dkey=[a,455,b,60]
print(dkey)
c=0
mul = 1
while c <= len(dkey):
if isinstance(dkey[c],int):
mul = mul * dkey[c]
c += 1
print(mul)
24. wap to iterate in a list if list elements are string type then store them in separate list
list1 = ["hello", 10, 20.55, True, "hai", "bye"]
list2 = []
c=0
while c < len(list1):
if isinstance(list1[c],str):
list2.append(list1[c])
c+=1
print(list2)
25. wap to iterate inside a list check if it has nested list if yes merge them.
list1 = ["hello", 10, 20.55, True, "hai", "bye",[25,90,False,"good"]]
list2 = []
c=0
while c < len(list1):
if isinstance(list1[c],list):
list2.extend(list1[c])
list1.remove(list1[c])
c += 1
print(list1+list2)
26. create a list using while loop, take list elements from user.
l = []
c=1
while c <= 5:
l.append(input())
c+= 1
print(l)
27. wp to print 2 tables.
n=1
while n<=10:
res = 2 * n
print(f"2 * {n} = {res}")
n += 1
print(res)
30. wp to print name which are starts with vowels in given list
l = ["Asha", "Sushma", "Nishma", "Oshma", "Eshma", "Kashma"]
n=0
while n<=len(l)-1:
if l[n][0].lower() in "aeiou":
print(f"{l[n]} starts with vowels")
n += 1
s = {10,20,"hello",True,75.55}
for rv in s:
print(rv)
for ch in str1[::-1]:
print(ch)
6. wap to access dictionary keys and values using enumerate and other methods.
d = {1:100,2:200,3:300,4:400}
for rv,key in enumerate(d):
print(key,end = " ")
#accessing dictionary keys
for key in d:
print(key, end = " ")
print()
for key in d.keys():
print(key, end="*")
print()
for key in d.items():
print(key[0])
print()
for key,value in d.items():
print(key)
print(value)
# accessing values
for key in d:
print(d[key], end=",")
for value in d.values():
print(value, end=" ")
for value in d.items():
print(value[1])
for key, value in d.items():
print(value)
print(key, value)
8. wap to create a dictionary of characters and its ASCII value pair by taking string as
input
d.update({ch:ord(ch)})
str1 = input()
d={}
for ch in str1:
#d[ch] = ord(ch)
d[ord(ch)] = ch
print(d)
9. wap to create a dictionary of word and its length pair from a string(sentence).
s = "python is an easiest programming language"
d={}
word = s.split()
for rv in word:
d[rv] = len(rv)
print(d)
11. wap to create a dictionary with word and its count pair from the given sentence.
s = "my day is good day or bad day or just a day"
str1 = "my day is good day or bad day or just a day"
w_list = str1.split()
print(w_list)
d = {}
for rv in w_list:
d[rv] = w_list.count(rv)
print(d)
(or)
num = int(input())
for i in range(2,num-1):
if num % i == 0:
break
else:
print("its a prime number")
15. wap to print nth prime numbers.(while loop, one extra variable)
num = int(input())
for i in range(2,num-1):
if num % i == 0:
break
else:
print("its a prime number")
17.wap to check the very first integer which is greater than 400 and print it.
l = [10,50,80,600,400,300,100]
for rv in l:
if rv > 400:
print(f"greater value: {rv}")
break
print(rv)
22.wap to check wether the elements of list are lesser than 100 sing nested loops and loops
with else block
l1 = [10,20,30,40,50,60]
for rv in l1:
if rv >= 100:
print("element is greater than 100")
break
print(rv)
else:
print("every value is valid")
26.wp to print first and last char of each name in the list
l = ["sunil", "anil", "suresh", "mahesh", "dinesh"]
for name in l: #name="sunil"
print(name[0],name[-1])
print(res)
28. wp if number is even the print its square else print its cube
l = [2, 4, 5, 1, 9, 7, 3]
for i in l: #i = 2
if i % 2 == 0:
print(f"the squre of {i} is {i**2}")
else:
print(f"the cube of {i} is {i ** 3}")
29. wp to create a new list of separate even number and odd number
l = [2, 4, 5, 1, 9, 7, 3]
evn = []
odd = []
for i in l:
if i % 2 == 0:
evn.append(i)
else:
odd.append(i)
print(evn)
print(odd)
print(res)
[(4, 8), (16, 64), (25, 125), (1, 1), (36, 216), (81, 729), (49, 343), (9, 27)]
31. wp to create a new list of reversing each name from the list.
names = ["sunil", "dinga", "penga", "harsha", "manga"]
res = []
for name in names:
res.append(name[::-1])
print(res)
32. wp to create a new list of company name in the given emails list.
print(ids)
33. wp to create a new list of individual and collection data type from list
datas = [20.12, True, [10, 20], {1, 2}. 2+6j, {"a":10}, 100]
ind = []
col = []
for data in datas:
if isinstance(data, (int, float, complex, bool)):
ind.append(data)
else:
col.append(data)
print(ind)
print(col)
34.wp to create a new list, if the name is palindrome then convert to upper case and add to
list, read names from tuple.
names = ("mom", "Komal", "pop", "nayan", "malayalam", "eye")
n = []
for name in names: #name=mom
res = ''
for i in range(len(name)-1, -1, -1): #i=2
res += name[i]
if res == name:
n += [res.upper()]
print(n)
35.wp to create a list with fruit name and along with index
fruits = ["apple", "orange", "banana", "mango", "grapes"]
logic1
n=0
f = []
for fruit in fruits:
f.append((fruit,n))
n += 1
print(f)
or
logic2
f = []
for i in range(0, len(fruits)):
f.append((fruits[i],i))
print(f)
[('apple', 0), ('orange', 1), ('banana', 2), ('mango', 3), ('grapes', 4)]
print(set(res))
{('fb', 3), ('gmail', 2), ('google', 2), ('yahoo', 3)}
print(hol)
39.wp to create a list if the price if the product is more than 1000 then add the product name
to a list
products = {"Asian-paint":4000, "Mobile":90000, "Hen":500, "Pen":5, "Watch":2500}
pro = []
for item in products.items():
if item[1]>1000:
pro.append(item[0])
print(pro)
40.wp create a list, if a key is a individual DT then add key and data type as its value
i/p:- elemnts = {10:"Ind", "hai":"Colle", [10]:"Colction", True:"Inddual", (11,22):"Colltion"}
o/p [(10, <class 'int'>), (True, <class 'bool')]
res = []
print(res)
print(d)
{'a': 2, 'M': 2, 'i': 2, 'A': 1, 'h': 1, 'H': 1, 'B': 1}
45.wp to create a dictionary with mobile and its count pair with and without inbuilt function
mobiles = ["mi", "iphone", "vivo", "poco", "samsung", "iphone", "mi", "vivo", "mi",
"relame"]
d = {}
for mobile in mobiles:
d[mobile] = mobiles.count(mobile)
print(d)
or
d = {}
for mobile in mobiles:
if mobile not in d:
d[mobile] = 1
else:
d[mobile] += 1
print(d)
{'mi': 3, 'iphone': 2, 'vivo': 2, 'poco': 1, 'samsung': 1, 'relame': 1}
print(d)
{'A': 2, 's': 1, 'o': 2, 'P': 1, 'O': 2, 'S': 1, 'H': 2, 'J': 1, 'V': 1}
print(d)
{'com': 2, 'in': 3, 'org': 1}
49.wp to create a dictionary 1st character as "key" and names starts with same 1st charcter
should be the value
names = ["anu", "dinesh", "abhi", "divya", "suresh", "dileep", "mahesh"]
{"a":["anu", "abhi"]}
d = {}
for name in names:
if name[0] not in d:
d[name[0]] = [name]
else:
d[name[0]].append(name)
print(d)
50.wp to create a dictionary length as key and same length as list of value
fruits = ["apple", "grapes", "kiwi", "mango", "papaya", "bannana", "cherry", "berry"]
d = {}
for fruit in fruits:
if len(fruit) not in d:
d[len(fruit)] = [fruit]
else:
d[len(fruit)].append(fruit)
print(d)
51.wp to create a dictionary, with list of even and odd number sepratley(intially we should
only add key and empty list)
numbers = [22, 34, 89, 10, 2, 4, 9, 7, 1, 56]
d = {"even":[], "odd":[]}
for num in numbers:
if num%2 == 0:
d["even"].append(num)
else:
d["odd"].append(num)
print(d)
{'even': [22, 34, 10, 2, 4, 56], 'odd': [89, 9, 7, 1]}
sequence = "hello"
index_ele = {}
print(index_ele)
sentence = "hai hello hai world hai good morning world hello hello"
words = sentence.split()
word_count = {}
print(word_count)
# using default_dict
sentence = "hai hello hai world hai good morning world hello hello"
words = sentence.split()
word_count = defaultdict(int)
for word in words:
word_count[word] = word_count[word] + 1
print(word_count)
(or)
s = "hello"
d = {}
for rv in s:
if rv not in d:
d[rv] = ord(rv)
print(d)
o/p:{'h': 104, 'e': 101, 'l': 108, 'o': 111}
57. create a dictionary with character and count pair, with only repeated character
s = "hello all... good morning... welcome all..."
d = {}
for rv in s:
if s.count(rv) > 1:
d[rv]= s.count(rv)
print(d)
o/p:{'e': 3, 'l': 7, 'o': 5, ' ': 5, 'a': 2, '.': 9, 'g': 2, 'm': 2, 'n': 2}
print(d)
o/p:
['hello', 'all', 'how', 'are', 'you', 'hope', 'you', 'all', 'doing', 'well', 'well', 'well']
{'hello': 1, 'all': 2, 'how': 1, 'are': 1, 'you': 2, 'hope': 1, 'doing': 1, 'well': 3}
59.break: if list elements are greater than 100 then i will break
l = [10,20,30,300, 100, 40,50]
for rv in l:
if rv > 100: #true means break false means continue to looping
break
else:
print(rv)
60. continue:
s = "hello"
for rv in range(0,len(s)):
if rv % 2 == 1: #true, skip and continue to next loop
continue
else:
print(rv)
63. Wap to check if the number is greater than 100 break the loop.
l = [10,20,30,300,10,50]
for r in l:
if r > 100:
break
else:
print(r)
else:
print("hello")
n = eval(input())
num = 0
p_c = 0
while p_c < n:
if num > 1:
for i in range(2,num): #(2,2)
if num % i ==0:
break
else:
p_c +=1
if p_c == n:
print(num)
num +=1
66.
s1 = "hello"
s2 = "hai"
s3 = "brave"
s4 = "mind"
from itertools import zip_longest
zv = list(zip_longest(s1,s2,s3,s4))
for r1 in zv:
if None not in r1:
new = r1
s5 = ""
for r2 in new:
s5 += r2
print(s5)
67.
sum1 = 0
t = (1,2,3,4)
for rv in t:
sum1 += rv
print(sum1)
68. wap to iterate through a string and access index value and corresponding character from a
string using enumerate
str1= input()
for i in enumerate(str1):
print(i,end=",")
69. wap to iterate through a string and access only index value using enumerate
str1= input()
for i in enumerate(str1):
print(i[0],end=",")
70. wap to iterate through a string and access only values(characters) using enumerate
str1= input()
for i in enumerate(str1):
print(i[1],end=",")
73.wap unpack the string in for loop definition itself and pring all characters
for i,e in enumerate(str1):
print(e)
74.wap to check each character from the string is vowel or not by using enumerate:
str1 = input()
for i,e in enumerate(str1):
if e in "aeiouAEIOU":
print(e)
75.wap to check each word of the sentence are even length or not,if even prepare a list of
them.
str1 = input()
l = str1.split()
l1= []
for i,e in enumerate(l):
if len(e) % 2 == 0:
l1.append(e)
print(l1)
76.
s = "hello"
print(list(reversed(s)))
l = [10,20,30,40,50]
print(list(reversed(l)))
t =(10,20,30,40,50)
print(tuple(reversed(t)))
77.
s1 = {10,20,30,40,50}
#print(set(reversed(s1)))
#as set type is unordered we cannot reverse it.
78.
d = {'a':100,'b':200,'c':300}
print(list(reversed(d))
#only key layer is visible to interpreter so that only reversed.
79.
s = "hello"
s1 = "apple"
s2 = "orange"
print(list(zip(s,s1,s2)))
80. wap to create a new list of power numbers(one list elements should be base number and
second list elements should be considered as their power).
l =[5,6,7,8,9]
l1=[4,3,2,1,0]
l_p = []
for e1,e2 in zip(l,l1):
e3 = e1 ** e2
l_p.append(e3)
print(l_p)
81. wap to find sum of cosecutive numbers of two different lists
l =[5,6,7,8,9]
l1=[4,3,2,1,0]
for e1,e2 in zip(l,l1):
e3 = e1 + e2
print(e3)
l =["0","1","2","3","4","5","6","7","8","9","10"]
l1=["zero","one","two","three","four","five","six","seven","eight","nine","ten"]
l2=[]
for e1,e2 in zip(l,l1):
e3 = e1+":"+e2
l2.append(e3)
print(l2)
83.
l = [10,20,30,40,50]
l1 = ["pinki","rinki","chinki","dimpi"]
84.wap to sagregate 4 different strings and concatinate same indexed characters together
using ziplongest if no character is none
s1 = input()
s2 = input()
s3 = input()
s4 = input()
from itertools import zip_longest
print(str(zip_longest(s1,s2,s3,s4)))
85.
s = "abracadadraca"
d = {}
for ch in s:
d[ch] = s.count(ch)
print(d)
86.
s1 = "abracadadraca"
d1 = defaultdict(int)
for ch in s1:
d1[ch] += 1 #it will take 0 and
print(d1)
87.
s2 = "abracadadraca"
d1 = {}
for ch in s2:
if ch not in d1:
d1[ch] = 1
else:
d1[ch] += 1
print(d1)
88.
s = "hello word uou"
d = {}
for ch in s:
if ch in "aeiouAEIOU":
d[ch] = s.count(ch)
print(d)
89.
s1 = "hello word uou"
d1 = defaultdict(int)
for ch in s:
if ch in "aeiouAEIOU":
d1[ch] += 1
print(d)
90.
s = "hello word uou"
d = {}
for ch in s:
if ch in "aeiouAEIOU":
if ch not in d:
d[ch] = 1
else:
d[ch] += 1
print(d)
91.
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
s1 = []
for e1, e2 in zip(a, b):
s1 += [e1+e2]
#s1.append(e1 + e2)
print(s1)
92.
names = ["apple", "google", "apple", "yahoo", "facebook", "google"]
d = {}
for na in names:
if names.count(na) > 1:
d[na] = names.count(na)
print(d)
(or)
names = ["apple", "google", "apple", "yahoo", "facebook", "google"]
d = defaultdict(int)
for na in names:
if names.count(na) > 1:
d[na] += 1
print(d)
93.
names = ["apple", "google", "apple", "yahoo", "facebook", "google"]
#names = {"apple" : [0,2] , "google" : [1,5]}
d = {}
94.
names = ['steve', 'john', 'adam']
l = []
for cnt in names:
l.append(len(cnt))
print(l)
95.
s1 = "abcd"
l = []
for ind, ch in enumerate(s1):
l.append((ind, ch))
print(l)
96.
l = []
for no in range(1, 51):
if no % 2 == 0:
l.append(no)
print(l)
l1 = [ ]
97.
s = ["hello", "bye", "appl"]
s1 = []
for ch in s:
if ch[0] in "aeiouAEIOU":
s1.append(ch)
print(s1)
(or)
(or)
101.
print(d)
103.
from collections import defaultdict
d = defaultdict(int)
for rv in words:
d[rv] += 1
print(d)
104. print only first 5 characters of the string
str1 = input()
if len(str1) >= 5:
for rv in range(0,len(str1)):
print(str1[rv])
if rv == 4:
break
else:
print("insufficient characters")
str1 = input()
for rv in range(0,len(str1)):
if rv % 2 == 0:
print(str1[rv])
106.wap to fetch each character from a string and check whether they are vowels or not. if
vowels print them.
str1 = input()
for rv in str1:
if rv in "aeiouAEIOU":
print(rv)
107 .wap to fetch each character from a string and check whether they are vowels or not. if
vowels print them.
# if not append them in a list
str1 = input()
s = ""
l=[]
for rv in str1:
if rv in "aeiouAEIOU":
s += rv #s = s+rv,
print()
else:
l.append(rv)
print(s)
print(l)
108. wap to fetch all the characters and remove the repated characters from the string.
str1 = input()
s = ""
for rv in str1:
if rv not in s:
s += rv
print(s)
109.
l1 = [1, 2, 3, 2, 1]
l2 = []
for no in l1:
if no not in l2:
l2.append(no)
print(l2)
110.
ll = []
[ll.append(no) for no in l1 if no not in ll] #here we can't write and inbuilt method directly so
we need a empty list
print(ll)
111.
l3 = list(dict.fromkeys(l1))
print(l3)
112.
a = [1,2,3,4]
b = [1,2,3,4,5,8]
print(set(b) - set(a))
for ch in b:
if ch not in a:
print(ch, end=" ")
print()
113.
114.
a = "hello"
print([*a[::2]])
l = []
l.extend((a[::2]))
print(l)
115.
names = ['apple', 'amazon', 'google', 'yah']
nn = []
for ch in names:
if len(ch) % 2 == 0:
nn.append(ch)
print(nn)
116.
l = [[1,2,3], [4,5,6], [7,8,9]]
res = 0
for le in range(len(l)):
print(sum(l[le]))
res = res + sum(l[le])
print(res)
117.
words = ["hi", "hello", "python"]
rev_wd = []
for ch in reversed(words):
rev_wd.append(ch[::-1])
print(rev_wd)
rev_wd1 = []
for ch in range(-1,-len(words)-1,-1):
rev_wd1.append(words[ch][::-1])
print(rev_wd1)
118.
# 1 - 50 even comprehension
l1 = [ n for n in range(51) if n % 2 == 0]
print(l1)
l1 = [ n for n in range(0,51,2) ]
print(l1)
119.
names = ["apple", "yahoo", "apple", "apple"]
for no in range(len(names)):
if names.count(no) >1:
# for num in range(no+1,len(names)):
# if names[no] == names[no+1]:
# break
print(names[no])
120.
st = "hello today is bad"
d = {}
for ch in st.split():
d[ch] = len(ch)
print(d)
121.
d1 = { ch: len(ch) for ch in st.split() }
print(d1)
122.
d = {'a':1, 'b':2}
d1 = {}
for ke in d:
d1[d[ke]] = ke
print(d1)
123.
s = "helloe"
d = {}
for ch in s:
if s.count(ch) > 1:
d[ch] = s.count(ch)
print(d)
124.
st = "today is tuess day"
s1 = {}
for ind, word in enumerate(st.split()):
if ind % 2 == 0:
s1[ind] = word[::-1]
else:
s1[ind] = word
print(s1)
125.
stmt = "hello world welcome to python hi"
d = {}
word = stmt.split()
for ch in word:
if ch[0] not in d:
d[ch[0]] = [ch]
else:
d[ch[0]].append(ch)
print(d)
126.
d1 = { ch[0] : [ch] if ch[0] not in {} else ch for ch in word }
print(d1)
127.
d = {'a':'hello', 'b':100, 'c':10.1, 'd':'world'}
d1 = {}
for key, value in d.items():
if isinstance(value, str):
d1[key] = value[::-1]
else:
d1[key] = value
print(d1)
d2 = { key : value[::-1] if isinstance(value, str) else value for key, value in d.items() }
print(d2)
128.
s = "helloworld"
d1 = {}
for ch in s:
if ch not in d1:
d1[ch] = 1
else:
d1[ch] += 1
print(d1)
print(d)
131.
names = ['apple', 'mango', 'apple', 'juice']
d1 = {}
for ch in names:
if ch not in d1:
d1[ch] = 1
else:
d1[ch] += 1
print(d1)
132.
names = ['apple', 'mango', 'apple', 'juice']
d1 = {}
for ch in names:
if names.count(ch) > 1:
if ch not in d1:
d1[ch] = 1
else:
d1[ch] += 1
print(d1)
133.
items = ['lotus-flower', 'lily-flower', 'cat-animal', 'sunflow-flower', 'dog-animal']
d1 = {}
for ch in items:
for name, catr in [ch.split('-')]:
if catr not in d1:
d1[catr] = [name]
else:
d1[catr].append(name)
print(d1)
134.
files = ['apple.txt', 'yahoo.pdf', 'gmail.pdf', 'google.txt', 'amazon.pdf']
d = {}
for ch in files:
for name, ext in [ch.split('.')]:
if ext not in d:
d[ext] = [name]
else:
d[ext].append(name)
print(d)
135.
numbers = [1,2,3,4,5,6,7,8,9,10]
evn = []
odd = []
d1 = {}
for no in numbers:
if no % 2 == 0:
evn.append(no)
else:
odd.append(no)
d1[0] = evn
d1[1] = odd
print(d1)
136.
name = ['apple', 'google', 'apple', 'yahoo', 'yahoo', 'google'] # {'apple': [0,2]}
d1 = {}
for ind, name in enumerate(name):
if name not in d1:
d1[name] = [ind]
else:
d1[name].append(ind)
print(d1)
FUNCTIONS :
l = [1,2,3,4,5,6,7,8,9,10]
def even(num):
if num % 2 == 0:
return num
print(list(map(even,l)))
(or)
l = [1,2,3,4,5,6,7,8,9,10]
even = map(lambda num : num%2 == 0, l)
print(list(even))
(or)
l = [1,2,3,4,5,6,7,8,9,10]
def even(num):
if num % 2 == 0:
return num
print(list(filter(even, l)))
(or)
l = [1,2,3,4,5,6,7,8,9,10]
even = lambda num: num%2==0
print(list(filter(even, l)))
2. wap to build a list of strings with even length from a list using filter
l = ["good", "boom", "spark","light","color","colour"]
even = lambda var : len(var)%2 == 0
print(list(filter(even, l)))
def prime_no(num):
if num >1:
for i in range(2,num):
if num % i == 0:
break
else:
return True
print(list(filter(prime_no,range(2,20))))
6.
n = 20
num = 0
prime = 0
while prime < n:
if num > 1:
for i in range(2,num):
if num % i == 0:
break
else:
prime += 1
if prime == n:
print(num)
num += 1
7.
num = int(input())
for i in range(2,num-1):
if num % i == 0:
break
else:
return True
ASSIGNMENT :
ON FOR LOOP:
24. wap to create a dictionary of index value and element pair of any iterable.
25.wap to count the number of characters in a string and create a dictionary with character
and count pair
s = "good morning"
d = {}
for ch in s:
d[ch] = s.count(ch)
print(d)
26.wap to create a dictionary with character and count pair if the character is vowel
27.wap to create a dictionary with character and count pair if the character is consonent
28.wap to create a dictionary with character and count pair if the character is digit
29.wap to create a dictionary with character and count pair if the character is spl characters
30. wp to print laptop name only if the price of the laptop is more than 30000 and it should
be "i5" generation.
laptop = {"hp":["i5", 20000], "dell":["amd", 18000], "sony":["i5", 45000]}
31. wp print only boys name whose age is more than 18.
shadi = {"Sunil":["Male","Bang",19], "Prabhu":["Male","UK",28], "Dingi":
["Female","Kashmir", 55], "Atul":["Male","Pune",15]}
32. wap to display * in pyramid(assignment)
33.wap to print odd numbers from 1 to 10 using continue keyword
34.wap to print the characters of string in both forward and reverse direction.
35.wap to display the positions of substring from the main string(pos of words in sentence)
36. wp list of names which are less than 6 character.
37. wap to count list elements and print only even numbers from the list
i/p: l = [5,10,15,17,88,45,66,73,98]
38. wap to print the elements if the length of list is even, else add one element and make it
even.
39.wap to fetch last character of each word from the given sentence
sen = "india is my country all indians are my brothers and sisters"
40.wap to fetch all even character words from a sentence.
sen = "jony jony yes papa eating sugar no papa"
41.wap to check if the word is of odd length from given string and find mid character of each
word.
sen= "twinckle twinckle little star how i wonder what you are ?"