Examples for Week 5

In [ ]:
# Question 1 page 507 (Gaddis)

# The program should let the user enter the name of a Galilean moon of Jupiter, then it should display
# the moon's mean radius, surface gravity, and orbital period.





In [5]:
# 
# The main function:
def main():
    # Initialize dictionaries.
    mean_radius = {'io':1821.6, 'europa':1560.8, 
                   'ganymede':2634.1, 'callisto':2410.3}

    surface_gravity = {'io':1.796, 'europa':1.314, 
                       'ganymede':1.428, 'callisto':1.235}


    orbital_period = {'io':1.769, 'europa':3.551, 
                      'ganymede':7.154, 'callisto':16.689}



    # Get input from user:
    moon = input('Enter name of Galilean moon of Jupiter: ')

    # Convert to lowercase for reliable matching in dictionaries:
    moon = moon.lower()

    # Show error message if name does not exist.
    # Otherwise, display details of specified moon.
    if moon not in mean_radius:
        print('\n\n'+moon.title(), 'is an invalid moon name.')
    else:
        print('\n\nDetails of', moon.title(), 'are:')
        print('-------------------------------')
        print('Mean Radius:', mean_radius[moon], 'km')
        print('Surface Gravity:', surface_gravity[moon], 'm/s²')
        print('Orbital Period:', orbital_period[moon], 'days')


# Call the main function.
main()
Enter name of Galilean moon of Jupiter: ganymede


Details of Ganymede are:
-------------------------------
Mean Radius: 2634.1 km
Surface Gravity: 1.428 m/s²
Orbital Period: 7.154 days
In [1]:
# Question 5 page 508 (Gaddis)





In [8]:
import random

# The main function:
def main():

    # Initialize an empty dictionary.
    number_dict = dict()

    # Repeat 100 times.
    for i in range(100):
        # Generate a random number between 1 and 10:
        random_number = random.randint(1, 10)

        # Establish or increment the number in the dictionary:
        if random_number not in number_dict:
            number_dict[random_number] = 1            
        else:
            number_dict[random_number] += 1

    # Display the results:
    print('Number\tFrequency')
    print('------  ---------')

    # The "sorted" function produces a sorted version of
    # the list of key-value pairs from the "items" method:
    for number, frequency in sorted(number_dict.items()):
        print(number, frequency, sep='\t')
         

# Call the main function.
main()
Number	Frequency
------  ---------
1	10
2	7
3	14
4	7
5	8
6	9
7	14
8	13
9	8
10	10
In [ ]:
# Question 1 from Week 5 (Mersenne primes)
In [10]:
import math

# Checks whether a given number ('number') is prime or not
# returns a Boolean variable: 
#         TRUE (if prime) ---- or ---- FALSE (if not prime)

def check_prime(number):
    for divisor in range(2, int(number**0.5) + 1):
        if number % divisor == 0:
            return False
    return True
#
#----------------------------------------------------------------
# Checks whether the numbers 2**i - 1 are prime
#                     for 1 <= i <= upper_bound:

def Mersenne_Primes(upper_bound):
    listM = []          # will store the Mersenne primes
    iter = 1
    while iter < upper_bound:
        iter += 1
        Mersenne = 2**iter -1
        if check_prime(Mersenne):
            listM.append(Mersenne)
    return listM
#
#-----------------------------------------------------------------
#
nval = 1000000                 # can change this value as we wish
# (2**i - 1 < nval --> take the max. val. of i)
n = math.log(nval+1,2)+1       # this is our 'upper_bound'          
primes = Mersenne_Primes(n)    # our list that stores the answer
for prime in primes:           # display the answer on the screen
    print(prime)
3
7
31
127
8191
131071
524287
In [14]:
# Another solution (using SETS)

import math

# this first function checks to see if a number is a prime
# it returns a boolean variable (either False or True):

def check_prime(number):
    for divisor in range(2, int(number**0.5) + 1):
        if number % divisor == 0:
            return False
    return True
#
#------------------------------------------------------------
#
def Primes(max):
    listP = []                   # store primes
    number = 1
    while number < max:
        number += 1
        if check_prime(number):
            listP.append(number)
    return listP                 # this list contains primes
#
#----------------------------------------------------------------
#
n = 1000000    
P = set(Primes(n))

# a list of integers 2**i - 1 <=n:
A = []
for i in range(2, int(math.log(n+1, 2))+1):
    A.append(2**i-1)
    
# The set of Mersenne primes as the intersection of A and P:
M = P.intersection(A)

# Output as a sorted list of M:
print(sorted(list(M)))    
[3, 7, 31, 127, 8191, 131071, 524287]
In [21]:
# Question 2 from Week 5

def Cubes(nmax):
    cubed = []
    for i in range(2,nmax+1):
        tmp =  i*i*i
        cubed.append(tmp)
    return cubed
#
#-----------------------------------------------------------------------
#
def Sum2(nmax):
    squared = []               # initialize list
    for i in range(1,nmax):
        for j in range(1,i+1):
            tmp = i**2 + j**2
            squared.append(tmp)
    return squared
#
#-------------------------------------------------------------------------
#
nmax = 1000              # you can change this to smaller values....
A = set(Cubes(nmax))
B = set(Sum2(nmax))

# take the intersection of A and B:
C = A.intersection(B)

answer = len(C)
print(answer)

# OPTIONAL: if you want to know what those numbers are....
L = []
for number in C:
    tmp = round(number**(1/3))
    L.append(tmp)

print(sorted(L))
40
[2, 5, 8, 10, 13, 17, 18, 20, 25, 26, 29, 32, 34, 37, 40, 41, 45, 50, 52, 53, 58, 61, 65, 68, 72, 73, 74, 80, 82, 85, 89, 90, 97, 98, 100, 101, 104, 106, 109, 113]