New imports... switched order so that PyCharm will pick up with Python 3 import first
This commit is contained in:
parent
aeafdfeb19
commit
4548b1dd9b
84 changed files with 1071 additions and 265 deletions
|
@ -16,7 +16,7 @@ sg.SetOptions (background_color = 'LightBlue',
|
|||
#adjust widths
|
||||
layout = [
|
||||
[sg.Text('Celcius', size =(12,1)), sg.InputText(size = (8,1))],
|
||||
[sg.Submit()],
|
||||
[sg.Submit()]
|
||||
]
|
||||
|
||||
window = sg.Window('Converter').Layout(layout)
|
||||
|
|
|
@ -4,6 +4,8 @@
|
|||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
#use of Column to help with layout - vertical sliders take up space
|
||||
|
||||
column1 = [
|
||||
[sg.Text('Pick operation', size = (15,1), font = ('Calibri', 12, 'bold'))],
|
||||
[sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (10,6))],
|
||||
|
@ -20,8 +22,12 @@ layout = [
|
|||
sg.Slider(range = (-9, 9),orientation = 'v', size = (5, 20), default_value = 0),
|
||||
sg.Text(' '), sg.Column(column1), sg.Column(column2)]]
|
||||
|
||||
window = sg.Window('Enter & Display Data', grab_anywhere=False).Layout(layout)
|
||||
#added grab_anywhere to when moving slider, who window doesn't move.
|
||||
|
||||
window = sg.Window('Enter & Display Data',grab_anywhere = False).Layout(layout)
|
||||
|
||||
#Get selection from combo: value[2]
|
||||
#Slider values: value[0] and value[1]
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
|
@ -31,11 +37,10 @@ while True:
|
|||
result = value[0] * value[1]
|
||||
elif value[2] == 'Subtract':
|
||||
result = value[0] - value[1]
|
||||
elif value[2] == 'Divide':
|
||||
elif value[2] == 'Divide': #check for zero
|
||||
if value[1] ==0:
|
||||
sg.Popup('Second value can\'t be zero')
|
||||
if value[0] == 0:
|
||||
result = 'NA'
|
||||
result = 'NA'
|
||||
else:
|
||||
result = value[0] / value[1]
|
||||
window.FindElement('result').Update(result)
|
||||
|
|
|
@ -7,19 +7,20 @@ sg.SetOptions(font= ('Calibri', 12, 'bold'))
|
|||
|
||||
layout = [
|
||||
[sg.Text('Spinner and Combo box demo', font = ('Calibri', 14, 'bold'))],
|
||||
[sg.Spin([sz for sz in range (-9,10)], initial_value = 0),
|
||||
sg.Spin([sz for sz in range (-9,10)], initial_value = 0),
|
||||
sg.Text('Pick operation', size = (13,1)),
|
||||
[sg.Spin([sz for sz in range (-9,10)], size = (2,1),initial_value = 0),
|
||||
sg.Spin([sz for sz in range (-9,10)], size = (2,1), initial_value = 0),
|
||||
sg.Text('Pick operation ->', size = (15,1)),
|
||||
sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (8,6))],
|
||||
[sg.Text('Result: ')],[sg.InputText(size = (6,1), key = 'result'),
|
||||
[sg.Text('Result: ')],[sg.InputText(size = (5,1), key = 'result'),
|
||||
sg.ReadButton('Calculate', button_color = ('White', 'Red'))]]
|
||||
|
||||
window = sg.Window('Enter & Display Data', grab_anywhere=False).Layout(layout)
|
||||
window = sg.Window('Enter & Display Data', grab_anywhere= False).Layout(layout)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
#convert returned values to integers
|
||||
val = [int(value[0]), int(value[1])]
|
||||
if value[2] == 'Add':
|
||||
result = val[0] + val[1]
|
||||
|
|
39
ProgrammingClassExamples/5a PSG (listboxes add remove).py
Normal file
39
ProgrammingClassExamples/5a PSG (listboxes add remove).py
Normal file
|
@ -0,0 +1,39 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.ChangeLookAndFeel('BlueMono')
|
||||
|
||||
#use column feature with height listbox takes up
|
||||
column1 = [
|
||||
[sg.Text('Add or Delete Items\nfrom a Listbox', font = ('Arial', 12, 'bold'))],
|
||||
[sg.InputText( size = (15,1), key = 'add'), sg.ReadButton('Add')],
|
||||
[sg.ReadButton('Delete selected entry')]]
|
||||
|
||||
List = ['Austalia', 'Canada', 'Greece'] #initial listbox entries
|
||||
|
||||
#add initial List to listbox
|
||||
layout = [
|
||||
[sg.Listbox(values=[l for l in List], size = (30,8), key ='listbox'),
|
||||
sg.Column(column1)]]
|
||||
|
||||
window = sg.Window('Listbox').Layout(layout)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
#value[listbox] returns a list
|
||||
if button == 'Delete selected entry': #using value[listbox][0] give the string
|
||||
if value['listbox'] == []: #ensure something is selected
|
||||
sg.Popup('Error','You must select a Country')
|
||||
else:
|
||||
List.remove(value['listbox'][0]) #find and remove this
|
||||
if button == 'Add':
|
||||
List.append(value['add']) #add string in add box to list
|
||||
List.sort() #sort
|
||||
#update listbox
|
||||
window.FindElement('listbox').Update(List)
|
||||
else:
|
||||
break
|
78
ProgrammingClassExamples/6a PSG search.py
Normal file
78
ProgrammingClassExamples/6a PSG search.py
Normal file
|
@ -0,0 +1,78 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List, display):
|
||||
names = ''
|
||||
for l in List: #add list elements with new line
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display1').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display1').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display2').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'Linear Search': #Find and display
|
||||
linearSearch()
|
||||
if button == 'Binary Search': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
82
ProgrammingClassExamples/6b PSG search (disabled buttons).py
Normal file
82
ProgrammingClassExamples/6b PSG search (disabled buttons).py
Normal file
|
@ -0,0 +1,82 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1),key = 'ls'), sg.ReadButton('Binary Search', size = (14,1),key='bs')],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
window.Finalize() #finalize allows the disabling
|
||||
window.FindElement('ls').Update(disabled=True) #of the two buttons
|
||||
window.FindElement('bs').Update(disabled=True)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List, display):
|
||||
names = ''
|
||||
for l in List: #add list elements with new line
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
window.FindElement('ls').Update(disabled=False) #enable buttons now
|
||||
window.FindElement('bs').Update(disabled=False) #now data loaded
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display1').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display1').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display2').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'ls': #Find and display
|
||||
linearSearch()
|
||||
if button == 'bs': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
79
ProgrammingClassExamples/6c PSG search text preloaded.py
Normal file
79
ProgrammingClassExamples/6c PSG search text preloaded.py
Normal file
|
@ -0,0 +1,79 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
names = ''
|
||||
for l in Names:
|
||||
names = names + l + '\n'
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
sortnames = ''
|
||||
for l in SortedNames:
|
||||
sortnames = sortnames + l +'\n'
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold'))],
|
||||
[sg.Text(names,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text(sortnames,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', bind_return_key=True, size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
sg.Popup('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
sg.Popup('Linear search\n' +(value['linear'] + ' was not found'))
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
sg.Popup('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
sg.Popup('Binary search\n' +(value['binary'] + ' was not found'))
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'Linear Search': #Find and display
|
||||
linearSearch()
|
||||
if button == 'Binary Search': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
130
ProgrammingClassExamples/6d PSG sort and search.py
Normal file
130
ProgrammingClassExamples/6d PSG sort and search.py
Normal file
|
@ -0,0 +1,130 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to sue in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List):
|
||||
global ListDisplayed #store list in Multiline text globally
|
||||
ListDisplayed = List
|
||||
display = ''
|
||||
for l in List: #add list elements with new line
|
||||
display = display + l + '\n'
|
||||
window.FindElement('display').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(Names):
|
||||
L = Names[:]
|
||||
L.sort() #inbuilt sort
|
||||
displayList(L)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def selSort(Names):
|
||||
L = Names[:]
|
||||
for i in range(len(L)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(L)):
|
||||
if L[j] < L[smallest]: #find smallest value
|
||||
smallest = j #swap it to front
|
||||
L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion
|
||||
displayList(L)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsortHolder(Names):
|
||||
L = Names[:] #pass List, first and last
|
||||
quick_sort(L, 0, len(L) -1) #Start process
|
||||
displayList(L)
|
||||
|
||||
def quick_sort(L, first, last): #Quicksort is a partition sort
|
||||
if first >= last:
|
||||
return L
|
||||
pivot = L[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while L[high] > pivot:
|
||||
high = high -1
|
||||
while L[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
L[high], L[low] = L[low], L[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(L, first, low -1) #continue splitting - sort small lsist
|
||||
quick_sort(L, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = ListDisplayed[:] #get List currently in multiline display
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
displayList(Names)
|
||||
if button == 'Default sort':
|
||||
default(Names)
|
||||
if button == 'Sort: selection':
|
||||
selSort(Names)
|
||||
if button == 'Sort: quick':
|
||||
qsortHolder(Names)
|
||||
if button == 'Linear Search':
|
||||
linearSearch()
|
||||
if button == 'Binary Search':
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to sue in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List):
|
||||
global ListDisplayed #store list in Multiline text globally
|
||||
ListDisplayed = List
|
||||
display = ''
|
||||
for l in List: #add list elements with new line
|
||||
display = display + l + '\n'
|
||||
window.FindElement('display').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(Names):
|
||||
L = Names[:]
|
||||
L.sort() #inbuilt sort
|
||||
displayList(L)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def selSort(Names):
|
||||
L = Names[:]
|
||||
for i in range(len(L)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(L)):
|
||||
if L[j] < L[smallest]: #find smallest value
|
||||
smallest = j #swap it to front
|
||||
L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion
|
||||
displayList(L)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsortHolder(Names):
|
||||
L = Names[:] #pass List, first and last
|
||||
quick_sort(L, 0, len(L) -1) #Start process
|
||||
displayList(L)
|
||||
|
||||
def quick_sort(L, first, last): #Quicksort is a partition sort
|
||||
if first >= last:
|
||||
return L
|
||||
pivot = L[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while L[high] > pivot:
|
||||
high = high -1
|
||||
while L[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
L[high], L[low] = L[low], L[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(L, first, low -1) #continue splitting - sort small lsist
|
||||
quick_sort(L, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = ListDisplayed[:] #get List currently in multiline display
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
displayList(Names)
|
||||
if button == 'Default sort':
|
||||
default(Names)
|
||||
if button == 'Sort: selection':
|
||||
selSort(Names)
|
||||
if button == 'Sort: quick':
|
||||
qsortHolder(Names)
|
||||
if button == 'Linear Search':
|
||||
linearSearch()
|
||||
if button == 'Binary Search':
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import os #to work with windows OS
|
||||
|
||||
sg.ChangeLookAndFeel('GreenTan')
|
||||
sg.SetOptions(font = ('Calibri', 12, 'bold'))
|
||||
|
||||
layout = [
|
||||
[sg.Text('Enter a Name and four Marks')],
|
||||
[sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = 'name')],
|
||||
[sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = 'm1')],
|
||||
[sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = 'm2')],
|
||||
[sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = 'm3')],
|
||||
[sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = 'm4')],
|
||||
[sg.ReadButton('Save', size = (8,1),key = 'save'), sg.Text('Press to Save to file')],
|
||||
[sg.ReadButton('Display',size = (8,1), key = 'display'), sg.Text('To retrieve and Display')],
|
||||
[sg.Multiline(size = (28,4), key = 'multiline')]]
|
||||
|
||||
window = sg.Window('Simple Average Finder').Layout(layout)
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read() #value is a dictionary holding name and marks (4)
|
||||
if button is not None:
|
||||
#initialise variables
|
||||
total = 0.0
|
||||
index = ''
|
||||
Name = value['name'] #get name
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__)) #get pathname to current file
|
||||
pathname = dirname + '\\results.txt' #add desired file name for saving to path
|
||||
|
||||
#needs validation and try/catch error checking, will crash if blank or text entry for marks
|
||||
|
||||
if button == 'save':
|
||||
for i in range (1,5):
|
||||
index = 'm' + str(i) #create dictionary index m1 ... m4
|
||||
total += float(value[index])
|
||||
average = total/4
|
||||
f = open(pathname, 'w') #open file and save
|
||||
print (Name, file = f)
|
||||
print (total, file = f)
|
||||
print (average, file = f)
|
||||
f.close()
|
||||
|
||||
#some error checking for missing file needed here
|
||||
|
||||
if button == 'display':
|
||||
#This loads the file line by line into a list called data.
|
||||
#the strip() removes whitespaces from beginning and end of each line.
|
||||
data = [line.strip() for line in open(pathname)]
|
||||
#create single string to display in multiline object.
|
||||
string = 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2])
|
||||
window.FindElement('multiline').Update(string)
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
#Matplotlib, pyplt and csv
|
||||
#Tony Crewe
|
||||
#Sep 2017 - updated Sep 2018
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import csv
|
||||
from matplotlib.ticker import MaxNLocator
|
||||
|
||||
|
||||
x=[]
|
||||
y=[]
|
||||
|
||||
with open('weight 20182.csv', 'r', encoding = 'utf-8-sig') as csvfile:
|
||||
plots = csv.reader(csvfile)
|
||||
for data in plots:
|
||||
var1 = (data[0]) #get heading for x and y axes
|
||||
var2 = (data[1])
|
||||
break
|
||||
for data in plots: #get values - add to x list and y list
|
||||
x.append(data[0])
|
||||
y.append(float(data[1]))
|
||||
|
||||
|
||||
ax = plt.subplot(1,1,1)
|
||||
ax.set_ylim([82, 96])
|
||||
ax.xaxis.set_major_locator(MaxNLocator(10))
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
plt.plot(x,y, label = 'data loaded\nfrom csv file')
|
||||
plt.axhline(y = 85.5, color = 'orange', linestyle = '--', label = 'target')
|
||||
plt.xlabel(var1)
|
||||
plt.ylabel(var2)
|
||||
plt.title('weight loss from\n first quarter 2018')
|
||||
|
||||
|
||||
plt.legend()
|
||||
plt.show()
|
|
@ -0,0 +1,41 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
#Based of Example program from MikeTheWatchGuy
|
||||
#https://gitlab.com/lotspaih/PySimpleGUI
|
||||
|
||||
import sys
|
||||
import PySimpleGUI as sg
|
||||
import csv
|
||||
|
||||
def table_example():
|
||||
filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
|
||||
#populate table with file contents
|
||||
#Assume we know csv has haeding in row 1
|
||||
#assume we know 7 columns of data - relevenat to AFL w/o Pts or % shown
|
||||
#data will be data[0] = team, data [1] P, data [2] W, data[3] L
|
||||
#data [4] D, data[5] F, data[6] A
|
||||
#no error checking or validation used.
|
||||
|
||||
data = []
|
||||
header_list = []
|
||||
with open(filename, "r") as infile:
|
||||
reader = csv.reader(infile)
|
||||
for i in range (1): #get headings
|
||||
header = next(reader)
|
||||
data = list(reader) # read everything else into a list of rows
|
||||
|
||||
|
||||
col_layout = [[sg.Table(values=data, headings=header, max_col_width=25,
|
||||
auto_size_columns=True, justification='right', size=(None, len(data)))]]
|
||||
|
||||
canvas_size = (13*10*len(header), 600) # estimate canvas size - 13 pixels per char * 10 char per column * num columns
|
||||
layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)],]
|
||||
|
||||
window = sg.Window('Table', grab_anywhere=False).Layout(layout)
|
||||
b, v = window.Read()
|
||||
|
||||
sys.exit(69)
|
||||
|
||||
table_example()
|
|
@ -0,0 +1,22 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Sep 2017 - updated Sep 2018
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
27
ProgrammingClassExamples/9b Plot (axes moved).py
Normal file
27
ProgrammingClassExamples/9b Plot (axes moved).py
Normal file
|
@ -0,0 +1,27 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Sep 2017 - updated Sep 2018import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
#centre bottom and keft axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
28
ProgrammingClassExamples/9c Plot (axes pi format).py
Normal file
28
ProgrammingClassExamples/9c Plot (axes pi format).py
Normal file
|
@ -0,0 +1,28 @@
|
|||
#Plt using matplylib, plotly and numpy
|
||||
#Tony Crewe
|
||||
#Sep 2017 updated Sep 2018
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import matplotlib.ticker as ticker
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x/np.pi,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
#Format axes - nicer eh!
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue