Essential Python Programming Examples and Algorithms

Posted by Anonymous and classified in Computers

Written on in English with a size of 4.88 KB

Binary Search Algorithm

The Binary Search algorithm is an efficient way to find a target value within a sorted array.

arr = [10, 20, 30, 40, 50, 60, 70]
key = int(input("Enter number to search: "))

low = 0
high = len(arr) - 1

while low <= high:
    mid = (low + high) // 2

    if arr[mid] == key:
        print("Element found at index", mid)
        break
    elif arr[mid] < key:
        low = mid + 1
    else:
        high = mid - 1
else:
    print("Element not found")

Finding the Largest Element

This snippet demonstrates how to iterate through a list to identify the maximum value.

numbers = [10, 25, 8, 45, 30]

largest = numbers[0]

for i in numbers:
    if i > largest:
        largest = i

print("Largest element is:", largest)

Linear Search Implementation

A Linear Search checks every element in the sequence until a match is found.

numbers = [10, 20, 30, 40, 50]

key = int(input("Enter element to search: "))

found = False

for i in range(len(numbers)):
    if numbers[i] == key:
        print("Element found at position", i + 1)
        found = True
        break

if found == False:
    print("Element not found")

Prime Number Verification

Determine if a given integer is a prime number using a simple loop and the modulus operator.

num = int(input("Enter a number: "))

if num <= 1:
    print("Not Prime")
else:
    for i in range(2, num):
        if num % i == 0:
            print("Not Prime")
            break
    else:
        print("Prime")

Python Dictionary Operations

Learn how to add, update, and delete entries within a Python dictionary.

employees = {
    "Rahul": 30000,
    "Anu": 25000
}

employees["Amit"] = 40000
employees["Rahul"] = 35000
del employees["Anu"]

print(employees)

Calculate Sum and Average

Using a function to return both the total sum and the arithmetic mean of a list.

def sum_avg(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    return total, average

nums = [10, 20, 30, 40]

s, a = sum_avg(nums)

print("Sum =", s)
print("Average =", a)

Sum of a List

A basic example of calculating the total sum of all items in a list using a loop.

numbers = [10, 20, 30, 40, 50]

total = 0

for i in numbers:
    total += i

print("Sum =", total)

Even or Odd Checker

Utilizing the modulus operator to determine if a number is even or odd.

def check(num):
    if num % 2 == 0:
        print("Even")
    else:
        print("Odd")

n = int(input("Enter a number: "))
check(n)

Extract Unique Elements

The set() function is the most efficient way to remove duplicate values from a list.

numbers = [1, 2, 3, 2, 4, 5, 1]

unique = set(numbers)

print("Unique elements:", unique)

Square of a Number

A simple function to compute the square of an input integer.

def square(n):
    return n * n

num = int(input("Enter a number: "))
print("Square =", square(num))

Find Largest and Smallest Elements

Using built-in max() and min() functions for efficient list analysis.

numbers = list(map(int, input("Enter numbers: ").split()))

largest = max(numbers)
smallest = min(numbers)

print("Largest =", largest)
print("Smallest =", smallest)

Fibonacci Series Generation

This code prints the Fibonacci sequence up to the Nth term provided by the user.

n = int(input("Enter N: "))

a = 0
b = 1

for i in range(n):
    print(a, end=" ")
    c = a + b
    a = b
    b = c

String Palindrome Verification

Check if a string reads the same forwards and backwards using Python slicing.

def palindrome(s):
    if s == s[::-1]:
        return "Palindrome"
    else:
        return "Not Palindrome"

text = input("Enter a string: ")
print(palindrome(text))

Factorial Calculation

An iterative approach to finding the factorial of a positive integer.

def factorial(n):
    fact = 1

    for i in range(1, n + 1):
        fact *= i

    return fact

num = int(input("Enter a number: "))
print("Factorial =", factorial(num))

Element Frequency Count

Using a dictionary to map each element to its occurrence count within a list.

numbers = [1, 2, 2, 3, 1, 4, 2]

freq = {}

for i in numbers:
    if i in freq:
        freq[i] += 1
    else:
        freq[i] = 1

print(freq)

Related entries: