[PYTHON] I tried to sort a random FizzBuzz column with bubble sort.

Introduction

I wanted to learn algorithms such as bubble sort, so I started by sorting a random FizzBuzz column.

Create a random FizzBuzz column of interest.

I defined a function fzbz () that changes a numerical value to FizzBuzz as appropriate, and make_random_fizzbuzz () that changes it in a random order.

def fzbz(n):
  if (n%15) == 0:
    return "FizzBuzz"
  elif (n%5) == 0:
    return "Buzz"
  elif (n%3) == 0:
    return "Fizz"
  else:
    return n

import random
def make_random_fizzbuzz(start=1,finish=100):
  seq = range(start,finish+1)
  random_fizzbuzz = []
  while seq:
    random_fizzbuzz.append(fzbz(seq.pop(random.randint(0,len(seq)-1))))
  return random_fizzbuzz

More specifically, the solution to this article is to sort the list like the one below in a FizzBuzz style. (List created by the above function) 001.png

What is bubble sort in the first place (quoted from other sites)

Bubble sort is an alignment algorithm that compares the values of the base element and other elements in a list and exchanges them according to conditions.

The condition is the magnitude relationship of the value. Sort the list in descending order (descending order) or ascending order (ascending order).

This sort is called a bubble sort because it looks like elements with higher or lower values emerge when you perform this sort.

Algorithm analysis Steps to sort the list in ascending order.

Extract one element from the list-base element'A' Compare the values of element'A'and the next element'B' Swap the values of element'A'and element'B' if element'A'is greater than element'B' Compare / exchange with each element like element'A'and element'C', element'A' and element'D' until the end of the list The element with the highest value or the element with the smallest value in the list emerges at the base point. Proceed to the base element (element'B') and repeat steps 2-6 until the end of the list Alignment is completed by performing a brute force comparison as described above and executing an exchange that matches the conditions. http://www.codereading.com/algo_and_ds/algo/bubble_sort.html

I wrote a bubble sort in python that may be slightly different from the above, but probably the same in essence.

First, a function that generates a random sequence.

import random
def make_randoms(start=1,finish=100):
  seq = range(start,finish+1)
  randoms = []
  while seq:
    randoms.append(seq.pop(random.randint(0,len(seq)-1)))
  return randoms

A function that sorts the sequence created by the above function, whose significance is not well understood.

def bubble_sort(target):
  limit = len(target)-1
  while limit > 0:
    i = 0
    while i<limit:
      if target[i]>target[i+1]:
        target[i], target[i+1] = target[i+1], target[i]
      i += 1
    limit -= 1
  return target

Points to be corrected

The problem with random FizzBuzz columns seems to be the magnitude relationship.

    if target[i]>target[i+1]:

In other words, it seems that we should do something about this area where the size is judged.

Summary of correction

Therefore, the code that defines the counters f, b, fb for digitizing the character strings Fizz, Buzz, FizzBuzz, and

    (f,b,fb) = (3,5,15)

Functions that digitize Fizz, Buzz, FizzBuzz based on counters,

def zbzf(n,f,b,fb):
  n = str(n)
  if n == 'FizzBuzz':
    return fb
  elif n == 'Buzz':
    return b
  elif n == "Fizz":
    return f
  else:
    return int(n)

With functions that update the counter when Fizz, Buzz, FizzBuzz appears

def next_count(n,f,b,fb):
  if n == 'FizzBuzz':
    fb += 15
  elif n == 'Buzz':
    if (b%15) == 10:
      b += 10
    else:
      b += 5 
  elif n == "Fizz":
    if (f%15) == 12:
      f += 6
    else:
      f += 3
  return f, b, fb
  

I made, and tried to compare each element and update the counter using these.

    (f,b,fb) = (3,5,15)
    while i<limit:
      if zbzf(target[i],f,b,fb)>zbzf(target[i+1],f,b,fb):
        target[i], target[i+1] = target[i+1], target[i]
      f,b,fb = next_count(target[i],f,b,fb)

code

import random
def fzbz(n):
  if (n%15) == 0:
    return "FizzBuzz"
  elif (n%5) == 0:
    return "Buzz"
  elif (n%3) == 0:
    return "Fizz"
  else:
    return n
    
def zbzf(n,f,b,fb):
  n = str(n)
  if n == 'FizzBuzz':
    return fb
  elif n == 'Buzz':
    return b
  elif n == "Fizz":
    return f
  else:
    return int(n)

def make_random_fizzbuzz(start=1,finish=100):
  seq = range(start,finish+1)
  random_fizzbuzz = []
  while seq:
    random_fizzbuzz.append(fzbz(seq.pop(random.randint(0,len(seq)-1))))
  return random_fizzbuzz

def next_count(n,f,b,fb):
  if n == 'FizzBuzz':
    fb += 15
  elif n == 'Buzz':
    if (b%15) == 10:
      b += 10
    else:
      b += 5 
  elif n == "Fizz":
    if (f%15) == 12:
      f += 6
    else:
      f += 3
  return f, b, fb
  
def fizzbuzz_sort(target):
  limit = len(target)-1
  while limit > 0:
    i = 0
    (f,b,fb) = (3,5,15)
    while i<limit:
      if zbzf(target[i],f,b,fb)>zbzf(target[i+1],f,b,fb):
        target[i], target[i+1] = target[i+1], target[i]
      f,b,fb = next_count(target[i],f,b,fb)
      i += 1
    limit -= 1
  return target
print fizzbuzz_sort(make_random_fizzbuzz())

result

Random FizzBuzz has been sorted! !! 002.png

Recommended Posts

I tried to sort a random FizzBuzz column with bubble sort.
I tried to program bubble sort by language
I tried to generate a random character string
I tried to create a table only with Django
I tried to draw a route map with Python
I tried to automatically generate a password with Python3
I tried to implement a volume moving average with Quantx
Sort random FizzBuzz columns with quicksort
I tried to solve a combination optimization problem with Qiskit
I tried to get started with Hy ・ Define a class
I tried to implement Harry Potter sort hat with CNN
I tried to divide with a deep learning language model
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
A memorandum when I tried to get it automatically with selenium
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I tried to create a list of prime numbers with python
I tried to make a 2channel post notification application with Python
I tried to create Bulls and Cows with a shell program
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to create a linebot (implementation)
I tried to implement Autoencoder with TensorFlow
I tried to create a linebot (preparation)
I tried to visualize AutoEncoder with TensorFlow
I tried to get started with Hy
Learn quicksort to sort random FizzBuzz columns
I tried a functional language with Python
I tried to implement CVAE with PyTorch
I tried to make a Web API
I tried to solve TSP with QAOA
I tried to introduce a serverless chatbot linked with Rakuten API to Teams
Python: I tried to make a flat / flat_map just right with a generator
I tried to implement a blockchain that actually works with about 170 lines
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I tried to create a plug-in with HULFT IoT Edge Streaming [Development] (2/3)
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to draw a system configuration diagram with Diagrams on Docker
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to create a plug-in with HULFT IoT Edge Streaming [Execution] (3/3)
I tried to send a registration completion email from Gmail with django.
[Outlook] I tried to automatically create a daily report email with Python
I tried to visualize all decision trees of random forest with SVG
I tried to create a plug-in with HULFT IoT Edge Streaming [Setup] (1/3)
I tried to build a Mac Python development environment with pythonz + direnv
I tried to make a url shortening service serverless with AWS CDK
I tried to build a super-resolution method / ESPCN
I tried to detect Mario with pytorch + yolov3
I tried to implement reading Dataset with PyTorch
I tried to use lightGBM, xgboost with Boruta
I tried to learn logical operations with TF Learn
I tried to move GAN (mnist) with keras
I tried to save the data with discord
I tried to detect motion quickly with OpenCV
I tried to integrate with Keras in TFv1.1
I want to make a game with Python
I tried to get CloudWatch data with Python