Question

In: Computer Science

PYTHON PROGRAM! Exercise 1 - The Collatz Conjecture The Collatz conjecture was a mathematical proposal set...

PYTHON PROGRAM!

Exercise 1 - The Collatz Conjecture

The Collatz conjecture was a mathematical proposal set forward by Lothar Collatz in 1937, also known as the 3n + 1 conjecture.

The conjecture is summarized as follows:

  1. Start with any positive integer
  2. if that number is even, divide it by 2
  3. otherwise (i.e. if it's odd), multiply the number by 3 and add one (hence 3n + 1)
  4. repeat until (and if!) the resulting number is 1

For example, if you start with 12, the series would be 12, 6, 3, 10, 5, 16, 8, 4, 2, 1, and takes 9 iterations to get to 1.

The Collatz conjecture says that any starting number will eventually end up at 1. However, it is still unproven (see Mathematician Proves Huge Result on ‘Dangerous’ Problem (Links to an external site.) for some recent progress!).

Collatz visualization

Write a python program that will determine how many iterations it takes for each starting value from 1 to 100 (experiment with higher values if you want!). Write out the starting value and number of iterations to a comma delimited csv file (i.e. one set of comma separated values per line). Also plot the result (starting value vs. iterations) with a visible marker for the points (you can choose which ever style you like) and no line. Make sure to give your plot a title and label the axes appropriately.

Solutions

Expert Solution

Code: Logic to find number of iterations for starting value ranging from 1 to 100

  • I have stored starting values in list l_val and number of iterations in list l_itr
​
l_val = []
l_itr = []

for i in range(1,101):
    val = i
    itr = 0
    
    while val != 1:
        itr += 1
        
        if val%2 == 0:
            val = val/2
        else:
            val = 3*val + 1
            
    l_val.append(i)
    l_itr.append(itr)
    
print("For starting value =", l_val[11], ", No. of iterations =", l_itr[11])

Code to save CSV file:

  • Use zip() to write values in comma-seperated format

import csv

with open('sample.csv', 'w') as fp:
    writer = csv.writer(fp)
    writer.writerows(zip(l_val, l_itr))

Code to plot:

  • I have used matplotlib package to plot the graph
  • See the code to understand how to put a title and label the axes.

import matplotlib.pyplot as plt

plt.plot(l_val,l_itr,'-or')
plt.title('Collatz conjecture', fontsize=18)
plt.xlabel('Starting Value', fontsize=16)
plt.ylabel('Number of Iterations', fontsize=16)

Plot:

PS: Let me know if anyone face any issue or have some doubts.


Related Solutions

This is an exercise to design and write a Python program in good programming style for...
This is an exercise to design and write a Python program in good programming style for a simulation of stock price over a period of 100 days. In this exercise, you are asked to simulate the stock price starting at $100.00 for 100 days with a daily fluctuation based on the Normal Distribution with mean = 0.0 & sigma = 0.0125. The program will show the daily stock price, the 7-day minimum, the 7-day maximum, the 7-day average, and the...
Want a project proposal for a MSc student in Applied Mathematical Modelling under Mathematical Epidemiology
Want a project proposal for a MSc student in Applied Mathematical Modelling under Mathematical Epidemiology
IN PYTHON Write a program to do the following: Solve the a set of equations as...
IN PYTHON Write a program to do the following: Solve the a set of equations as mentioned in "Zybook 5.20 LAB: Brute force equation solver". Instead of the arithmetic operators use your own function defined in a module named calc. You must provide two files (calc.py, brute_force_solver.py) :- 1) calc.py:- Add function named 'add' instead of using operator '+' [10pts] Add function named 'difference' instead of using operator '-' [10pts] Add function named 'product' instead of using operator '*' [10pts]...
PYTHON Exercise 5. Guess the number 1. Develop a “Guess the number” game. Write a program...
PYTHON Exercise 5. Guess the number 1. Develop a “Guess the number” game. Write a program that comes up with a random number and the player has to guess it. The program output can be like this: I am thinking of a number between 1 and 20. Take a guess. 10 Your guess is too low. Take a guess. 15 Your guess is too low. Take a guess. 17 Your guess is too high. Take a guess. 16 Good job!...
Write a program IN PYTHON of the JUPYTER NOOTBOOK that keeps getting a set of numbers...
Write a program IN PYTHON of the JUPYTER NOOTBOOK that keeps getting a set of numbers from user until the user enters "done". Then shows the count, total, and average of the entered numbers. This should the answer when finished Enter a number: 55 Enter a number: 90 Enter a number: 12 Enter a number: done You entered 3 numbers, total is 157, average is 52.33333
Write a program in python that reads the elements of a set from the keyboard, stores...
Write a program in python that reads the elements of a set from the keyboard, stores them in a set, and then determines its powerset. Specifically, the program should repeatedly ask the user: Enter one more element ? [Y/N] If the user answers Y then an new element is read from the keyboard: Enter the new element in the set: This cycle continues until the user answers N to the first question. At that point the program shall compute the...
(Python) Write a program which accomplishes the following tasks: set a variable to the result of...
(Python) Write a program which accomplishes the following tasks: set a variable to the result of mathematical expression including +, -, * and / and of both Integer and Float values (or variables) set a variable to the result of a combination of string values (or variables) set a variable to the result of a combination of string, Integer and Float values (you may need to use the type casting functions) Using the following variables: a = 1.3 b =...
4.9 Branching Practice - Python Exercise #Write the code for the following # Exercise 1 #...
4.9 Branching Practice - Python Exercise #Write the code for the following # Exercise 1 # Ask user for a number using an input statement (no prompt) & assign the input to a variable # Convert the user entry to an integer and assign it to a variable # Condition: user entry is greater than zero # Action: display the following word on screen: positive # Exercise 2 # Ask user for a number using an input statement (no prompt)...
Python Exercise 2 A program is to display all odd numbers between 10 and 3000. The...
Python Exercise 2 A program is to display all odd numbers between 10 and 3000. The starting value and end value are to be assigned by the programmer, not requested from user.
Write a Python program which takes a set of positive numbers from the input and returns...
Write a Python program which takes a set of positive numbers from the input and returns the sum of the prime numbers in the given set. The sequence will be ended with a negative number.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT