DEV Community

Saravanan Cn
Saravanan Cn

Posted on

Python Learning Journey:Sets,Luhn Algorithm,HashCode Algorithm

I explored three interesting concepts in python:

1.Python Sets and Set Operations
2.Luhn Algorithm - Number Validation
3.Hash Code Algorithm - Generating Numerical Hash Values.

1.Python Sets

A set is a collection of unique elements in Python.

  • They do not allow duplicate values.
  • They are unordered.
  • They are mutable.
  • They are created using curly braces{}.

Example:

s1 = {10,20,30,40,50,60}
s2 = {30,40,50,60}

print(s1)
print(s2)

Enter fullscreen mode Exit fullscreen mode

Set Operations:

A.Union:

It combines all unique elements from both sets.



 UNION = {10, 20, 30, 40, 50, 60}
_
Python code:_

print(s1.union(s2))
print(s1 | s2)

Enter fullscreen mode Exit fullscreen mode

B.Intersection:

Intersection only the common elements in both sets.

Diagram:

C.Difference:

they return elements present in the first set but not in the second set.

print(s1.difference(s2))
print(s1 - s2)

Output:

{10, 20}

Remember: s1 - s2 and s2 - s1 produce different results.
Enter fullscreen mode Exit fullscreen mode

D.Symmetric Difference:

Returns elements that are present in either set,but not in both.

print(s1.difference(s2))
print(s1 - s2)

Output:

{10, 20}
Enter fullscreen mode Exit fullscreen mode

_
Remember:_ s1 - s2 and s2 - s1 produce different results.

2.Luhn Alogrithim:

It _checks sum algorithim _used to check whether a number passes a mathematical validation.

It is commonly used as an initial check for payment card numbers.

Working process:

  • Read from digits from right to left.
  • starting from the second digit from right,doule every alternate digit.
  • if douled digit is greater than 9,subtract 9.
  • Add all the resulting digits.
  • check whether the total is divisible by 10.

Python Implentation :

def validate_card(card_number):

    if not card_number.isdigit():
        return False

    if not 13 <= len(card_number) <= 19:
        return False

    total = 0
    double_digit = False

    for digit in reversed(card_number):

        digit = int(digit)

        if double_digit:
            digit = digit * 2

            if digit > 9:
                digit = digit - 9

        total = total + digit

        double_digit = not double_digit

    return total % 10 == 0


card_number = input("Enter test number: ")

if validate_card(card_number):
    print("Number passes Luhn validation")
else:
    print("Invalid number")
Enter fullscreen mode Exit fullscreen mode

Method Purpose
_isdigit() _ Checks whether the input contains only digits.

_len() _ Finds the length of number.

_reversed() _ Reads the digits in reverse order.

_int() _ Converts a character into an integer.

_%10 _ Checks the remainder after division by 10.

Important:passing the Luhn check does not mean a payment card is genuine,active or usable.Practise with fictional test numbers only.

3.Hash Code Algorithm in Python

A hash code is numerical value generated from input data using a hash function.

Hashing is used in areas such as:

  • Hash tables.
  • Dictionaries.
  • Data retreival.
  • Data comparison.

Works of Hash Code Algorithim ?

1.Take a string as input.
2.Initialize the hash value to zero.
3.Read each character one by one.
4.Convert each character into its Unicode value using or d().
5.Update the hashvalue using a mathematical formuala.
6.Return the numerical value.

Python Implementaion:


def generate_hash(text):

    hash_value = 0

    for char in text:

        hash_value = (hash_value * 31 + ord(char)) % 1000000007

    return hash_value


text = input("Enter text: ")

result = generate_hash(text)

print("Hash Code:", result)

Enter fullscreen mode Exit fullscreen mode

Understanding the code

Step 1: Create a function

def generate_hash(text):

This function accepts a string as input.

Step 2: Initialize the hash value

hash_value = 0

We start with zero.

Step 3: Iterate through the string

for char in text:

This loop reads each character one by one.

Step 4: Calculate the hash value

hash_value = (hash_value * 31 + ord(char)) % 1000000007

hash_value * 31 multiplies the previous hash value by 31.

ord(char) converts the character into its Unicode number.

% 1000000007 keeps the result within a fixed numerical range.
**
Step 5: Return the result**

return hash_value

This returns the final numerical hash value.

What is ord() in Python?

The ord() function returns the Unicode code point of a character.

print(ord('A'))
print(ord('B'))
print(ord('a'))

Output:

65
66
97

What is Hash Collision ?
A hash collision happen when two diffrent inputs generate the same hash value.

A hash function cannot guarentee a unique value for every possible input when its output range is limited.

Learning python becomes more interesting when we apply programming concepts to practical examples.

These three topics helped me understand collections,algorithims,validations and hashing.

My python journey continues and looking forward to explore more algorithms and pratctical problems.

Top comments (0)