-
Notifications
You must be signed in to change notification settings - Fork 1
/
session2.py
78 lines (65 loc) · 2.34 KB
/
session2.py
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
# KINDLY GO THROUGH TEST FILE TO UNDERSTAND
from typing import List
import time
import gc
import sys
# Here in this code we will be leaking memory because we are creating cyclic reference.
# Find that we are indeed making cyclic references.
# Eventually memory will be released, but that is currently not happening immediately.
# We have added a function called "clear_memory" but it is not able to do it's job. Fix it.
# Refer to test_clear_memory Test in test_session2.py to see how we're crudely finding that
# this code is sub-optimal.
class Something(object):
def __init__(self):
super().__init__()
self.something_new = SomethingNew(None)
def __repr__(self):
return hex(id(self))
class SomethingNew(object):
def __init__(self, i: int = 0, something: Something = None):
super().__init__()
self.i = i
self.something = something
def __repr__(self):
return hex(id(self))
def add_something(collection: List[Something], i: int):
something = Something()
something.something_new = SomethingNew(i, something)
collection.append(something)
def reserved_function():
# to be used in future if required
pass
def clear_memory(collection: List[Something]):
# adding gc collect to clear the memory
collection.clear()
gc.collect()
def critical_function():
collection = list()
for i in range(1, 1024 * 128):
add_something(collection, i)
clear_memory(collection)
# Here we are suboptimally testing whether two strings are exactly same or not
# After that we are trying to see if we have a particular character in that string or not
# Currently the code is suboptimal. Write it in such a way that it takes 1/10 the current time
# DO NOT CHANGE THIS PROGRAM
def compare_strings_old(n):
a = 'a long string that is not intered' * 200
b = 'a long string that is not intered' * 200
for i in range(n):
if a == b:
pass
char_list = list(a)
for i in range(n):
if 'd' in char_list:
pass
# YOU NEED TO CHANGE THIS PROGRAM
def compare_strings_new(n):
a = sys.intern('a long string that is not intered' * 200)
b = sys.intern('a long string that is not intered' * 200)
for i in range(n):
if a is b:
pass
char_list = list(set(a))
for i in range(n):
if 'd' in char_list:
pass