Write a program for Hailstone Sequence in Python

Carvia Tech | May 04, 2019 at 11:40 AM | 3 views | Python Coding Problem

Hailstone Sequence

A hailstone sequence is a calculation of numbers that increase and decrease but eventually settles into a repeating pattern of the numbers 4, 2, 1. The sequence is generated by starting with any positive whole number greater than zero and completing the following steps:

  • If the number is even, divide it by 2 to calculate a new number

  • If the number is odd, multiple it by 3 and add 1 to calculate a new number

  • Repeat the above process for calculated numbers until the sequence 4, 2, 1 is generated.

def generate_hale_seq(num):
    lnum = [num]
    while num != 1:
        if (num%2) == 0:
            num = num//2
            num = (num * 3) + 1
    return lnum

[10, 5, 16, 8, 4, 2, 1]

Top articles in this category:
  1. Top 100 interview questions on Data Science & Machine Learning
  2. Write a program to check if the given word is Isogram & Pair isogram in python
  3. Write a program to find if a number is Lychrel Number in Python
  4. Write a python program to find Largest Substring that occurs more than once
  5. Introduction to Python 3.6 & Jupyter Notebook
  6. Creating custom Keras callbacks in python
  7. Creating AWS Lambda using python 3.6

Find more on this topic:
Machine Learning image
Machine Learning

Data science, machine learning, python, R, big data, spark, the Jupyter notebook, and much more

Last updated 1 month ago

Recommended books for interview preparation:
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.5 by Munish Chandel

This website uses cookies to ensure you get the best experience on our website. more info