This commit is contained in:
Marina Wahl 2014-07-09 03:30:46 -04:00
commit 895214fa59
6 changed files with 136 additions and 76 deletions

3
.gitignore vendored
View File

@ -34,3 +34,6 @@ nosetests.xml
.mr.developer.cfg .mr.developer.cfg
.project .project
.pydevproject .pydevproject
# PyCharm
.idea

View File

@ -1,10 +1,19 @@
#!/usr/bin/python3 #!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail # Mari von Steinkirch @ 2013
# mari.wahl9@gmail.com
# Bernardo Sulzbach (mafagafo) @ 2014
# 1449441@gmail.com
def bubble_sort(seq): def bubble_sort(seq):
''' implement bubble sort, a O(n^2) not efficient algorithm''' """
Implementation of bubble sort.
O() and thus highly ineffective.
:param seq: the sequence to be sorted.
:return: the sorted sequence.
"""
size = len(seq) -1 size = len(seq) -1
for num in range(size, 0, -1): for num in range(size, 0, -1):
for i in range(num): for i in range(num):
@ -15,7 +24,6 @@ def bubble_sort(seq):
return seq return seq
def test_bubble_sort(module_name='this module'): def test_bubble_sort(module_name='this module'):
seq = [4, 5, 2, 1, 6, 2, 7, 10, 13, 8] seq = [4, 5, 2, 1, 6, 2, 7, 10, 13, 8]
assert(bubble_sort(seq) == sorted(seq)) assert(bubble_sort(seq) == sorted(seq))

View File

@ -1,26 +1,63 @@
#!/usr/bin/python3 #!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail # Mari von Steinkirch @ 2013
# mari.wahl9@gmail.com
# Bernardo Sulzbach (mafagafo) @ 2014
# 1449441@gmail.com
# This file defines and compares four different functions that reverse a string.
# timeit is used for benchmarking.
from timeit import timeit
def reverse_str(s): def reverse_1(string):
''' in place ''' """
sr_ls = [] Slowest function. Use a list and str.join to reverse the string.
for i in range(len(s)-1, -1, -1): :param string: the string to be reversed.
sr_ls.append(s[i]) :return: a reversed string.
return ''.join(sr_ls) """
reversed_string = []
# Iterates from the last to the first character.
for i in range(len(string) - 1, -1, -1):
# Appends the character to the list.
reversed_string.append(string[i])
return ''.join(reversed_string)
def reverse_2(string):
"""
Same principle as reverse_1. One-liner cousin.
:param string: the string to be reversed.
:return: a reversed string.
"""
return ''.join([character for character in [string[i] for i in range(len(string) - 1, -1, -1)]])
def main(): def reverse_3(string):
s1 = 'abcdefg' """
s2 = 'buffy' Another one-liner. We make a list from the characters of the string and reverse it.
s3 = '' :param string: the string to be reversed.
print(reverse_str(s1)) :return: a reversed string.
print(reverse_str(s2)) """
print(reverse_str(s3)) return ''.join([character for character in string][::-1])
if __name__ == '__main__': # Overkill of elegance. A bit too passionate but it defines this lambda function well.
main() # Simply returns the string backwards. As fast as concise.
reverse_lambda = lambda s: s[::-1]
# We define some short strings to test our functions.
strings = ('buffy', 'foo', 'bar')
# We announce what we are doing.
print(', '.join(strings), ' should appear reversed if the function is working.\n')
print('{:<30}:'.format('Function name'), 'benchmarking result (lower is better):')
# Iterate over a tuple of functions.
for function in (reverse_1, reverse_2, reverse_3, reverse_lambda):
name = function.__name__ if function.__name__ != "<lambda>" else 'reverse_lambda'
# We print the function's name and its benchmark result.
print("{:<30}:".format(name), timeit(name + "('string')", setup='from __main__ import ' + name))
# We print the output so that we can check if the function is working as expected.
print(', '.join(map(function, strings)), '\n')
# We wait until the user wants to quit.
input('Press Return to quit.')

View File

@ -0,0 +1,45 @@
#!/usr/bin/python3
# Mari von Steinkirch @ 2013
# mari.wahl9@gmail.com
# Bernardo Sulzbach (mafagafo) @ 2014
# 1449441@gmail.com
def reverse_words(string):
"""
Reverse the order of the words in a sentence.
:param string: the string which words wil lbe reversed.
:return: the reversed string.
"""
l1 = string.split(' ')
l1.reverse()
return ' '.join(l1)
def reverse_words_brute(string):
"""
Reverse the order of the words in a sentence.
:param string: the string which words wil lbe reversed.
:return: the reversed string.
"""
word, sentence = [], []
for character in string:
if character != ' ':
word.append(character)
else:
# So we do not keep multiple whitespaces. An empty list evaluates to False.
if word:
sentence.append(''.join(word))
word = []
# So we do not keep multiple whitespaces. An empty list evaluates to False.
if word != '':
sentence.append(''.join(word))
sentence.reverse()
return ' '.join(sentence)
if __name__ == '__main__':
phrase = 'I love Google, Fedora & Python!'
print(reverse_words(phrase))
print(reverse_words_brute(phrase))

View File

@ -1,44 +0,0 @@
#!/usr/bin/python3
# mari von steinkirch @2013
# steinkirch at gmail
''' reverse words in a setence, keeping the words right
>>> str1 = 'I love Google and Python!'
>>> reverse_words(str1)
'Python! and Google love I'
>>> reverse_words('bla')
'bla'
>>> reverse_words('')
''
>>> reverse_words_brute(str1)
'Python! and Google love I'
>>> reverse_words_brute('bla')
'bla'
>>> reverse_words_brute('')
''
'''
def reverse_words(str1):
l1 = str1.split(' ')
l1.reverse()
return ' '.join(l1)
def reverse_words_brute(str1):
aux_lt = []
aux_str = ''
for i, c in enumerate(str1):
if c != ' ':
aux_str += c # WE COULD HAVE USED LT HERE, MORE EFFICIENT
elif c == ' ':
aux_lt.append(aux_str) # WE COULD HAVE USED STR BUT NOT EFFICIENT!
aux_str = ''
aux_lt.append(aux_str) # REMEMBER THAT THE LAST ONE DOEN'T HAVE SPACE!
aux_lt.reverse()
return ' '.join(aux_lt)
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -1,9 +1,20 @@
import sys import sys
print "System version:",sys.version print("System version:", sys.version, '\n')
import numpy as np
print "Numpy version:",np.version.version
import matplotlib
print "Matplotlib version:",matplotlib.__version__
import pandas as pd
print "Pandas version:",pd.__version__
try:
import numpy
print("\nNumpy version:", numpy.__version__)
except ImportError as e:
print(e)
try:
import matplotlib
print("\nMatplotlib version:", matplotlib.__version__)
except ImportError as e:
print(e)
try:
import pandas
print("\nPandas version:", pandas.__version__)
except ImportError as e:
print(e)