-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprograms.py
More file actions
180 lines (89 loc) · 2.79 KB
/
programs.py
File metadata and controls
180 lines (89 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# create a class which acts as an iterable
l = [1, 2, 3, 4]
class Sample:
def __init__(self, iterable):
self.iterable = iterable
def __iter__(self):
return iter(self.iterable)
s = Sample(l)
# print(dir(s))
#
# for item in s:
# print(item)
#################################################################################################
# custom iterator to generate the numbers from 1 to 10
class Numbers:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start > self.end:
raise StopIteration
a = self.start
self.start += 1
return a
n = Numbers(1, 5)
# for item in n:
# print(item)
# print(next(n))
# print(next(n))
# print(next(n))
# print(next(n))
# print(next(n))
#################################################################################################
# from 10 to 1
class CountDown:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start < self.end:
raise StopIteration
a = self.start
self.start -= 1
return a
#####################################################################################################
# to return all the even numbers from 1 to 50
class Even:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start > self.end:
raise StopIteration
a = self.start
self.start += 1
if a % 2 == 0:
return a
####################################################################################################
# custom iterators to return prime numbers from 1 to 50
class Prime:
def __init__(self, end, start=0):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start > self.end:
raise StopIteration
num = self.start
self.start += 1
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
return num
p = Prime(10)
for i in p:
if i:
print(i)
#############################################################################################
# return even indexed elements in the list
# return the elements in the list in reversed order