Skip to content
Snippets Groups Projects
Commit d67b3908 authored by Daniel Moix's avatar Daniel Moix
Browse files

Lecture 10

parent b74bf059
No related branches found
No related tags found
No related merge requests found
File added
#Program: SortMyWords.py
#Purpose: Open a text file with thousands of words,
# sort the word using different sorting algoriths
# and compare how long it for each algorithm
# to perform the sorting task
#Author: Adelaida Medlock
#Date: February 29, 2024
# import sorting algorithms from module
from SortingAlgorithms import *
# import time to keep track of start and end times
from time import time
# import shuffle to mix up words in file
from random import shuffle
# function to open and read file
# filename is a string with the name of the file we want to open
def getWords(filename) :
inFile = open(filename, 'r')
content = inFile.read()
inFile.close()
words = content.split()
return words
# the main script
if __name__ == "__main__":
# get list of words from data file
# Small File
wordList = getWords('news.txt')
print('List size:', len(wordList), 'words')
# Very, very, very large file
#wordList = getWords('english3.txt')
#print('List size:', len(wordList), 'words')
# shuffle words before testing quick sort
shuffle(wordList)
# set timer and sort with quick sort
print('Testing quick sort')
startTime = time()
quickSort(wordList, 0, len(wordList) - 1)
endTime = time()
duration = endTime - startTime
print('Time taken for quick sort:', duration, 'seconds')
# shuffle words before testing insertion sort
shuffle(wordList)
# set timer and sort with insertion sort
print('Testing insertion sort')
startTime = time()
insertionSort(wordList)
endTime = time()
duration = endTime - startTime
print('Time taken for insertion sort:', duration, 'seconds.')
\ No newline at end of file
#Program: SortingAlgorithms.py
#Purpose: Implement Insertion and Quick Sorts
#Author: Adelaida Medlock
#Date: February 25, 2024
'''
Purpose: Exchange the values of two elements in a list
Parameters: a list of values,
the indeces of the elements to be swapped
Return value: none
Sample call: swap (myList, 3 ,5)
'''
def swap(values, i, j):
temp = values[i]
values[i] = values[j]
values[j] = temp
'''
Purpose: Implement the insertion sort algorithm
This implementation sorts values in ascending order
Parameters: a list of items to be sorted
Return value: none. Values are sorted in place.
Sample Call: insertion_sort(myList)
'''
def insertionSort(values):
for i in range(1, len(values)):
j = i
# Insert values[i] into sorted part
# stopping once values[i] in correct position
while j > 0 and values[j] < values[j - 1]:
# Swap values[j] and values[j - 1]
swap(values, j, j - 1)
j = j - 1
'''
Purpose: partition a list into two parts:
one with the high values and
one with the low values
Parameters: a list of values
the index of the 1st element
the index of the last element
Return value: an integer representing the index to be used
as the partition point
Sample Call: splitPoint = partition(myList, 0, len(myList) - 1)
'''
def partition(values, fromIndex, toIndex):
# Pick middle element as pivot
midpoint = fromIndex + (toIndex - fromIndex) // 2
pivot = values[midpoint]
# Initialize variables
done = False
leftIndex = fromIndex
rightIndex = toIndex
while not done:
# Increment leftIndex while values[leftIndex] < pivot
while values[leftIndex] < pivot:
leftIndex = leftIndex + 1
# Decrement rightIndex while pivot < values[rightIndex]
while pivot < values[rightIndex]:
rightIndex = rightIndex - 1
# If there are zero or one items remaining,
# all numbers are partitioned. Return rightIndex
if leftIndex >= rightIndex:
done = True
else:
# Swap values[leftIndex] and values[rightIndex],
# update leftIndex and rightIndex
swap(values, leftIndex, rightIndex)
leftIndex = leftIndex + 1
rightIndex = rightIndex - 1
return rightIndex
'''
Purpose: Implement the quick sort algorithm, using recursion
This implementation sorts values in ascending order
Parameters: a list of values
the index of the 1st element
the index of the last element
Return value: none. Values are sorted in place.
Sample Call: quick_sort(myList, 0, len(myList) - 1))
'''
def quickSort(values, fromIndex, toIndex):
# Base case:
# If there are 1 or zero values to sort, there is nothing to sort
if fromIndex < toIndex:
# Partition the data within the list. Value splitPoint returned
# from partitioning is the location of last item in low partition
splitPoint = partition(values, fromIndex, toIndex)
# Recursively sort low partition (fromIndex to splitPoint) and
# high partition (splitPoint + 1 to toIndex)
quickSort(values, fromIndex, splitPoint)
quickSort(values, splitPoint + 1, toIndex)
Source diff could not be displayed: it is too large. Options to address this: view the blob.
import sorts
data = [8, 6, 7, 5, 3, 0, 9]
sorts.quicksort(data)
print(data)
\ No newline at end of file
print("Hello CS 171")
\ No newline at end of file
#Program: modulesExample.py
#Purpose: Demo the usage of random and datetime modules
#Author: Adelaida Medlock
#Date: February 29, 2024
# The random module supplies functions to generate pseudo-random values
import random
# randint(min, max) returns a random integer n such that min <= n <= max
def guessGame():
computer = random.randint(1, 10)
print ('I have a number between 1 and 10. Try to guess it.')
count = 1
player = int(input('Enter an number between 1 and 10: '))
while player != computer :
count = count + 1
if player < computer :
print('Too low. Try again.')
else :
print('Too high. Try again.')
player = int(input('Enter an number between 1 and 10: '))
print ('Good job! It took you', count, 'attempts to guess my number.')
# random.choice(list) returns a random element from list
def guessGame2() :
again = 'YES'
while (again == 'YES'):
computer = random.choice(['red', 'blue', 'yellow', 'orange', 'green', 'purple'])
print ("Guess what color I am thinking of?")
player = input("Enter your color guess: ")
player = player.lower()
if player == computer :
print ("How did you know?? You win!!")
else :
print ('Sorry, I picked', computer, '. I win.' )
again = input("Do you want to play again (YES/NO)? ")
again = again.upper()
# The datetime module supplies classes for manipulating dates and times
# date(year, month, day) creates a date object
# weekday() method of the date class returns the day of the week as an integer,
# where Monday is 0 and Sunday is 6
import datetime
def birthday():
print ("Let's find out what day of the week you were born")
bday = input('Please enter your birthday in the format mm/dd/yyyy: ')
month = int(bday[0:2])
day = int(bday[3:5])
year = int(bday[6:])
birthDate = datetime.date(year, month, day)
dayOfWeek = birthDate.weekday()
print ('You entered:', bday)
if dayOfWeek == 0 : #Monday
print ('You were born on a Monday.')
elif dayOfWeek == 1 : #Tuesday
print ('You were born on a Tuesday.')
elif dayOfWeek == 2 : #Wednesday
print ('You were born on a Wednesday.')
elif dayOfWeek == 3 : #Thursday
print ('You were born on a Thursday.')
elif dayOfWeek == 4 : #Friday
print ('You were born on a Friday.')
elif dayOfWeek == 5 : #Saturday
print ('You were born on a Saturday.')
else : #Sunday
print ('You were born on a Sunday.')
Odysseus moon lander still operational, in final hours before battery dies
Feb 27 (Reuters) - Odysseus, the first U.S. spacecraft to land on the moon since 1972, neared the end of its fifth day on the lunar surface still operational, but with its battery in its final hours before the vehicle is expected to go dark, according to flight controllers.
Texas-based Intuitive Machines (LUNR.O), opens new tab said in an online update on Tuesday that its control center in Houston remained in contact with the lander as it "efficiently sent payload science data and imagery in furtherance of the company's mission objectives."
The spacecraft reached the lunar surface last Thursday after an 11th-hour navigational glitch and white-knuckle descent that ended with Odysseus landing in a sideways or sharply tilted position that has impeded its communications and solar-charging capability.
Intuitive Machines said the next day that human error was to blame for the navigational issue. Flight readiness teams had neglected to manually unlock a safety switch before launch, preventing subsequent activation of the vehicle's laser-guided range finders and forcing flight engineers to hurriedly improvise an alternative during lunar orbit.
An Intuitive executive told Reuters on Saturday that the safety switch lapse stemmed from the company's decision to forgo a test-firing of the laser system during pre-launch checks in order to save time and money.
Whether or not failure of the range finders and last-minute substitution of a work-around ultimately caused Odysseus to land in an off-kilter manner remained an open question, according to Intuitive officials.
Nevertheless, the company said last Friday that two of the spacecraft's communication antennae were knocked out of commission, pointed the wrong way, and that its solar panels were likewise facing the wrong direction, limiting the vehicle's ability to recharge its batteries.
As a consequence, Intuitive said on Monday that it expected to lose contact with Odysseus on Tuesday morning, cutting short the mission that held a dozen science instruments for NASA and several commercial customers and had been intended to operate on the moon for seven to 10 days.
On Tuesday morning, Intuitive said controllers were still "working on final determination of battery life on the lander, which may continue up to an additional 10-20 hours."
The latest update from the company indicated the spacecraft might last for a total of six days before the sun sets over the landing site.
The company's shares closed 7% higher on Tuesday. The stock plummeted last week following news the spacecraft had landed askew.
It remained to be seen how much research data and imagery from payloads might go uncollected because of Odysseus' cockeyed landing and shortened lunar lifespan.
NASA paid Intuitive $118 million to build and fly Odysseus.
NASA chief Bill Nelson told Reuters on Tuesday he understood that agency scientists expected to retrieve some data from all six of their payloads. He also said Odysseus apparently landed beside a crater wall and was leaning at a 12-degree angle, though it was not clear whether that meant 12 degrees from the surface or 12 degrees from an upright position.
Intuitive executives said on Feb. 23 that engineers believed Odysseus had caught the foot of one of its landing legs on the lunar surface as it neared touchdown and tipped over before coming to rest horizontally, apparently propped up on a rock.
No photos from Odysseus on the lunar surface have been transmitted yet. But an image from an orbiting NASA spacecraft released on Monday showed the lander as a tiny speck near its intended destination in the moon's south pole region.
Despite its less-than-ideal touchdown, Odysseus became the first U.S. spacecraft to land on the moon since NASA's last crewed Apollo mission to the lunar surface in 1972.
It was also the first lunar landing ever by a commercially manufactured and operated space vehicle, and the first under NASA's Artemis program, which aims to return astronauts to Earth's natural satellite this decade.
import random
import time
def swap(list, i, j):
temp = list[i]
list[i] = list[j]
list[j] = temp
def insertionSort(A):
size = len(A)
i = 1 #i tracks first unsorted element
while i < size:
#Shift the value A[j] into position
j = i
while j > 0 and A[j-1] > A[j]:
swap(A, j-1, j)
j = j - 1
#End While
#Update position of first unsorted element
i = i + 1
#End While
#End Function
def partition(A, start, stop):
#Select Random index
randomIndex = random.randint(start, stop) # is this a bug?
#Swap with last position
swap(A, stop, randomIndex)
#//Partition Based on Last Index Pivot
pivot = A[stop]
i = start
#For(j := start; j < stop; j++)
for j in range(start, stop):
#//Swap a small and large value into place
if A[j] < pivot:
swap(A, i, j)
i = i + 1
#End If
#End For
#Put the pivot in place
swap(A, i, stop)
#Return index of pivot
return i
#End Function
def qsort(A, start, stop):
if start < stop:
p = partition(A, start, stop)
qsort(A, start, p-1)
qsort(A, p+1, stop)
#End If
#End Function
#//QuickSort
def quicksort(A):
size = len(A)
qsort(A, 0, size-1)
#End Function
if __name__ == "__main__":
print("This code is in the sorts.py file")
data = ['A', 'L', 'M', 'O', 'S', 'T']
data = []
for s in range(100, 1000000, 1000):
for i in range(0, s):
data.append(random.randint(0, 100))
# print(data)
random.shuffle(data)
now = time.time()
quicksort(data)
quickSortTime = time.time() - now
random.shuffle(data)
now = time.time()
insertionSort(data)
insertionSortTime = time.time() - now
# print(data)
print(f"QuickSort took {quickSortTime} seconds to sort {len(data)} values.")
print(f"Insertion Sort took {insertionSortTime} seconds to sort {len(data)} values.")
import time
now = time.time()
for x in range(1, 5000):
print(x)
later = time.time()
print(later - now)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment