alexsib

Since
16 Snippets
  • Binary search algorithm in Python

    # Returns index of target in arr if present, else -1
    def binary_search(arr, target):
    	low = 0
    	high = len(arr) - 1
    
    	while low <= high:
    		# Check base case
    		mid = (high + low) // 2
    
    		# If element is smaller than mid, then it can only
    		# be present in left subarray
    		if arr[mid] > target:
    			high = mid - 1
    		# Else the element can only be present in right subarray
    		elif arr[mid] < target:
    			low = mid + 1
    		# If element is present at the middle itself
    		else:
    			return mid
    
    	# Element is not present in the array
    	return -1
    
    # Test array
    arr = [ 2, 3, 4, 10, 40 ]
    target = 10
    
    result = binary_search(arr, target)
    
    if result != -1:
    	print("Element is present at index", str(result))
    else:
    	print("Element is not present in array")

    Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.

  • Implementation of the Quick Sort algorithm in Python

    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            left = [x for x in arr[1:] if x <= pivot]
            right = [x for x in arr[1:] if x > pivot]
            return quick_sort(left) + [pivot] + quick_sort(right)
    
    # Example usage:
    input_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    sorted_array = quick_sort(input_array)
    
    print("Original Array:", input_array)
    print("Sorted Array:", sorted_array)
    

    In this code, the quick_sort function is a recursive implementation of the Quick Sort algorithm. The pivot element is chosen as the first element of the array, and elements are partitioned into two sub-arrays (left and right) based on their relationship to the pivot. The function is then called recursively on the left and right sub-arrays until the entire array is sorted.

  • CSV file handling in Python

    import csv
    
    # Writing to a CSV file
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['name', 'age', 'city']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        writer.writerow({'name': 'John', 'age': 30, 'city': 'New York'})
        writer.writerow({'name': 'Alice', 'age': 25, 'city': 'London'})
    
    # Reading from a CSV file
    with open('data.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)

    Examples of code for writing to a csv file and reading from a csv file.