Learning Python: Introductory Excercises
These are rudimentary functions created in Python, working through the exercises in Computational Statistics in Python from Duke.
def power_function(num, power):
"""Funcion to caculate power, number ** power."""
return num**power
def fizz_buzz(begin, end):
"""Write a program that prints the numbers from 1 to 100.
But for multiples of three print “Fizz” instead of the number
and for the multiples of five print “Buzz”.
For numbers which are multiples of both three and five print “FizzBuzz"""
for i in range(begin, end):
if i%3 == 0 & i%5 == 0:
print("FizzBuzz")
elif i%5 == 0:
print("Buzz")
elif i%3 == 0:
print("Fizz")
else:
print(1)
def euclidean(UPoint, VPoint, ShortCalc):
"""Write a function that calculates and returns the euclidean distance
between two points u and v, where u and v are both 2-tuples (x,y).
For example, if u=(3,0) and v=(0,4) the function should return 5."""
try:
if ShortCalc == False:
hyp = UPoint[0]**2 + VPoint[1]**2
return hyp**.5
elif ShortCalc == True:
return math.hypot(UPoint[0], VPoint[1])
except:
return 0
def CountCharacters(someString):
"""Using a dictionary, write a program to calculate the number times
each character occurs in the given string s. Ignore differneces in
capitalization - i.e ‘a’ and ‘A’ should be treated as a single key.
For example, we should get a count of 7 for ‘a’."""
arr = list(someString.lower())
arrUnique = dict.fromkeys(set(arr), 0)
for item in arrUnique:
arrUnique[item] = arr.count(item)
return arrUnique
def CountCharactersAlt(someString):
"""Using a dictionary, write a program to calculate the number times
each character occurs in the given string s. Ignore differneces in
capitalization - i.e ‘a’ and ‘A’ should be treated as a single key.
For example, we should get a count of 7 for ‘a’."""
newDict = {}
for item in list(someString.lower()):
try:
val = newDict.get(item)
newDict[item] = val + 1
except:
newDict[item] = 1
return newDict
def CountCharactersAlt2(someString):
"""Using a dictionary, write a program to calculate the number times
each character occurs in the given string s. Ignore differneces in
capitalization - i.e ‘a’ and ‘A’ should be treated as a single key.
For example, we should get a count of 7 for ‘a’."""
newDict = {}
for item in someString.lower():
newDict[item] = newDict.get(item, 0) + 1
return newDict
#import string
def Sliding_Windows_Percentage(someString, findThis):
"""Write a program that finds the percentage of sliding windows
of length 5 for the sentence s that contain at least one ‘a’.
Ignore case, spaces and punctuation. For example, the first
sliding window is ‘write’ which contains 0 ‘a’s, and the second
is ‘ritea’ which contains 1 ‘a’."""
exclude = set(string.punctuation)
out = ''.join(ch for ch in someString if ch not in exclude)
found_Counter = 0
for i in range(0, len(out)-4):
if findThis in out[i: i+4]:
found_Counter += 1
return found_Counter / (len(out)-4)
Comments
Post a Comment