Skip to content

Commiting finished code exercises. #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions palindrome_product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Michael John
# Usage: python palindrome_product.py

"""A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 99.Find the largest
palindrome made from the product of two 3-digit numbers."""



if __name__ == '__main__':
'''I chose to start from 999 and count down as that just made the most sense
in my head. If you wanted just the palindrome, the list would not be
necessary. I just used one here because I wanted to print the palindrome
along with the two digits.'''

pal_list = [] # Will hold our list of palindromes
pmin = 100 # Minimum 3 digit number
pmax = 999 # Maximum 3 digit number

# start at the max and count down
for m in range(pmax,pmin,-1):
# start at 'm', to avoid duplicate checks of the same combination
for n in range(m,pmin,-1):
# Check if Palindrome
if str(m*n) == str(m*n)[::-1]:
# For convenience, save as a tuple to the list
pal_list.append((m*n,m,n))

# Find the largest palindrome in our list of tuples
m = max(pal_list, key=lambda x:x[0])
print("Largest Palindrome: {0} {1}*{2}".format(m[0],m[1],m[2]))

3 changes: 0 additions & 3 deletions palinodrome_product.py

This file was deleted.

85 changes: 85 additions & 0 deletions prime.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,87 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Michael John
# Usage: python prime.py [options]



"""Write a program to find the 10 001st prime number using the sieve of
aristothanes."""

'''The algorithm design does the following:
1) Create a list of consecutive integers from 2 to 10 million.
2) Set p=2 as the first prime number
3) Starting from p, enumerate its multiples, and mark them in the list
4) Find the first number greater than p not marked. This is the next
prime number. Repeat starting back at step 3.
'''


from optparse import OptionParser, OptionGroup
import sys

SEARCH_MAX = 1000000 #just a randomly chosen default
NPRIME_NUMBER = 10001 #default prime number to return


def define_options(parser):
'''Defind options to set for this script'''
# Max search
parser.add_option("-m", "--max", dest="max", type="int",
default=SEARCH_MAX, action="store",
help="Max integer to search up to for Primes [default: %default]")
# Nth Prime
parser.add_option("-p", "--prime", dest="nprime", type="int",
default=NPRIME_NUMBER, action="store",
help="Nth Prime number to find [default: %default]")
# Verbose flag
parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", help="More output")

# Example section
group_ex = OptionGroup(parser, "Examples","")
group_ex1 = OptionGroup(parser, "To find the 10,001st Prime number",
"prime.py -p 10001")
parser.add_option_group(group_ex)
parser.add_option_group(group_ex1)



if __name__ == '__main__':
parser = OptionParser()
define_options(parser)
(options, args) = parser.parse_args()

if options.verbose:
print("Max Search limit: {0}".format(options.max))
print("Looking for the {0} Prime".format(options.nprime))

# Define variables before algorithm
PRIME = 1 # Constant: ID for a prime
NOT_PRIME = 0 # Constant: ID for a non prime
prime_list = [] # list of prime numbers
num_list = [] # list of consecutive integers

# Create list of consecutive integers
for x in range(2, options.max):
# Initially all index are set as primes
num_list.append([x, PRIME])

# Start of algorithm, find the Primes
for index in num_list:
if index[1] == NOT_PRIME:
continue
prime_list.append(index[0])
p = index[0]
mult = 2 #multiple, start at 2, then 3,4,5,... till out-of-bounds
while p*mult-2 < len(num_list):
num_list[p*mult-2][1] = NOT_PRIME
mult = mult + 1

# Finished, see if we were able to find what the user wanted
if options.nprime-1 > len(prime_list):
print("Could not find the {0} prime number.".format(options.nprime))
print("Try increasing the search limit. (Option: '-max=')")
else:
print("The {0} Prime Number: {1}".format(options.nprime,
prime_list[options.nprime-1]))
47 changes: 45 additions & 2 deletions series_product.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,46 @@
"""Complete this program to find the greatest produdct of five consecutive
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Michael John
# Usage: python series_product.py

"""Complete this program to find the greatest product of five consecutive
digits in the list"""
in_file = open('array.txt')


def consecutive_product(digits):
'''Calculates the product of the consecutive digits
Param: digits -list or tuple
'''
return reduce(lambda x,y: x*y, digits)


if __name__ == '__main__':
in_file = open('array.txt')

intlist = [] # our list of integers

# Read each line in the file and store it as a list of integers
for line in in_file.readlines():
l = list(line.rstrip()) # convert string to list
intlist.extend([int(x) for x in l]) # convert chars to ints and store

# Finished with the file
in_file.close()

# start at 0 and send to function that produces product of 5 digits
# if higher than max, save five digits
start = 0
end = len(intlist) - 5 #end is the last sequence of 5 digits
pmax = 0 #max product found
pseq = None #sequence that produces max product

while start != end:
prod = consecutive_product(intlist[start:start+5])
if prod > pmax:
pseq = intlist[start:start+5]
pmax = prod
start = start + 1 #slide window forward by one

# Finished
print("Max product: {0} {1}".format(pmax, pseq))