Python For Quantum Mechanics:#

Week 2: Tutorial#

Exercise 1: Convert Decimal To Ten Bit Binary String#

In this exercise we want to convert a decimal number to a binary string with exactly ten character bits. For example,

\[ 1_{decimal} = 1_{binary} = 0000000001_{binary}\]

or

\[ 10_{decimal} = 1010_{binary} = 0000001010_{binary}\]

Create code that converts a decimal to binary, bin(decimal), removes the proceding 0b, and adds in the required amount of 0s to make it a ten character string. If the binary has more than ten bits, slice the string so it contains only the last 10 bits. Prompt the user with the input() function for a decimal number.

Hint: bin(decimal) returns a string. Can use string manipulation, and a conditional to differentiate between strings with less than or more than ten bits.

If we wanted to make the number of bits an arbitrary amount, rather than just 10, rewrite the code in such a way to accomplish this.

Given some arbitrary fixed number of bits, what is the largest decimal number you can represent with those bits?

Exercise 2: For Loops, Sequence Sum#

Prompt the user to input a positive integer number \(n\). Calculate the sum $\(1+2+3+...+n \)$ using a for loop. Print the answer

Alternatively, we could use the formula $\(1+2+3+...+n = \frac{n(n+1)}{2}\)$. Check to see our for loop returns the value obtained from the formula. Print a Boolean answer.

Exercise 3: While Loops, Reverse A Given Number#

Prompt the user to input a positive integer number and reverse the number. For example: $\( 257864 \rightarrow 468752 \)$

(Hint: 257864 % 10 = 4)

Exercise 4: List Comprehensions#

Create a list of all the even numbers from 0 \(\rightarrow\) 1000 that are not divisible by 4.

A year is a leap year when it is divisible by 4, not divisible by 100 unless it is divisible by 400. Create a list containing leap years from year \(1890 \rightarrow 2050\)

Make a list of all the primes less than 100.

Exercise 5: DNA#

Read in the file named ‘DNA.txt’ and count the number of times the base C occurs. A DNA sequence contains bases A,C,G and T.

Exercise 6: Collatz Conjecture#

If we take any positive integer and if it’s even divide it by two and if it’s odd multiply it by three and add one. Do this successivly again and again. Verify that we always get back to 1.

Exercise 7: Fizz Buzz#

Print out numbers in order. Every time there is a multiple of 3 print ‘Fizz’ instead. Every time there is a multiple of 5 print ‘Buzz’. Every time there is both print ‘Fizz Buzz’.