Python Coding: FizzBuzz challenge

FizzBuzz is a very common task, asked in Dev/DevOps interviews. You are given a range of numbers and need to write algorithm using the following rules: if the number is divisible by 3, print “Fizz”; if the number is divisible by 5, output “Buzz”; if the number is divisible by both 3 and 5, the result should be “FizzBuzz”.

The main goal of the task is to check how you understand loops, conditionals and simple math using one of programming or scripting languages. I solved the task using PowerShell years ago: check this gist.

As I started to learn Python, I decided to share FizzBuzz implementation in this language to show how simple and “elegant” the solution can be.

I used matplotlib and colorama to make a pie chart and add color text output respectively. Defined a function fizz_buzz with 2 arguments, and then used try/catch/finally statements to catch exceptions errors. Inside of the try, the for loop and if conditionals are described to meet all task’s rules. As a result, the function outputs numbers and categories based on rules, and makes a pie chart to show how many fizz, buzz, fizzbuzz found in percentage.

import matplotlib.pyplot as plt
import colorama
from colorama import Fore, Back, Style
colorama.init()

def fizz_buzz(x,y):
    """Python version of popular Fizz Buzz task"""
    fb = 0 ; b = 0; f = 0; rest = 0 # start values
    fb_type = ['fizzbuzz','fizz','buzz','rest'] # plot labels
    fb_colors = ['r','y','c','g'] # plot colors
    fb_explode = [0.2, 0.1, 0.1, 0.1] # plot fraction of the radius
    try:
        for n in range(x,y):
            if ((n % 3 == 0) and (n % 5 == 0)):
                fb += 1
                print(Fore.RED + f"Found FizzBuzz: {n}")
            elif n % 3 ==0:
                f += 1
                print(Fore.WHITE + f"Found Fizz: {n}")
            elif n % 5 ==0:
                b += 1
                print(Fore.GREEN + f"Found Buzz: {n}")
            else: 
                rest += 1
                print(Style.BRIGHT + f"The rest is {n}")
            print(Style.RESET_ALL)
        fb_array = [fb, f, b, rest]
        plt.pie(fb_array, colors = fb_colors, explode = fb_explode, shadow = True, radius = 1.1, autopct = '%1.1f%%') # form a pie
        plt.legend(fb_type,loc='upper right') # show legend
        plt.show() # show a pie
    except:
        print(Style.BRIGHT + Fore.RED + "You provided wrong x and y")
        print(Style.RESET_ALL)
    finally:
        print(Style.BRIGHT + Fore.GREEN + "Author: github.com/rlevchenko")
        print(Style.RESET_ALL)

Result

Available at Gist

Public preview of Azure Cloud Shell

At the recent Build conference, Microsoft officially announced public preview of Azure Cloud Shell browser-accessible, pre-configured shell experience for managing Azure resources without the overhead of installing, versioning, and maintaining a machine yourself.

Cloud Shell runs entirely on containers orchestrated by Kubernetes and shows us just another example of how container technology can revolutionize solutions built on Azure.

Machine for Cloud Shell is not persistent and temporary provided on a per-request basis (1 machine per 1 user, permissions are set as a regular Linux user). That machine’s hosting is free. You just need to pay for storage that it consumes (file share –> described later in this post).

Cloud Shell comes with the support of well known tools and languages:

Category Name
Azure Tools Azure CLI 2.0 and 1.0
Linux shell interpreter Bash,sh
Text editors vim,nano,emacs
Containers Docker,Kubectl, DC/OS CLI
Language Version
.NET 1.01
Go 1.7
Node.js 6.9.4
Python 2.7 and 3.5
More: use this link

It supports Bash experience so far. Everyone’s favorite PowerShell is coming soon. You can try the new shell today by pressing the special icon at the top navigation bar of the Azure portal.

azure

The new storage account (LRS), resources group and file share will be created during one-time setup.

  • Resource group is named: cloud-shell-storage-
  • Storage Account: cs-uniqueGuid
  • File Share: cs—com-uniqueGuid

As Cloud Shell’s machine is temporary, file share makes possible to persist your bash $Home directory. This file share will mount as clouddrive under your $Home directory and it’s also used to store a 5 GB image created for you that automatically updates and persists your $Home directory as well (see the pic below, acc_<username>.img).

Note: you pay only for this file share. There are no any  additional compute costs.

SNAGHTML5a54f4

To download/upload files you can use portal as usual. For example, I created txt-file in my clouddrive and would like to download it to my local machine. So, I need to open the file share associated with cloud shell, locate the file “text.txt” and just hit “Download”.

To add some files from local machine to clouddrive, use the “Upload” button and then check result by running cd clouddrive and  ls in the cloud shell session

SNAGHTML7097ce

As you may noticed, Cloud Shell automatically authenticates on each session for instant access to your resources through the Azure CLI 2.0. You can even use the interactive mode for Azure CLI 2.0 to ease scripting and save a lot of time

azure shell

Each cloud shell session times out after 10 minutes without any activities

image

That’s great, but that is not the whole news

Cloud Shell is also embedded directly in docs.microsoft.com and it makes Azure CLI samples in documentation fully interactive. To evaluate this new functionality, go to Azure CLI 2.0 documentation, log in to Cloud Shell by clicking “Try it” and start learning in just a new way.

azure cloud shell and docs

Some more examples

Creating VM in the cloud shell

SNAGHTMLa23890

List of VMs in the resource group with customized output

SNAGHTMLb64914

%d bloggers like this: