algorithm

A Game of Chance

"""Simulating the dice game Craps""" ## 'Simulating the dice game Craps' import random def roll_dice(): """Roll two dice and return their face values as a tuple.""" die1 = random.randrange(1,7) die2 = random.randrange(1,7) return (die1, die2) def display_dice(dice): """Display one roll of the two dice.""" die1, die2 = dice print(f'Player rolled {die1} + {die2} = {sum(dice)}') die_values = roll_dice() #first roll display_dice(die_values) # determine game status and point, based on first roll.

Continue reading

Functions

1. Defining functions def square(number): print("The square of", number, "is", number ** 2) square(7) ## The square of 7 is 49 2. Functions with multiple parameters def maximum(value1, value2, value3): max_value = value1 if value2 > max_value: max_value = value2 if value3 > max_value: max_value = value3 return max_value maximum(12, 27, 36) ## 36 maximum('yellow', 'red', 'orange') ## 'yellow' 3. Random-Number Generation import random random.seed(10) for roll in range(10): print(random.

Continue reading

Binary Search Algorithm

def binary_search(lista, item): low = 0 # low and high are part of the list thar you are searching for high = len(lista) - 1 while low <= high: #while you are not achieving one unique element middle = (low + high) // 2 # checking the central element guess = lista[middle] if guess == item: return middle if guess > item: # the guess are too high high = middle - 1 else: # the guess are too low low = middle + 1 return None my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 3)) ## 1 print(binary_search(my_list, -1)) ## None

Continue reading

Quicksort Algorithm

def quicksort(array): if len(array) < 2: return array else: pivo = array[0] # caso recursivo menores = [i for i in array [1:] if i <= pivo] # subarray de todos os elementos menores do que o pivo maiores = [i for i in array[1:] if i > pivo] # subarray de todos os elementos maiores do que o pivo return quicksort(menores) + [pivo] + quicksort(maiores) print(quicksort([10, 5, 2, 3])) ## [2, 3, 5, 10]

Continue reading