This doth be a machine-wrought text which may contain errors!
Quote
“Algorithm”, a terme by coders ycleped, when they desire not to unfold what deeds they have wrought.
Algoritme?
What manner of thing is an algoritme?
An algoritme doth be a logical function which performeth a given operation. Thus, one might technically call a function which addeth two numbers together an “algoritme”, yet oft times an algoritme is somewhat more complex than so. Oft are algoritmes employed to make operations which take much time, swifter.
Must I employ Python in these tasks?
Nay! Thou mayest use whatsoever tongue of programming doth please thee in these endeavours.
Innebygde biblioteker?
The conceit in these tasks doth lie in eschewing the use of built-in libraries or special Python functions. Forsooth, there existeth a simple “one-liner” to reverse text: text[::-1], yet here we desire thee to attempt to solve such tasks without employing the same. It may be that we mention a built-in function should the solution prove somewhat difficult to divine. This shall be marked with ❗.
In practice, ‘tis fully possible to resolve all these tasks with if, for, while and common list operations.
How to “Design” an Algorithm?
Most oft are algorithms designed iteratively. What doth this signify?
1. ✅ Break first the problem into lesser parts.
- Think ye first upon that which is most vital for the algorithm to function
- Shall it return a value? A
boolean? A list? - Do I require any helping functions?
- Shall it return a value? A
2. ❓ Doth any “edge-cases” exist?
- What doth befall shouldst thou cast in an empty list or text?
3. ✅ Begin, perchance, but to assay a solution.
4. ✅ Prithee, Examine if the Algorithm Doth Function Aptly in its Running
- Essay with larger input, doth it consume much time?
5. ❓ Ponder upon thy solution, doth thou require all the steps thou hast employed?
- Are all
if-checks needful? - Shouldst thou possess more than one
for-loop, exist there any clear ways to make this onefor-loop?- This doth differ shouldst thou have nested loops or loops one after another. One after another is oft times avoidable.
6. ✅ Consider Extreme Scenarios with Inputs:
- Example with numbers: great numbers, small numbers, negative numbers
- Text example: much text, many small words, extra spaces, large and small letters.
7. ❓ Doth it avail to employ pseudo-code to wit the logic more fully?
Task 1 - To Discern if a List Doth Contain a Given Number
Compose ye an algorithm (a function, if thou wilt) which shall discern if a list doth contain a given number. It shall return True or False based upon whether the number doth exist within the list or doth not.
Herein lieth a list with test-data:
Test-data for algoritme:
| Test-Data | Sjekk | Svar |
|---|---|---|
[1, 2, 3, 4, 5, 6, 7, 8, 9] | 5 | True |
[1, 2, 3, 4, 5, 6, 7, 8, 9] | 10 | False |
[2, 3, 5, 7, 11, 13, 17, 19, 23] | 2 | True |
[2, 3, 5, 7, 11, 13, 17, 19, 23] | 10 | False |
[-1, 0, 1, -34, 321, 22, 98, -214] | -214 | True |
[-1, 0, 1, -34, 321, 22, 98, -214] | 0 | True |
[-1, 0, 1, -34, 321, 22, 98, -214] | 2 | False |
Tips til framgangsmåte
- Take in a list and a list-value into a function. In this task, ‘tis numbers, yet may be text.
- Employ a
for-loop to traverse the list. - Should the number be like unto the check-number, return
True. - If the
for-loop doth conclude and thou hast not found it, returnFalse.
Svaret (i python)
def exists_in_list(the_list, check):
for number in the_list:
if number == check:
return True
return False
Verily, the answer (in the tongue of Python) doth present itself thus:
def exists_in_list(the_list, check):
for number in the_list:
if number == check:
return True
return False
A Task – Summation
Devise an algorithm that doth sum a list of numbers together.
Test-data for algoritme:
[1, 2, 3, 4, 5, 6], doth yield the answer21.[5, 1, 23, 68, 22, 13, 4], doth yield the answer136[3, 3, -3, -3, 3]doth yield the answer3. Perchance thou mayest disregard the numbers of ill omen and give the answer9.
Tips til framgangsmåte
- Do take a list within a function’s hold,
- And store a temporary sum as
0of old. - Employ a
for-loop to traverse the list, I say. returnthe sum of the list without delay.
Svaret (i python)
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
Lo, the answer (in the tongue of Python) doth lie thus:
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
Task 3a - The Greatest Value in a List
Devise an algorithm that doth discover the largest value within a list.
Test-data for algoritme:
[1, 2, 3, 4, 5, 6], doth yield the answer6.[6, 17, 227, 1, 23, 42, 12], doth yield the answer227[2, -2, 2, -2, -2, 2]doth yield the answer2.
Tips til framgangsmåte
- Take ye a list into a function.
- Set a temporary value unto the first element of the list.
- Employ a
for-loop to traverse the list and compare it with the value thou didst set in 2. - If the value be greater, set the temporary value unto the new value.
returnthis temporary value.
Svaret (i python)
def find_max(numbers):
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
Verily, the answer (in the tongue of Python) doth lie thus:
def find_max(numbers):
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
Task 3b - Should the List be Void?
Add a check which doth assay if the list doth contain any elements. Should it be empty, return None.
Svaret (i python)
def find_max(numbers):
if len(numbers) == 0:
return None
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
Verily, the answer (in the tongue of Python) doth lie thus:
def find_max(numbers):
if len(numbers) == 0:
return None
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
Task the Fourth – To Count the Number of a Given Element Within a List
Devise an algorithm which doth tally the number of a given element within a list.
Test-data for algoritme:
["apple", "banana", "orange", "apple", "apple", "banana"]withappledoth yield the answer 3.[1, 4, 5, 2, 4, -3, -4, 4, 2, 4, 221, 3, 1, 1, 4, 1, 12, 33, 4, 4, 2, -4, 1, 4]with4doth yield the answer8.["cat", "dog", "cat", "mouse", "cat", "dog", "dog"]withdogdoth yield the answer3.[7, 7, 2, 9, 7, 1, 0, 7, 3, 7, 9]with7doth yield the answer5.["red", "blue", "green", "red", "yellow", "red"]withreddoth yield the answer3.[10, -2, -2, -2, 5, 10, 10, -2]with-2doth yield the answer4.
Tips til framgangsmåte
- Take in a list and a check-value into a function
- Begin with a temporary count-value set to 0.
- Traverse the list with a
for-loop. - If the element is like unto the check, increase the count-value by 1.
- Return the count-value.
Svaret (i python)
def count(the_list, check):
count = 0
for element in the_list:
if element == check:
count += 1
return count
Lo, the answer (in the tongue of Python) doth present itself thus:
def count(the_list, check):
count = 0
for element in the_list:
if element == check:
count += 1
return count
Task the Fifth – To Reverse a String, Sayeth the Text
Devise an algorithm that doth reverse a given string.
Test-data for algoritme:
Hello there!doth become!ereht olleH.heisann alle sammendoth becomenemmas ella nnasiehPythondoth becomenohtyPracecardoth becomeracecar12345abcdoth becomecba54321god morgendoth becomenegrom dog
Tips til framgangsmåte
- Take in a
stringinto a function - Create a temporary value to store an empty
string. - Go through the texts with a
for-loop withrange. Here thou mayest traverse the list backwards, but ‘tis possible to solve this by proceeding forwards in the list. - Add each character to the temporary value in order.
- Return the temporary text.
Svaret (i python)
def reverse(text):
result = ""
# This line is somewhat complex, yet it doth begin
# at the end, proceeding (inclusive) to 0 (by writing
# -1 as the end), and counting downwards by 1 each time
for i in range(len(text) - 1, -1, -1):
result += text[i]
return result
Perchance thou mayest employ an algorithm that addeth to the beginning instead:
def reverse(text):
result = ""
for i in range(0, len(text)):
# add to the beginning instead
result = text[i] + result
return result
Task the Sixth - An Algorithm for Palindromes
Devise ye an algorithm that doth assay whether a given word be a palindrome. Examples of such palindromes are abba, racecar, regninger.
Tips til framgangsmåte
- Create a function that doth receive text to examine.
- Employ a
for-loop to ascertain if the letters on either side of the text be alike. - Return
Falseshould a letter not correspond; if all do match (for-loop doth complete), returnTrue.
Ekstra:
Dost thou perceive how thou mightest render the algorithm twice as swift?
Hint
Du trenger bare å sjekke halvparten!
Svaret (i python)
def palindrome(text):
for i in range(0, len(text)):
if text[i] != text[len(text) - i - 1]:
return False
return True
Raskere algoritme
def palindrome(text):
for i in range(0, int(len(text) / 2)):
if text[i] != text[len(text) - i - 1]:
return False
return True
Lo, the answer (in the tongue of Python)
def palindrome(text): for i in range(0, len(text)): if text[i] != text[len(text) - i - 1]: return False return TrueRaskere algoritme
def palindrome(text):
for i in range(0, int(len(text) / 2)):
if text[i] != text[len(text) - i - 1]:
return False
return True
Task the Seventh – To Discern if a List Be Sorted
Compose an algorithm that doth examine if a list be sorted. The most facile manner to assay this is to commence from the beginning, comparing if the next element be “greater.” Should an element not be “greater,” then is the list not sorted.
Test-data for algoritme:
[1, 2, 3, 4, 5, 6], doth yield the answerTrue.[6, 17, 227, 1, 23, 42, 12], doth yield the answerFalse[2, -2, 2, -2, -2, 2]doth yield the answerFalse.[2, 2, 3, 4, 4, 6], doth yield the answerTrue.[12, 23, 34, 45, 56, 67], doth yield the answerTrue.
Tips til framgangsmåte
- Create a function that doth receive a list.
- Employ a
for-loop to traverse the whole list (use range to the length of the list, less onelen(list) - 1). - Compare element \(n\) with \(n + 1\), that is, the current element with the next element.
- If \(n\) be less than \(n + 1\), proceed to the next comparison.
- If it be not less, but greater, then is the list not sorted. Return
Falsehere. - If thou dost reach the end, then is the list sorted, return
True.
Svaret (i Python)
def is_sorted(the_list):
for i in range(len(the_list) - 1):
if the_list[i] > the_list[i + 1]:
return False
return True
Verily, the answer (in the tongue of Python) doth lie thus:
def is_sorted(the_list):
for i in range(len(the_list) - 1):
if the_list[i] > the_list[i + 1]:
return False
return True
Task the Eighth - To Shuffle
Devise an algorithm that doth mingle a list of things. There be many ways to accomplish this, yet a goodly method is that which is called a Fisher-Yates shuffle algorithm. More upon this matter mayst thou find here Wikipedia.
Test Data
["a", "b", "c", "d", "e"]→ can become, forsooth,["c", "e", "a", "d", "b"][1, 2, 3, 4, 5, 6]→ can become, forsooth,[4, 1, 6, 3, 2, 5]["apple", "banana", "orange"]→ can become, forsooth,["orange", "apple", "banana"]["x"]→ doth remain as["x"][]→ doth remain as[]
Hark, how it doth operate:
Algoritmen
- Create a function that doth receive the list of numbers.
- Create a new, empty list which shall hold the mingled result.
- Employ a
randomto choose a chance index within the list. - Add this element unto the empty list and delete it from the old.
- Return the new list from the function.
Svaret (i Python)
import random
def shuffle(the_list):
shuffled = []
while len(the_list) > 0:
i = random.randrange(0, len(the_list))
shuffled.append(the_list[i])
the_list.pop(i)
return shuffled
Task 9 - Bogo-sort
In this task, thou shalt craft a (for all intents and purposes) dreadful, yet most simple sorting algorithm. ‘Tis exceedingly poor when it cometh to large lists (it shall take an age with more than 12-13 items). In Level 2, we shall devise a better sorting algorithm, bubble-sort.
Test Data
[3, 1, 2]→[1, 2, 3][5, 4, 3, 2, 1]→[1, 2, 3, 4, 5][10, 7, 8, 2]→[2, 7, 8, 10][1, 1, 1]→[1, 1, 1][9, 3, 6, 3, 9]→[3, 3, 6, 9, 9][0, -1, 4, -2]→[-2, -1, 0, 4]
The Algorithm doth function thus:
Algoritmen
- Create a function that doth receive the list of unsorted numbers.
- Shuffle the list by chance (use the shuffle from task 8).
- Check if the list is sorted (use the check thou didst make in task 7).
- If the list be not sorted, repeat steps 2 and 3.
- Repeat until the list is sorted, then return.
Simply explained: bogo-sort doth mix the whole list and hopeth that it is sorted.
Hark! Perchance employ shuffle from task eight to fashion an unsorted list for thine algorithm.
Svaret (i Python)
def bogo_sort(the_list):
while not is_sorted(the_list):
the_list = shuffle(the_list)
return the_list
Verily, the answer (in the tongue of Python) doth present itself thus:
def bogo_sort(the_list):
while not is_sorted(the_list):
the_list = shuffle(the_list)
return the_list
Task the Tenth, Part A - To Seek for Text - “Substring” (Most Difficult!)
Devise ye an algorithm that may discover a keyword within text. That is to say, shouldst thou possess a sentence such as hello there, thou shalt return True with the keyword hello, and False with a keyword like hahah. This algorithm shall function withal, regardless of input and output.
Employ the text-data hereunder to assay if thine algorithm doth function aright.
Test-data for algoritme:
hello there everyonewiththere=Truehello there everyonewithever=Truehello there everyonewiththen=Falseqwecvyufavsjekkftyergwcerywithsjekk=True
Tips til framgangsmåte
- Create a function that doth receive two
strings, data and søkeord. - Employ a
for-loop withrangeto traverse the text. - Here ‘tis most vital to consider how far the loop shall proceed.
- Create a temporary variable which doth declare if the søkeord hath been found, set it to
Trueby default. - Use yet another
for-loop withrangeto compare where thou art in the text with the søkeord. - If aught in the søkeord doth not match where thou dost check now, set the temporary variable to
Trueandbreakout of the inner loop. - If thou dost reach the end of the text without finding any match, return
False.
Svaret (i Python)
def search(data, word):
for i in range(0, len(data) - len(word) + 1):
found = True
for j in range (0, len(word)):
if data[i + j] != word[j]:
found = False
break
if found:
return True
return False
Verily, the answer (in the tongue of Python) doth lie thus:
def search(data, word): for i in range(0, len(data) - len(word) + 1): found = True for j in range (0, len(word)): if data[i + j] != word[j]: found = False break if found: return True return False
Task 10b
Add, I pray thee, yet another check to ensure the keyword doth not exceed the length of the sentence itself.
Tips til framgangsmåte
- Add this check ere the
for-loop doth begin.
Svaret (i python)
def search(data, word):
if len(word) > len(data):
return False
for i in range(0, len(data) - len(word) + 1):
found = True
for j in range (0, len(word)):
if data[i + j] != word[j]:
found = False
break
if found:
return True
return False
Lo, the answer (in the tongue of Python)
def search(data, word): if len(word) > len(data): return False for i in range(0, len(data) - len(word) + 1): found = True for j in range (0, len(word)): if data[i + j] != word[j]: found = False break if found: return True return False
Task Eleven – Reversing of Words in Sentence (Difficult)
Recall ye back unto Task Five concerning the reversing of a sentence. Amend (or begin anew), to craft an algorithm that doth reverse each single word within a sentence, and then joineth them once more.
Test-data for algoritme:
hello there everyonedoth becomeolleh ereht enoyreveThis is the way it goes!doth becomesihT si eht yaw ti !seogdoes this racecar go? of course!doth becomeseod siht racecar ?og fo !esruoc
Tips til framgangsmåte
- Create a function that doth receive a
string. - ❗Divide the text by employing
.split(" "). - Create a temporary variable to store the final value.
- Use a
for-loop to traverse each word. - Employ the same method for reversal as in Task 5
- Use the result and add it to the variable thou didst create in step 2.
- Return the final value
Svaret (i Python)
def reverse_words(words):
sentence = words.split(" ")
output = ""
for word in sentence:
reversed_word = ""
for i in range(0, len(word)):
reversed_word = word[i] + reversed_word
output += reversed_word + " "
return output
Lo, the answer (in the tongue of Python)
def reverse_words(words): sentence = words.split(" ") output = "" for word in sentence: reversed_word = "" for i in range(0, len(word)): reversed_word = word[i] + reversed_word output += reversed_word + " " return output
➕ An Addendum:
Task E1 - To Expunge Duplicates from a List
Say thou hast a list which doth contain numbers, or text, yet we would expunge the duplicates. Forge an algorithm which shall expunge all duplicates from a list, and contain only the first of each unique element which doth exist within the said list.
Tips til framgangsmåte
- Begin with a function that doth receive a list
- Here shall we employ
while-loops instead offor. ‘Tis made easier in Python, in other tonguesforwith counting variables doth function well. - Create a counting variable
idx(for index, ori) - Use a
whileloop which shall proceed to the length of the list - We shall compare the element at
idxwith all other elements - Create a counting variable to
jdx(orj) which doth begin atidx + 1 - Compare element at
idxwith element atjdx, if they be alike, deletejdxby usingpop(jdx). - HUSK! If thou dost delete the element, then the list doth become smaller, therefore must we step back a pace at
jdx -= 1. - Increase
jdxby 1 and test the next element - After the inner
while-loop increaseidxby 1 and the outerwhile-loop shall continue - Return at length the list with deleted duplicates
Test Data
[1, 2, 2, 3, 1, 4, 3]→ blir[1, 2, 3, 4]["a", "b", "a", "c", "b", "d"]→ blir["a", "b", "c", "d"][5, 5, 5, 5]→ blir[5]["x", "y", "z", "x", "y", "x"]→ blir["x", "y", "z"][10, -1, 10, -1, 0, 0, 10]→ blir[10, -1, 0]["apple", "apple', "banana", "orange", "apple", "orange", "pear", "apple"]- Shall yield:
["apple", "banana", "orange", "pear"]
- Shall yield:
Svaret (i Python)
def delete_duplicates(the_list):
idx = 0
while idx < len(the_list):
jdx = idx + 1
while jdx < len(the_list):
if the_list[idx] == the_list[jdx]:
the_list.pop(jdx)
jdx -= 1
jdx += 1
idx += 1
return the_list
Lo, the answer (in the tongue of Python)
def delete_duplicates(the_list): idx = 0 while idx < len(the_list): jdx = idx + 1 while jdx < len(the_list): if the_list[idx] == the_list[jdx]: the_list.pop(jdx) jdx -= 1 jdx += 1 idx += 1 return the_list
Task E2 - Counting Sort
Counting sort is one of the few sorting algorithms which doth function in what we call \(O(n)\) time. That is to say, it taketh not so very much longer than the number of elements in the list. Read more of Big O notation in Level 2.
It doth depend somewhat upon how great the span of elements is. If the least be 0 and the greatest be 100000 it may take a little time, so this may be used if the span of values is small. It worketh not for negative numbers, but one may modify the algorithm to work with negative numbers.
The algorithm worketh thus:
- Find out how great the greatest element is, store the value of this element as \(k\).
- Create a list which containeth \(k + 1\) elements,
count. - Go through the unsorted list and use the value of the number as index. That is to say, if the element hath the value 47, then go to
count[47]and increase it by 1. - Go through
countthe list and place the number of numbers as the index is. Example: There standeth 3 at index 1, so add three 1 numbers.
Testdata
| Unsorted Data | Sorted Data |
|---|---|
[7, 3, 9, 1, 4, 3, 0, 6, 8, 6, 2, 1, 9, 0, 5, 4] | [0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9] |
[12, 13, 15, 0, 8, 15, 8, 5, 16, 8, 0, 20, 4, 9, 17, 16, 1, 3, 6, 15, 5, 2, 3, 1, 19, 13, 17, 5, 3, 10] | [0, 0, 1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 8, 8, 8, 9, 10, 12, 13, 13, 15, 15, 15, 16, 16, 17, 17, 19, 20] |
Tips til framgangsmåte
- Begin with the crafting of a function, taking a list as its input.
- Create an empty
outputlist. - Employ a
for-loop to traverse the entirety of the list. - Keep track of the highest value within a variable ere the
for-loop. - Update the highest value shouldst thou discover a greater.
- Create a list containing this number of zeroes, plus one. For example: should the greatest value be forty-seven, then create a list with forty-eight zeroes. This canst thou do with
[0] * (maks + 1), or aforloop. Call itcount. - Traverse the list once more with a
for-loop. - Use the value of the element as index and increase by one.
count[value] += 1 - Employ a
for-loop to traverse thecountlist. - Use the value that is at each index to add that number of numbers.
- Return the sorted list.
Svaret (i Python)
def counting_sort(input_list):
output = []
max_val = input_list[0]
for n in input_list:
if n > max_val:
max_val = n
# dette vil lage en haug med nuller
count = [0] * (max_val + 1)
for n in input_list:
count[n] += 1
for i in range(len(count)):
# bruk _ for å ignorere en verdi
for _ in range(count[i]):
output.append(i)
return output

