Skip to content

Commit 84b444a

Browse files
authored
Create calsses_exercises_python.py
1 parent e0ab87c commit 84b444a

File tree

1 file changed

+363
-0
lines changed

1 file changed

+363
-0
lines changed

calsses_exercises_python.py

+363
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,363 @@
1+
"""
2+
1. Write a Python class to convert an integer to a roman numeral.
3+
"""
4+
5+
class RomanNumeral:
6+
"""Roman Numerals class
7+
Rules:
8+
I = 1
9+
V = 5
10+
X = 10
11+
L = 50
12+
C = 100
13+
D = 500
14+
M = 1000
15+
16+
1. Repeating a numeral up to three times represents addition of the number.
17+
For example, III represents 1 + 1 + 1 = 3.
18+
Only I, X, C, and M can be repeated; V, L, and D cannot be, and there
19+
is no need to do so.
20+
21+
2. Writing numerals that decrease from left to right represents addition of the numbers.
22+
For example, LX represents 50 + 10 = 60 and XVI represents 10 + 5 + 1 = 16.
23+
24+
3. Writing a smaller numeral to the left of a larger numeral represents subtraction.
25+
For example, IV represents 5 - 1 = 4 and IX represents 10 - 1 = 9.
26+
To avoid ambiguity, the only pairs of numerals that use this subtraction rule are:
27+
IV 4 = 5 - 1
28+
IX 9 = 10 - 1
29+
XL 40 = 50 - 10
30+
XC 90 = 100 - 10
31+
CD 400 = 500 - 100
32+
CM 900 = 1000 - 100
33+
34+
4. To represent larger numbers, a bar over a numeral means to multiply the number by 1000.
35+
For example, D(bar) represents 1000 x 500 = 500,000 and M(bar) represents 1000 x 1000
36+
= 1,000,000, one million.***
37+
38+
*** this class only works for integers lower than 4000 (till 3999 including)
39+
"""
40+
41+
def __init__(self, integer):
42+
self.integer = integer
43+
self.roman = ''
44+
45+
roman_numerals = ['I','IV','V','IX','X','XL','L','XC','C','CD', 'D', 'CM', 'M']
46+
integers = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
47+
48+
n = self.integer
49+
for i,r in sorted(zip(integers, roman_numerals), reverse=True):
50+
while n//i > 0:
51+
self.roman += r
52+
n = n-i
53+
54+
x = int(input("please enter a number from 1 to 3999: "))
55+
var = RomanNumeral(x)
56+
print("the Roman numeral of your number is:", var.roman)
57+
print("your number in Hindu-Arabic numerals is:", var.integer)
58+
##print(var.__doc__)
59+
60+
"""
61+
2. Write a Python class to convert a roman numeral to an integer.
62+
"""
63+
class HinduArabic:
64+
"""HinduArabic class lets you convert roman numeral to hindu-arabic numeral
65+
Rules:
66+
I = 1
67+
V = 5
68+
X = 10
69+
L = 50
70+
C = 100
71+
D = 500
72+
M = 1000
73+
74+
1. Repeating a numeral up to three times represents addition of the number.
75+
For example, III represents 1 + 1 + 1 = 3.
76+
Only I, X, C, and M can be repeated; V, L, and D cannot be, and there
77+
is no need to do so.
78+
79+
2. Writing numerals that decrease from left to right represents addition of the numbers.
80+
For example, LX represents 50 + 10 = 60 and XVI represents 10 + 5 + 1 = 16.
81+
82+
3. Writing a smaller numeral to the left of a larger numeral represents subtraction.
83+
For example, IV represents 5 - 1 = 4 and IX represents 10 - 1 = 9.
84+
To avoid ambiguity, the only pairs of numerals that use this subtraction rule are:
85+
IV 4 = 5 - 1
86+
IX 9 = 10 - 1
87+
XL 40 = 50 - 10
88+
XC 90 = 100 - 10
89+
CD 400 = 500 - 100
90+
CM 900 = 1000 - 100
91+
92+
4. To represent larger numbers, a bar over a numeral means to multiply the number by 1000.
93+
For example, D(bar) represents 1000 x 500 = 500,000 and M(bar) represents 1000 x 1000
94+
= 1,000,000, one million.***
95+
96+
*** this class only works for integers lower than 4000 (till 3999 including)
97+
"""
98+
99+
def __init__(self, roman):
100+
self.integer = int()
101+
self.roman = roman
102+
103+
roman_numerals = ['IV','IX','XL','XC','CD','CM','I','V','X','L','C','D','M']
104+
105+
integers = [ 4, 9, 40, 90, 400, 900, 1, 5, 10, 50, 100, 500, 1000]
106+
107+
n = self.roman
108+
for i,r in zip(integers, roman_numerals):
109+
while n.rfind(r) != -1:
110+
self.integer += i
111+
n = n.replace(r , '', 1)
112+
113+
x = input("please enter a roman numeral using I, V, X, L, C, D, M letters only: ")
114+
var = HinduArabic(x)
115+
print("your number in Hindu-Arabic numerals is:", var.integer)
116+
print("the Roman numeral of your number is:", var.roman)
117+
##print(var.__doc__)
118+
119+
"""
120+
3. Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' and '].
121+
These brackets must be close in the correct order, for example "()" and "()[]{}" and "([]){}"are valid but
122+
"[)", "({[)]" and "{{{" are invalid.
123+
"""
124+
125+
class Parenthesis:
126+
def __init__(self, par_string):
127+
self.par_string = par_string
128+
129+
# not the most elegant solution, but it works. there is a great solution on w3resource site at
130+
# https://www.w3resource.com/python-exercises/class-exercises/python-class-exercise-3.php
131+
def is_valid(self):
132+
p = self.par_string
133+
open_par = ['(', '[', '{']
134+
close_par = [')', ']', '}']
135+
wrong_par = ['(]', '(}', '[)', '[}', '{)', '{]']
136+
137+
if len(p)%2 != 0:
138+
# check if length is not even, the string is invalid, no need to check further
139+
return False
140+
elif p[0] in close_par:
141+
# check if string starts with closing parenthesis, the string is invalid
142+
return False
143+
elif p[-1] in open_par:
144+
# check if string ends with opening parenthesis, the string is invalid
145+
return False
146+
else:
147+
# check if there is a wrong pair of open+close parenthesis from a wrong couples list
148+
for par in wrong_par:
149+
if p.find(par) != -1:
150+
return False
151+
# check if all closing parentheses have their opening counterpart before them
152+
for o, c in zip(open_par, close_par):
153+
while c in p:
154+
i = p.find(c)
155+
print(i)
156+
j = p.rfind(o, 0, i)
157+
print(j)
158+
if j == -1:
159+
return False
160+
else:
161+
p = p.replace(o, '', 1)
162+
p = p.replace(c, '', 1)
163+
print(p)
164+
if p == '':
165+
return True
166+
else:
167+
return False
168+
169+
print(Parenthesis("{}{{}}{{").is_valid())
170+
171+
"""
172+
4. Write a Python class to get all possible unique subsets from a set of distinct integers.
173+
Input : [4, 5, 6]
174+
Output : [[], [6], [5], [5, 6], [4], [4, 6], [4, 5], [4, 5, 6]]
175+
"""
176+
177+
class Subsets:
178+
179+
def all_subsets(self, my_set):
180+
output = [[]]
181+
for i in range(len(my_set)):
182+
output.append([my_set[i]])
183+
k = len(my_set)
184+
while k>=i:
185+
for j in range(i+1, k):
186+
output.append([my_set[i]]+my_set[j:k])
187+
k = k - 1
188+
return sorted(output)
189+
190+
191+
print(Subsets().all_subsets([4, 5, 6]))
192+
193+
194+
"""
195+
5. Write a Python class to find a pair of elements (indices of the two numbers) from a
196+
given array whose sum equals a specific target number.
197+
Input: numbers= [10,20,10,40,50,60,70], target=50
198+
Output: 3, 4
199+
"""
200+
201+
# solution 1 (finds first pair only)
202+
class EqualsTarget:
203+
def find_pair(self, iterable, target):
204+
for i in iterable:
205+
for j in iterable[iterable.index(i)+1:]:
206+
if i+j == target:
207+
return iterable.index(i), iterable.index(j)
208+
return -1, -1
209+
210+
print(EqualsTarget().find_pair([10,20,10,40,50,60,70], 50))
211+
212+
# solution 2 (finds all pairs)
213+
class EqualsTarget:
214+
def find_pair(self, iterable, target):
215+
pairs = []
216+
for i,n in enumerate(iterable):
217+
for j,m in enumerate(iterable[i+1:]):
218+
if n+m == target:
219+
pairs.append((i, j+i+1))
220+
return pairs
221+
222+
print(EqualsTarget().find_pair([-10,10,20,10,40,50,60,70,0,-20], 50))
223+
224+
"""
225+
6. Write a Python class to find the three elements that sum to zero from a set
226+
of n real numbers.
227+
Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
228+
Output : [[-10, 2, 8], [-7, -3, 10]]
229+
"""
230+
231+
class SumZero:
232+
def three_sum_zero(self, iterable):
233+
triples = []
234+
for i, n in enumerate(iterable):
235+
for j, m in enumerate(iterable[i+1:]):
236+
for x, y in enumerate(iterable[i+1+j+1:]):
237+
if n+m+y == 0:
238+
triples.append([n, m, y])
239+
return triples
240+
241+
242+
print(SumZero().three_sum_zero([-25, -10, -7, -3, 2, 4, 8, 10]))
243+
244+
245+
"""
246+
7. Write a Python class to implement pow(x, n).
247+
"""
248+
249+
class ImplementPow:
250+
def imp_pow(self, x, n):
251+
return x ** n
252+
253+
print(ImplementPow().imp_pow(3, 4))
254+
255+
"""
256+
8. Write a Python class to reverse a string word by word. - Go to the editor
257+
Input string : 'hello .py'
258+
Expected Output : '.py hello'
259+
"""
260+
261+
# solution 1
262+
class ReverseString:
263+
def reversed(self, astring):
264+
split_string = astring.split()
265+
reversed_string = ''
266+
for word in split_string[::-1]:
267+
reversed_string += word+' '
268+
return reversed_string
269+
270+
print(ReverseString().reversed('hello .py nice to meet you'))
271+
272+
# solution 2
273+
class ReverseString:
274+
def reversed(self, astring):
275+
split_string = astring.split()
276+
reversed_string = ' '.join(reversed(split_string))
277+
return reversed_string
278+
279+
print(ReverseString().reversed('hello .py nice to meet you'))
280+
281+
"""
282+
9. Write a Python class which has two methods get_String and print_String.
283+
get_String accepts a string from the user and print_String prints the string in upper case.
284+
"""
285+
286+
class MyString:
287+
def __init__(self):
288+
self.string = ''
289+
290+
def get_String(self):
291+
s = input('input your string: ')
292+
self.string = s
293+
294+
def print_String(self):
295+
print(self.string.upper())
296+
297+
var = MyString()
298+
var.get_String()
299+
var.print_String()
300+
print(var.string)
301+
302+
"""
303+
10. Write a Python class named Rectangle constructed by a length and width and
304+
a method which will compute the area of a rectangle.
305+
"""
306+
307+
class Rectangle:
308+
def __init__(self, l, w):
309+
self.length = l
310+
self.width = w
311+
312+
def area(self):
313+
a = self.length * self.width
314+
return a
315+
316+
X = Rectangle(4,5)
317+
print(X.area())
318+
319+
"""
320+
11. Write a Python class named Circle constructed by a radius and two methods which
321+
will compute the area and the perimeter of a circle.
322+
"""
323+
from math import pi
324+
325+
class Circle:
326+
def __init__(self, r):
327+
self.radius = r
328+
329+
def area(self):
330+
return round(pi * self.radius * self.radius, 2)
331+
332+
def perimeter(self):
333+
return round(2 * pi * self.radius, 2)
334+
335+
X = Circle(8)
336+
print(X.area())
337+
print(X.perimeter())
338+
print(X.radius)
339+
340+
"""
341+
12. Write a Python program to get the class name of an instance in Python.
342+
"""
343+
"""
344+
instance.__class__
345+
The class to which a class instance belongs.
346+
definition.__name__
347+
The name of the class, function, method, descriptor, or generator instance.
348+
"""
349+
class Circle:
350+
""" construct a circle """
351+
def __init__(self, r):
352+
self.radius = r
353+
def area(self):
354+
return round(3.1415 * self.radius * self.radius, 2)
355+
356+
def perimeter(self):
357+
return round(2 * 3.1415 * self.radius, 2)
358+
359+
X = Circle(8)
360+
print(X.__class__)
361+
print(type(X).__name__)
362+
##print(type(X).__bases__)
363+
##print(type(X).__dict__)

0 commit comments

Comments
 (0)