Open In App

Python | Same and Different value space

In Python, we have same pool for similar values, even if they share different variables. This has many advantages, that it saves a lot of memory arranging different spaces for similar values. This is provided for small integers. But there are ways in which we can have same and different pool values. Lets discuss certain cases of the same. 

Case #1 : Same pool ( Using + operator ) In this, when we create a String using “+” operator, we create a space that will point to similar space in memory. 






# Python3 code to demonstrate working of
# Same and Different value space
# Same value case
 
# initializing strings
test_str1 = "gfg"
 
# printing original string
print("The original string is : " + test_str1)
 
# Using + to construct second string
test_str2 = "g" + "fg"
 
# testing values
res = test_str1 is test_str2
 
# printing result
print("Are values pointing to same pool ? : " + str(res))

Output : 
The original string is : gfg
Are values pointing to same pool ? : True

Time Complexity: O(1)



Auxiliary Space: O(1)

  Case #2 : Different Pool ( Using join() + ord() ) This is way in which we need to initialize string pointing to different value space in memory. This can be achieved using join() for joining ASCII values extracted using ord(). 




# Python3 code to demonstrate working of
# Same and Different value space
# Different value case
 
# initializing strings
test_str1 = "abc"
 
# printing original string
print("The original string is : " + test_str1)
 
# Using join() + ord() to construct second string
test_str2 = ''.join((chr(idx) for idx in range(97, 100)))
 
# testing values
res = test_str1 is test_str2
 
# printing result
print("Are values pointing to same pool ? : " + str(res))

Output : 
The original string is : abc
Are values pointing to same pool ? : False

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Approach#3: using hash()

This function takes in two strings as input and returns True if the hash value of both the strings is the same, indicating that the strings are equal. It uses the built-in hash() function to calculate the hash value of the strings and compares them using the == operator. In this specific example, the function will return True as both test_str1 and test_str2 have the same content and, therefore, the same hash value.

Algorithm

1. Create two variables, one for each input string.
2. Use the hash() function to obtain the hash value for each string.
3. Compare the hash values.
4. Return the result.




def compare_strings(test_str1, test_str2):
    return hash(test_str1) == hash(test_str2)
 
test_str1 = 'gfg'
test_str2 = 'g' + 'fg'
print(compare_strings(test_str1, test_str2))

Output
True

Time Complexity: O(n), where n is the length of the input strings, because we need to compute the hash value for each string.
Auxiliary Space: O(1), because we only create two variables.


Article Tags :