-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathematics.py
More file actions
1196 lines (882 loc) · 33.1 KB
/
mathematics.py
File metadata and controls
1196 lines (882 loc) · 33.1 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# neccessary dependencies
from decimal import Decimal
import turtle
from pandas import Series
# for patenting my name
print("Thanks for using mathematics module created by viraj sharma to view source code goto https://github.com/virajsharma2000/python_apps/blob/main/mathematics.py")
# dictnoary of number names for time to text
number_names = {
1: "one", 2: "two", 3: "three", 4: "four", 5: "five",
6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten",
11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen",
16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty",
21: "twenty-one", 22: "twenty-two", 23: "twenty-three", 24: "twenty-four", 25: "twenty-five",
26: "twenty-six", 27: "twenty-seven", 28: "twenty-eight", 29: "twenty-nine", 30: "thirty",
31: "thirty-one", 32: "thirty-two", 33: "thirty-three", 34: "thirty-four", 35: "thirty-five",
36: "thirty-six", 37: "thirty-seven", 38: "thirty-eight", 39: "thirty-nine", 40: "forty",
41: "forty-one", 42: "forty-two", 43: "forty-three", 44: "forty-four", 45: "forty-five",
46: "forty-six", 47: "forty-seven", 48: "forty-eight", 49: "forty-nine", 50: "fifty",
51: "fifty-one", 52: "fifty-two", 53: "fifty-three", 54: "fifty-four", 55: "fifty-five",
56: "fifty-six", 57: "fifty-seven", 58: "fifty-eight", 59: "fifty-nine", 60: "sixty"
}
# intresting mathematicians
mathematicians = {
"Isaac Newton": {
"Description": "English mathematician who co-invented calculus and made significant contributions to classical mechanics and optics.",
"BirthDate": "1643-01-04",
"DeathDate": "1727-03-31",
"KeyWorks": ["Calculus", "Laws of Motion", "Universal Gravitation"]
},
"Leonhard Euler": {
"Description": "Swiss mathematician known for his work in graph theory, topology, and introducing the modern notation for functions and constants like 'e'.",
"BirthDate": "1707-04-15",
"DeathDate": "1783-09-18",
"KeyWorks": ["Euler's Formula", "Graph Theory", "Number Theory"]
},
"Carl Friedrich Gauss": {
"Description": "German mathematician who contributed to number theory, geometry, statistics, and the theory of magnetism.",
"BirthDate": "1777-04-30",
"DeathDate": "1855-02-23",
"KeyWorks": ["Gaussian Elimination", "Prime Number Theorem", "Electromagnetic Theory"]
},
"Euclid": {
"Description": "Ancient Greek mathematician often referred to as the 'Father of Geometry'.",
"BirthDate": "300 BCE",
"DeathDate": "unknown",
"KeyWorks": ["Euclidean Geometry", "Elements"]
},
"Pythagoras": {
"Description": "Ancient Greek mathematician and philosopher known for the Pythagorean theorem and contributions to number theory.",
"BirthDate": "570 BCE",
"DeathDate": "495 BCE",
"KeyWorks": ["Pythagorean Theorem", "Numerical Mysticism"]
},
"Srinivasa Ramanujan": {
"Description": "Indian mathematician who made significant contributions to number theory, infinite series, and continued fractions despite limited formal training.",
"BirthDate": "1887-12-22",
"DeathDate": "1920-04-26",
"KeyWorks": ["Ramanujan Prime", "Partitions", "Modular Forms"]
},
"Alan Turing": {
"Description": "British mathematician known as the father of computer science, instrumental in cracking the Enigma code during World War II.",
"BirthDate": "1912-06-23",
"DeathDate": "1954-06-07",
"KeyWorks": ["Turing Machine", "Artificial Intelligence", "Cryptography"]
},
"Ada Lovelace": {
"Description": "English mathematician considered the first computer programmer for her work on Charles Babbage's Analytical Engine.",
"BirthDate": "1815-12-10",
"DeathDate": "1852-11-27",
"KeyWorks": ["First Algorithm", "Computing"]
},
"Blaise Pascal": {
"Description": "French mathematician known for Pascal's Triangle, contributions to probability theory, and early work on calculating machines.",
"BirthDate": "1623-06-19",
"DeathDate": "1662-08-19",
"KeyWorks": ["Pascal's Triangle", "Probability Theory", "Pascal's Law"]
},
"Hypatia": {
"Description": "Greek mathematician, philosopher, and astronomer; one of the earliest female mathematicians in recorded history.",
"BirthDate": "360 CE",
"DeathDate": "415 CE",
"KeyWorks": ["Conic Sections", "Astronomy", "Philosophy"]
},
"Andrew Wiles": {
"Description": "British mathematician who solved Fermat's Last Theorem, a problem that had been unsolved for over 350 years.",
"BirthDate": "1953-04-11",
"DeathDate": "N/A",
"KeyWorks": ["Fermat's Last Theorem", "Elliptic Curves"]
},
"John von Neumann": {
"Description": "Hungarian-American mathematician known for his work in quantum mechanics, game theory, and computer science.",
"BirthDate": "1903-12-28",
"DeathDate": "1957-02-08",
"KeyWorks": ["Game Theory", "Von Neumann Architecture", "Set Theory"]
},
"Brahmagupta": {
"Description": "Indian mathematician and astronomer who introduced rules for arithmetic operations with zero and negative numbers.",
"BirthDate": "598 CE",
"DeathDate": "668 CE",
"KeyWorks": ["Brahmasphutasiddhanta", "Zero and Negative Numbers", "Algebraic Rules"]
},
"Aryabhata": {
"Description": "Ancient Indian mathematician and astronomer who introduced the concept of zero and approximated pi with remarkable accuracy.",
"BirthDate": "476 CE",
"DeathDate": "550 CE",
"KeyWorks": ["Aryabhatiya", "Trigonometry", "Pi Approximation"]
},
"Bhaskara I": {
"Description": "Indian mathematician who worked on the sine function and continued Aryabhata's work on astronomy and trigonometry.",
"BirthDate": "600 CE",
"DeathDate": "680 CE",
"KeyWorks": ["Sine Function", "Number System", "Astronomy"]
},
"Bhaskara II": {
"Description": "Indian mathematician who made significant contributions to calculus, algebra, and number systems.",
"BirthDate": "1114 CE",
"DeathDate": "1185 CE",
"KeyWorks": ["Bijaganita", "Lilavati", "Differential Calculus"]
},
"Madhava of Sangamagrama": {
"Description": "Indian mathematician and astronomer who laid the foundations for calculus and pioneered infinite series expansions.",
"BirthDate": "1350 CE",
"DeathDate": "1425 CE",
"KeyWorks": ["Madhava Series", "Infinite Series", "Trigonometry"]
},
"Narendra Karmarkar": {
"Description": "Indian mathematician and computer scientist known for the development of the Karmarkar algorithm for linear programming.",
"BirthDate": "1957-06-06",
"DeathDate": "N/A",
"KeyWorks": ["Karmarkar's Algorithm", "Optimization", "Computational Mathematics"]
},
"C. R. Rao": {
"Description": "Indian statistician known for his contributions to estimation theory, multivariate analysis, and the Cramér-Rao bound.",
"BirthDate": "1920-09-10",
"DeathDate": "2023-08-23",
"KeyWorks": ["Cramér-Rao Bound", "Multivariate Statistics", "Fisher Information"]
},
"Harish-Chandra": {
"Description": "Indian-American mathematician known for his work in representation theory and harmonic analysis.",
"BirthDate": "1923-10-11",
"DeathDate": "1983-10-16",
"KeyWorks": ["Harmonic Analysis", "Representation Theory", "Lie Groups"]
}
}
# dictnoary of devanrangi digits
devarangi_numbers = {
0: '०', # शून्य (Shunya)
1: '१', # एक (Ek)
2: '२', # दो (Do)
3: '३', # तीन (Teen)
4: '४', # चार (Chaar)
5: '५', # पाँच (Paanch)
6: '६', # छह (Chhah)
7: '७', # सात (Saat)
8: '८', # आठ (Aath)
9: '९' # नौ (Nau)
}
# reversed devarangi number
reversed_devarangi_numbers = {
'०': 0, # Shunya
'१': 1, # Ek
'२': 2, # Do
'३': 3, # Teen
'४': 4, # Chaar
'५': 5, # Paanch
'६': 6, # Chhah
'७': 7, # Saat
'८': 8, # Aath
'९': 9 # Nau
}
# constant pi value
pi_value = 3.141592653589793
# keprekar's constant
kaprekar_constant = 6174
# calculates square root of a number
def square_root(number):
square_root = number ** 0.5
return square_root
# calculates cube root of a number
def cube_root(number):
return number ** 0.3333333333333333
# calculates square of a number
def square(number):
square = number ** 2
return square
# calculates cube of the number
def cube(number):
return number ** 3
# calculates that the number is perfect square or not
def is_perfect_square(number):
return number ** 0.5 == int(number ** 0.5)
# calculates that the cube is perfect cube or not
def is_perfect_cube(number):
return number ** 0.3333333333333333 == int(number ** 0.3333333333333333)
# calculates hypotenus length of right angle tringle
def hypotenus(x,y):
hypotenus = (x ** 2 + y ** 2) ** 0.5
return hypotenus
# converts radians to degrees
def radians_to_degrees(radians):
degrees = radians * (180 / pi_value)
return degrees
# converts degrees to radians
def degrees_to_radians(degrees):
radians = degrees * (pi_value / 180)
return radians
# calculates sine
def sine(opposite,hypotenus):
sine = opposite / hypotenus
return sine
# calculates cosine
def cosine(adjecent,hypotenus):
cosine = adjecent / hypotenus
return cosine
# triangle detection using angle measures
def is_it_triangle(x,y,z):
is_it_triangle = x + y + z == 180
return is_it_triangle
# finds the base raised to a given power
def base(exponent,value):
base = 0
number = 0
while number > 1 or number == 0:
if number == 0:
number = value / exponent
base += 1
else:
number = number / exponent
base += 1
if base ** exponent == value:
return base
else:
raise ValueError('no base found for {} and {}'.format(exponent,value))
# calculates circumfrence
def circumfrence(diameter):
circumfrence = pi_value * diameter
return circumfrence
# calculates circle area
def circle_area(radius):
circle_area = pi_value * radius ** 2
return circle_area
# calculates diameter using radius
def diameter(radius):
diameter = radius * 2
return diameter
# calculates radius using diameter
def radius(diameter):
radius = diameter / 2
return radius
# generates pythogorean triplets of a number
def get_pythogorean_triplets(number):
triplet = '{} square + {} square = {} square'.format(number * 2,number ** 2 - 1,number ** 2 + 1)
return triplet
# detects that the number is even number
def is_it_even_number(number):
is_it_even_number = number % 2 != 0
return is_it_even_number
# calculates triangle area
def triangle_area(base,height):
triangle_area = 0.5 * base * height
return triangle_area
# calculates paralellogram area
def paralellogram_area(base,height):
paralellogram_area = base * height
return paralellogram_area
# calculates rectangle perimeter
def rectangle_perimeter(length,breadth):
rectangle_perimeter = length * 2 + breadth * 2
return rectangle_perimeter
# calculates rectangle area
def rectangle_area(length,breadth):
rectangle_area = length * breadth
return rectangle_area
# calculates paralellogram perimeter
def paralellogram_perimeter(base,height):
paralellogram_perimeter = base * 2 + height * 2
return paralellogram_perimeter
# calculates triangle perimeter
def triangle_perimeter(s1,s2,s3):
triangle_perimeter = s1 + s2 + s3
return triangle_perimeter
# detects that the number is negitive integer
def is_it_negitive_integer(number):
is_it_negitive_integer = number < 0
return is_it_negitive_integer
# gets multiplication table of a number
def table(number):
table = ''
for i in range(10):
table += '{} x {} = {}\n'.format(number,i + 1,(i + 1) * number)
return table
# gets additive inverse of a number
def aditive_inverse(number):
aditive_inverse = number * (-1)
return aditive_inverse
# gets factors of a number
def factors(number):
return [num for num in range(1, number + 1) if number % num == 0]
# gets hcf of 2 numbers
def hcf(first_number,second_number):
factors1 = factors(first_number)
factors2 = factors(second_number)
common_factors = []
for factor in factors1:
if factor in factors2:
common_factors.append(factor)
hcf = max(common_factors)
return hcf
# detects that number is prime number
def is_it_prime_number(number):
is_it_prime_number = len(factors(number)) == 2
return is_it_prime_number
# calculates prime factors of the numbers
def prime_factorize(num):
minimum_prime_number_divisible = 0
prime_factors = []
while num > 1:
minimum_prime_number_divisible = min([n for n in factors(num) if is_it_prime_number(n)])
prime_factors.append(minimum_prime_number_divisible)
num //= minimum_prime_number_divisible
return prime_factors
# gets factorial of a number (without recursion)
def factorial(number):
factorial = number
if number == 1:
return 1
else:
while number != 1:
number -= 1
factorial *= number
return factorial
# calculates the percentage
def percentage(consumption,total):
percentage = consumption / total * 100
return percentage
# convertes km to meter
def km_to_meter(km):
meter = float(km * 1000)
return meter
# convertes meter to km
def meter_to_km(meter):
km = meter / 1000
return km
# convertes meter to cm
def meter_to_cm(meter):
cm = float(meter * 100)
return cm
# convertes cm to meter
def cm_to_meter(cm):
meter = cm / 100
return meter
# convertes cm to mm
def cm_to_mm(cm):
mm = float(cm * 10)
return mm
# convertes mm to cm
def mm_to_cm(mm):
cm = mm / 10
return cm
# gets the standard form of number (small numbers of decimal form) number to be inputted in string
def standard_form(num):
if Decimal(num) > Decimal('0.0') and Decimal(num) < Decimal('1.0') and str(num) == num:
exponent = 0
while int(float(num)) == 0:
num = Decimal(num) * Decimal('10.0')
num = num.normalize()
exponent -= 1
return f"{num} * 10 ** {exponent}"
else:
raise ValueError('the number type might not be string or the number value might not be decimal')
# split digits of integer into a list (without any conversions)
def split_into_digits(num):
digits = []
while num > 0:
digits.append(num % 10)
num = (num - num % 10) // 10
return digits[::-1]
# combines array of digits into number (without any conversions)
def combine_digits(digits):
num = 0
for digit in digits:
num = num * 10 + digit
return num
# gets number of iterations to applied on number for kaprekar's routine
def iterations_of_keprekar_routine(num):
iterations = 0
while num != kaprekar_constant:
splitted_digits_of_number = split_into_digits(num)
ascending_digits = []
while splitted_digits_of_number:
ascending_digits.append(max(splitted_digits_of_number))
splitted_digits_of_number.remove(max(splitted_digits_of_number))
num = abs(combine_digits(ascending_digits) - combine_digits(ascending_digits[::-1]))
if num > 0:
iterations += 1
else:
raise ValueError('Is a repdigit number')
return iterations
# check weather integer is palindrome
def is_palindrome(num):
return split_into_digits(num) == digits[::-1]
# seprates number into commas (using international system)
def seperate_digits_of_number(n, seperator = ','):
commas_seperated_number = ''
digits_added = 0
while n > 0:
commas_seperated_number += str(n % 10)
n = (n - n % 10) // 10
digits_added += 1
if digits_added == 3:
commas_seperated_number += seperator
digits_added = 0
commas_seperated_number = commas_seperated_number[::-1]
if len(commas_seperated_number) > 0:
if commas_seperated_number[0] == seperator:
return commas_seperated_number[1:len(commas_seperated_number)]
else:
return commas_seperated_number
else:
return "0"
# converts integer to devrangi number
def convert_to_devarangi_number(number):
devarangi_number = ''
for digit in split_into_digits(number):
devarangi_number += devarangi_numbers.get(digit)
return devarangi_number
def convert_to_english_number(devarangi_number):
number = 0
for digit in devarangi_number:
number = number * 10 + reversed_devarangi_numbers.get(digit)
return number
# gets the number of cuts in a circle to break circle to number of pieces
def minimum_cuts(number_of_pieces_to_break):
if number_of_pieces_to_break > 1:
return number_of_pieces_to_break // 2 if number_of_pieces_to_break % 2 == 0 else number_of_pieces_to_break
else:
return 0
# gets the type of triangle (returns none in string if the sides do not form triangle)
def type_of_triangle(side1, side2, side3):
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2:
if side1 == side2 and side2 == side3:
return "equilateral"
if side1 != side2 and side2 != side3 and side1 != side3:
return "scalene"
if side1 == side2 or side2 == side3 or side1 == side3:
return "isosceles"
else:
return "none"
# gets the expanded form of a number
def expanded_form(number):
expanded_form = []
number_position = 0
while number > 0:
expanded_form.append(number % 10 * 10 ** number_position)
number = (number - number % 10) // 10
number_position += 1
return expanded_form
# gets the lcm of the number
def lcm(number1, number2):
return (number1 * number2) // hcf(number1, number2)
# performs all operations on fraction and has some more features of fraction
class Fraction:
def __init__(self, fraction):
fraction = fraction.replace(' ', '')
if fraction[1] != '*':
self.numerator = int(fraction.split('/')[0])
self.denominator = int(fraction.split('/')[1])
self.whole_number = 1
else:
self.numerator = int(fraction.split('/')[0].split('*')[1])
self.denominator = int(fraction.split('/')[1])
self.whole_number = int(fraction.split('*')[0])
# converts fraction to improper fraction
def improper_fraction(self):
return Fraction(f'{self.denominator * self.whole_number + self.numerator}/{self.denominator}')
# converts fraction object to string
def to_string(self):
if self.whole_number > 1:
return f'{self.whole_number}*{self.numerator}/{self.denominator}'
else:
return f'{self.numerator}/{self.denominator}'
# simplifies the fraction
def simplify(self):
if self.whole_number == 1:
hcf_of_fraction = hcf(numerator, denominator)
return Fraction(f'{self.numerator // hcf_of_fraction}/{self.denominator // hcf_of_fraction}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# checks weather the fraction is simplified
def is_simplified(self):
if self.whole_number == 1:
hcf_of_fraction = hcf(numerator, self.denominator)
return hcf_of_fraction == 1
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# reciprocals the fraction
def reciprocal(self):
if self.whole_number == 1:
return Fraction(f'{self.denominator}/{self.numerator}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# converts fraction to mixed fraction
def mixed_fraction(self):
quotient, remainder = divmod(self.numerator, self.denominator)
return Fraction(f'{quotient}*{remainder}/{self.denominator}')
# adds two fractions
def __add__(self, other):
if self.whole_number == 1 and other.whole_number == 1:
lcm_of_denominators = lcm(self.denominator, other.denominator)
numerator1, numerator2 = lcm_of_denominators // self.denominator * self.numerator, lcm_of_denominators // other.denominator * other.numerator
return Fraction(f'{numerator1 + numerator2}/{lcm_of_denominators}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# subtracts two fractions
def __sub__(self, other):
if self.whole_number == 1 and other.whole_number == 1:
lcm_of_denominators = lcm(self.denominator, other.denominator)
numerator1, numerator2 = lcm_of_denominators // self.denominator * self.numerator, lcm_of_denominators // other.denominator * other.numerator
return Fraction(f'{numerator1 - numerator2}/{lcm_of_denominators}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# multiplies two fractions
def __mul__(self, other):
if self.whole_number == 1 and other.whole_number == 1:
return Fraction(f'{self.numerator * other.numerator}/{self.denominator * other.denominator}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# divides two fractions
def __truediv__(self, other):
if self.whole_number == 1 and other.whole_number == 1:
return Fraction(f'{self.numerator * other.denominator}/{self.denominator * other.numerator}')
else:
raise ValueError('you must first convert the fraction into improper fraction, check in documentation')
# has three features related to (x, y) coordinates
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# calculates distance and direction between two points
def __sub__(self, other):
direction = ''
distance = square_root(square(other.x - self.x) + square(self.y - other.y))
if other.x > self.x:
direction += 'N'
if other.x < self.x:
direction += 'S'
if other.y > self.y:
direction += 'E'
if other.y < self.y:
direction += 'W'
return {'distance': distance, 'direction':direction, 'MidPoint': Point((self.x + other.x) / 2, (self.y + other.y) / 2)}
# converts point into tuples
def to_tuple(self):
return (self.x, self.y)
# has all the features related to algebric or numeric expressions
class Expression:
def __init__(self, expression):
self.expression = expression
self.constants = 0
self.numbers = 0
for char in expression:
self.constants += char.isalpha()
# splits expression into terms
def split_into_terms(self):
expression = self.expression.replace(' ', '').replace('(', '').replace(')', '')
terms_list = []
idx = 0
for charecter in expression:
if charecter.isalpha() or charecter.isdigit() or charecter == '/' or charecter == '*':
if len(terms_list) > 0:
terms_list[len(terms_list) - 1] += charecter
else:
terms_list.append(charecter)
else:
terms_list.append(charecter)
return terms_list
# checks that the 2 terms are like terms or not
def __eq__(self, other):
if len(self.split_into_terms()) == 1 and len(other.split_into_terms()) == 1:
variables_of_term1 = ''
variables_of_term2 = ''
for charecter in self.split_into_terms()[0]:
if charecter.isalpha():
variables_of_term1 += charecter
for charecter in other.split_into_terms()[0]:
if charecter.isalpha():
variables_of_term2 += charecter
return variables_of_term1 == variables_of_term2 and any(variables_of_term1) and any(variables_of_term2)
# identifies that the expression is algebric or not
def is_algebric_expression(self):
for term in self.split_into_terms():
for charecter in term:
if charecter.isalpha():
return True
return False
# gets the coefficient of the constant or a variable
def coefficient(self, variable_or_constant):
if variable_or_constant.isalpha() or variable_or_constant.isdigit():
if self.expression.index(variable_or_constant) == len(self.expression) - 1:
coefficient = self.expression[self.expression.index(variable_or_constant) - 1]
elif self.expression.index(variable_or_constant) == 0:
coefficient = self.expression[self.expression.index(variable_or_constant) + 1]
else:
coefficient = self.expression[self.expression.index(variable_or_constant) - 1] + self.expression[self.expression.index(variable_or_constant) + 1]
coefficient = '-1' if coefficient == '-' else '1' if coefficient == '+' else coefficient
return coefficient.replace('+', '') if coefficient.startswith('+') else coefficient
# splits algebric expression into factors
def factorize(self):
factors_of_expression = []
for term in self.split_into_terms():
for char in term:
if char == '-':
factors_of_expression.append(-1)
elif char.isdigit():
factors_of_expression += prime_factorize(int(char))
elif char.isalpha():
factors_of_expression.append(char)
return factors_of_expression
# common factor of two terms (without brackets)
def find_common_factor(self, other):
if len(self.split_into_terms()) == 1 and len(other.split_into_terms()) == 1:
factors1 = self.factorize()
factors2 = other.factorize()
common_factors = []
for factor in factors1:
if factor in factors2 and factor not in common_factors:
common_factors.append(factor)
return common_factors
# expands an exprssion (with brackets)
def expand_expression(self):
self.expression = self.expression.replace(' ', '')
expression = ''
splitted_expression = self.expression.split(')')
expression_outside_paranthesis = splitted_expression[len(splitted_expression) - 1]
if self.expression[0] == '(':
common = self.expression.split(')(')[0] + ')'
expression_inside_paranthesis = self.expression.split(')(')[1].split(')')[0]
else:
common = self.expression.split('(')[0]
expression_inside_paranthesis = self.expression.split('(')[1].split(')')[0]
for term in Expression(expression_inside_paranthesis).split_into_terms():
if not term.startswith('+') and not term.startswith('-'):
if term.isalpha():
expression += common + term
elif common.isalpha():
expression += term + common
else:
expression += common + '*' + term
else:
if term.replace(term[0], '').isalpha():
expression += term[0] + common + term.replace(term[0], '')
elif common.isalpha():
expression += term + common
else:
expression += term[0] + common + '*' + term.replace(term[0], '')
return Expression(expression + expression_outside_paranthesis)
# has few features related to time like convert it to text representation or convert 24 hour time to 12 hour time or calculate difference between two times
class Time:
def __init__(self, time):
minute = int(time.split(':')[1])
hour = int(time.split(':')[0])
if hour == 0:
self.hour = 24
if hour <= 24 and minute <= 59 and minute >= 0:
self.hour = hour
self.minute = minute
else:
raise ValueError('invalid time')
# converts time to text
def convert_to_text(self):
past = ''
to = ''
if self.minute == 15:
past = 'quater'
elif self.minute == 30:
past = 'half'
elif self.minute >= 45:
if self.minute == 45:
to = 'quater'
else:
to = number_names.get(60 - self.minute)
elif self.minute > 0:
past = number_names.get(self.minute)
if past:
return f'{past} past {number_names.get(self.hour)}'
elif to:
return f'{to} to {number_names.get(self.hour + 1)}'
elif not past and not to:
return f'{number_names.get(self.hour)} o clock'
# converts 24 hour clock time to 12 hour clock time
def twelve_hour_time(self):
if self.hour < 13:
if self.minute < 9:
return f'{self.hour}:0{self.minute} AM'
else:
return f'{self.hour}:{self.minute} AM'
else:
if self.minute < 9:
return f'{self.hour - 12}:0{self.minute} PM'
else:
return f'{self.hour - 12}:{self.minute} PM'
# gets difference between two times (in minutes or hours or secs)
def __sub__(self, other):
mins1 = self.hour * 60 + self.minute
mins2 = other.hour * 60 + other.minute
return mins1 - mins2
# shows the analog format of digital format
def analog_format(self, clock_image_path):
hour_angle = self.hour * 30 + self.minute * 0.5
minute_angle = self.minute * 6
t = turtle.Turtle()
turtle.bgpic(clock_image_path)
t.left(90)
t.right(hour_angle)
t.forward(50)
t.width(10)
t.backward(50)
t.width(10)
t.setheading(90)
t.width(5)
t.right(minute_angle)
t.width(5)
t.forward(100)
# performs all operations on matrix and has few features of matrix
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
# adds metrices
def __add__(self, other):
result_matrix = []
for row in zip(self.matrix, other.matrix):
r = []
for num in zip(row[0], row[1]):
r.append(num[0] + num[1])
result_matrix.append(r)
if len(self.matrix) > len(result_matrix):
idx = 0
for row in self.matrix:
if idx > len(other.matrix) - 1:
result_matrix.append(row)
idx += 1
if len(other.matrix) > len(result_matrix):
idx = 0
for row in other.matrix:
if idx > len(self.matrix) - 1:
result_matrix.append(row)
idx += 1
return Matrix(result_matrix)
# subtracts metrices
def __sub__(self, other):
result_matrix = []