Find the Mode of a List - python-3.x

L = [98,75,92,87,89,90,92,87]
def mode(L):
shows = []
modeList = []
L.sort()
length = len(L)
for num in L:
count = L.count(num)
shows.append(count)
print 'List = ', L
maxI = shows.index(max(shows))
for i in shows:
if i == maxI:
if modeList == []:
mode = L[i]
modeList.append(mode)
print 'Mode = ', mode
elif mode not in modeList:
mode = L[i]
modeList.append(mode)
print 'Mode = ', mode
return mode
mode(L)
I can't seem to iterate through my list properly...
I can successfully get the first Mode to return >>>(Mode = 87) using the 2nd for-loop however, I can't get it to search the rest of the list so that it will also return >>>(Mode = 92)
I've deleted my attempts at Mode = 92, can you help fill in the blanks?
Thanks

the same idea with collections.Counter
from collections import Counter
L = [98,75,92,87,89,90,92,87]
def mode(L):
# count the occurring frequencies
count = Counter(L)
# find the max
mx = max(count.values())
# collect the frequencies that occur the most
modes = [f for f, m in count.items() if m == mx]
return modes
print(mode(L))
# [87, 92]

Good job on the code. I rewrote it a little. See below code:
L = [98,75,92,87,89,90,92,87]
def mode(L):
# Create a frequency table
freq = {}
for num in L:
if not num in freq:
freq[num] = 1
else:
freq[num] += 1
# Gets maximal occurence
maxoccurence = 0
for f in freq:
maxoccurence = max(maxoccurence, freq[f])
# Put all the numbers with the occurence in a list
modes = []
for f in freq:
if freq[f] == maxoccurence:
modes += [f]
# Returns the list
return modes
print(mode(L))

Related

Appending results from a list to a string

Heavy python beginner here. I want to create a simple function for a PIN guessing game that receives two 4-digit lists ( [guess], [answer] ) and returns a string with 4 letters stating how close I am to guessing the correct [answer] sequence (eg. Higher, True, Lower, Higher)
However, I get a new list for each string:
def checkNumbers(guess,right):
for n in range(4):
result = []
if guess[n] == right[n]:
result.append("T") #true
elif guess[n] < right[n]:
result.append("H") #higher
elif guess[n] > right[n]:
result.append("L") #lower
else:
result.append("F") #false
print (result)
return
checkNumbers([1,2,3,5],[2,2,1,6])
The result should look like this:
checkNumbers([1,2,3,4], [2, 2, 1 , 6]) #call function with ([guess], [answer])
'HTLH' #returns a string stating how accurate [guess] is to [answer] list
Result looks like this however:
checkNumbers([1,2,3,5],[2,2,1,6])
['H']
['T']
['L']
['H']
Thanks very much in advance for any help I could get.
you can use string instead of list or "".join()
def checkNumbers(guess, right):
result = ""
for n in range(4):
if guess[n] == right[n]:
result += "T" # true
elif guess[n] < right[n]:
result += "H" # higher
elif guess[n] > right[n]:
result += "L" # lower
else:
result += "F" # false
print(result)
but... maybe you want to use zip function
def checkNumbers(guess, right):
result = ""
for g, r in zip(guess, right):
if g == r:
result += "T" # true
elif g < r:
result += "H" # higher
elif g > r:
result += "L" # lower
else:
result += "F" # false
print(result)
Funny bonus here:
def checkNumbers(guess, right):
print("".join("THL"[(g > r) + (g != r)] for g, r in zip(guess, right)))
I don't get why you need else part...
Initiate the list and print the result outside of the loop:
def checkNumbers(guess, right):
result = []
for n in range(4):
# do loopy stuff
print (result)
return # not strictly necessary
If you do it inside, you are creating a new list on every iteration.

ModuleNotFoundError: No module named 'src'. Python 3 error

I'm facing the dreaded ModuleNotFoundError: No module named 'src' error. I've done quite some extensive reading into this problem and see that this is a common problem. I can't seem to wrap my head around this.
You can pull my repo at https://github.com/mustafahoda/data-structures-and-algos
Here is what my current project directory looks like.
I'm using pipenv and running commands from after entering the env shell.
I'm using python 3
DSandAlgoBenchmarkSuite
src
|---CommonProblems
|---DataStructures
|---SortingAlgorithms
|--sorting_algos.py
test
|---test_bubble_sort_1.py
.gitignore
.benchmarks
.pytest_cache
Pipfile
Pipfile.lock
test.py
test_bubble_sort_2.py
I have two files that I'd like to run:
test/test_bubble_sort_1.py
test_bubble_sort_2.py
Contents of each file.
# test/test_bubble_sort_1.py
from src.SortingAlgorithms import sorting_algos
import pytest
# test_bubble_sort_2.py
from src.SortingAlgorithms import sorting_algos
import pytest
# src/SortingAlgorithms/sorting_algos.py
# ---------BUBBLE SORT-------------
def bubble_sort(A: list) -> list:
sorted = len(A)
for i in range(len(A)):
L = 0
R = 1
while R != len(A) :
# if L > R, then swap
if A[L] > A[R]:
temp = A[L]
A[L] = A[R]
A[R] = temp
L = L + 1
R = R + 1
return A
# -----------------INSERTION SORT----------------------
def shift_items_to_right(B, start, stop):
for i in range(stop, start, -1):
B[i] = B[i - 1]
return B
def insertion_sort(A : list) -> list:
sorted = 0
while sorted != len(A):
hole = 0
for i in A[:sorted + 1]:
value = A[sorted]
if value < A[hole]:
# move all items to the right from the hole onwards
shift_items_to_right(A, hole, sorted)
# store the value in the hole
A[hole] = value
else:
hole = hole + 1
sorted = sorted + 1
return A
# ---------------------MERGE SORT--------------------------------------
def merge(A: list, B: list) -> list:
ptr_A = 0
ptr_B = 0
C = []
while ptr_A <= len(A) - 1 and ptr_B <= len(B) - 1:
if A[ptr_A] >= B[ptr_B]:
C.append(B[ptr_B])
ptr_B = ptr_B + 1
else:
C.append(A[ptr_A])
ptr_A = ptr_A + 1
if ptr_A == len(A):
for i in B[ptr_B:]:
C.append(i)
else:
for i in A[ptr_A:]:
C.append(i)
return C
def merge_sort(A: list) -> list:
print("A: %s" % A)
if len(A) == 1:
return A
# STEP 1: Divide
mid = len(A) // 2
L = A[:mid]
R = A[mid:]
if L is not None:
L = merge_sort(L)
if R is not None:
R = merge_sort(R)
merged = merge(L, R)
print("Merged: %s" % merged)
return merged
# ---------------------QUICK SORT--------------------------------------
def quicksort(A: list) -> list:
return _quicksort(A, 0, len(A) - 1)
def _quicksort(A: list, start: int, end: int) -> list:
if start >= end:
return A
print("A before partition: %s" % A)
pIndex = partition(A, start, end)
print("A after partition: %s" % A)
print("_____________________________")
_quicksort(A, start, pIndex - 1)
_quicksort(A, pIndex, end)
return A
def partition(A, start: int, end: int):
# set_trace()
pivot = A[end]
i = start
pIndex = start
# set_trace()
while i < end:
# set_trace()
if pivot >= A[i]:
# implement swap between pIndex and A[i]
temp = A[i]
A[i] = A[pIndex]
A[pIndex] = temp
pIndex = pIndex + 1
i = i + 1
# once we reach the element before the pivot, we swap pivot into pIndex
temp = A[pIndex]
A[pIndex] = pivot
A[end] = temp
# set_trace()
print(A)
return pIndex
# ---------------------SELECTION SORT-------------------------------------
def find_min_not_in_place(A: list, visited) -> int:
for i in A:
if visited[i] == False:
min = i
break
for i in A[1:]:
# set_trace()
if i < min and visited[i] == False:
# set_trace()
min = i
# visited[min] = True
return min
def selection_sort_not_in_place(A: list) -> list:
B = []
# construct a dictionary that will keep track of visited numbers
visited = dict()
for i in A:
visited[i] = False
# keep repeating the process until theere are no values in dictionary with False
while False in visited.values():
for i in A:
min = find_min_not_in_place(A, visited)
# set_trace()
B.append(min)
visited[min] = True
print(B)
return B
def find_min_in_place(A: list, sorted_index: int) -> int:
min_index = sorted_index
min = A[sorted_index]
# for i in A[sorted_index:]:
for i in range(sorted_index, len(A)):
if A[i] < min:
min = A[i]
min_index = i
return (min, min_index)
def selection_sort_in_place(A: list) -> list:
sorted = 0
while sorted != len(A):
# min, min_index = find_min_in_place(A[sorted + 1:])
min, min_index = find_min_in_place(A, sorted)
# implement swapping
temp = A[sorted]
A[sorted] = min
A[min_index] = temp
sorted = sorted + 1
return A
Ideally, I want pytest-benchmark suite to work but I've isolated the problem to being an import error.
When I run test_bubble_sort_2.py from the main project directory, it works fine!
However, when I run test/test_bubble_sort_1.py from the main project directory, it doesn't work and throws the exception: ModuleNotFoundError: No module named 'src'
I'd like to run test/test_bubble_sort_1.py in order to maintain the project structure and access the functions from my sorting_algos.py file so I can benchmark them.

list index error python (numeric words program)

I'm trying to write a program in Python 3.
This is how it works:
The input is a word.
And the program has to look if the word contains a dutch numeric word.
A word cannot contain more than 1 numeric word and if a word doesn't contain a numeric word than it has to print 'geen' (none in dutch).
example:
Input = BETWEEN
Output = TWEE (two in dutch)
Input = ZEEVERS
Output = ZES (six in dutch)
Here is my code:
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(0, 8):
for j in range(0, len(letterwoorden[a])):
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord.clear()
if antwoord != letterwoorden[a]:
print('geen')
Could someone help me with the error on line 21? (list index out of range)
Thanks!
The code is not fully done but when the input is TWEET the output is TWEE,
when the input is BETWEEN it gives the error.
Even though usr2564301's first solution looks good, I wanted to add a couple things. You'll find this in the comments in the code.
Here's how I'd modify your code:
## use strings instead of list of strings
## ['T', 'W', 'E', 'E'] ==> 'TWEE'
## they are also iterable (you can loop through them)
## as well as indexable (['T', 'W', 'E', 'E'][0] == 'TWEE'[0])
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
## keep the string
woord = input()
print('Input:', woord)
## answer should be string as well
antwoord = ''
## name your variables something meaningful
## how does one differentiate between b and c? smh
letterWoordenIndex = 0
woordenIndex = 0
## for-loops can be powerful in Python
## you might've been used to index-based loops from other languages :|
## this way, tempWord can replace all occurrences of letterwoorden[a]
for tempWord in letterwoorden:
## reset your variables at the beginning of the loop
letterWoordenIndex = woordenIndex = 0
# """ ## debug output printing word
print('Word:', tempWord, '?')
# """
## loop through the length of word
## use _ to indicate that the variable won't be used
for _ in range(len(woord)):
# """ ## debug output comparing letters/indices
print(tempWord[letterWoordenIndex],
'({})'.format(letterWoordenIndex),
'<=>', woord[woordenIndex],
'({})'.format(woordenIndex))
# """
## check current indices equals match
if tempWord[letterWoordenIndex] == woord[woordenIndex]:
antwoord += tempWord[letterWoordenIndex] ## append char to string using +
## increment indices
letterWoordenIndex += 1
woordenIndex += 1
## check if index is filled
if letterWoordenIndex == len(tempWord):
break
else:
woordenIndex += 1
# """ ## debug output comparing final results
print(antwoord, '>==<', tempWord)
# """
## assert that the accumulated result (antwoord)
## equates to the tempWord
if antwoord == tempWord:
# """ ## debug assert true
print('Yep\n')
# """
print(antwoord)
break
## no need to use else here
## if the code inside the above if executes, then it's already game-over
antwoord = '' ## empty the string
# """ ## debug assert false
print('Nope\n')
# """
## antwoord would be empty if everything failed
if antwoord == '':
print('GEEN')
You are iterating over the wrong list with your line
for j in range(0, len(letterwoorden[a])):
as this increases a for all letterwoordenagain – you already iterate over letterwoorden with the first loop, for i in range(0, 8):. Changing that to iterate over the word in question led to another error if you run out of 'source' characters (the length of invoer) OR of 'compare' characters (the word woord[c]). You must also take care to reset your b and c counters when restarting a compare.
At the very end, you test antwoord[a] but a may be out of range
The following code works
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(len(letterwoorden)):
b = 0
c = 0
for j in range(len(woord)):
print ('test', a,b,c, letterwoorden[a][b], woord[c])
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
if b >= len(letterwoorden[a]):
break
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord = []
if antwoord == []:
print('geen')
A few additional notes: you don't need to maintain separate variables if you already have a loop variable. Where you use a, for example, you can also use the loop i; and the same with j.
About all of your comparing can be done much more efficiently, since Python can immediately check if a phrase contains another phrase: if straw in haystack. So, basically,
invoer = 'ZEEVERS'
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
for word in letterwoorden:
if word in invoer:
print (word)
break
else:
print ('geen')
where the else is linked to the for and not to the else, to check if the loop stopped for a result.

always got the same output with random.choice in a function

I tried using for-loop to exec my function but its always the same result.
import random
def main(arr):
result = random.choice(arr)
...some code...
return len(result)
for i in range(100):
main(arr)
I could only get diff result from stop/run the terminal. Anyone know why?
my question is the same as this one. random.choice always same
import random
results = []
with open('kargerMinCut.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split('\t'))
def contract(arr):
while len(arr) > 2:
# Generate random number in list of lists
# ranList = random.choice(arr)
ranList = arr[np.random.choice(len(arr))]
ranNum = random.choice(ranList[1:])
# retrieve the index of the random number
listIndex = arr.index(ranList)
for i in range(0, len(arr)):
if arr[i][0] == ranNum:
targetList = i
break
target = ranList[0]
for i in range(0, len(arr)):
if i == listIndex:
arr[i].pop(0)
arr[i] = [x for x in arr[i] if x != ranNum]
elif i == targetList:
arr[i] = [x for x in arr[i] if x != target]
else:
for index, item in enumerate(arr[i]):
if item == target:
arr[i][index] = ranNum
arr[targetList] += arr[listIndex]
del arr[listIndex]
return len(arr[0])-1
the arr would be like this
array = [[1,2,3,4],[2,1,3,4],[3,1,2,4],[4,1,2,3]]
I don't know what you do inside your function but I've got the normal result. And in the question what you linked to the person just used seed. This is kinda pseudorandom that gives you all the time the same random output. Here is the link to deep your knowledge about pseudorandom
import random
arr = [1,2,3,4,5]
def main(arr):
result = random.choice(arr)
print(result)
for i in range(100):
main(arr)
The result is as it has to be:
1
3
5
3
4
3
1
4
4
3
2

Counting substrings in string

Lets assume that i have 2 strings
M = "sses"
N = "assesses"
I have to count how many times string M is present into string N
I am not allowed to use any import or methods just loops and range() if needed.
M = "sses"
N = "assesses"
counter = 0
if M in N:
counter +=1
print(counter)
This isn't good enough i need loop to go trough N and count all M present
in this case it is 2.
def count(M, N):
i = 0
count = 0
while True:
try:
i = N.index(M, i)+1
count += 1
except ValueError:
break
return count
Or a one-liner without str.index:
def count(M, N):
return sum(N[i:i+len(M)]==M for i in range(len(N)-len(M)+1))
The same without using the sum function:
def count(M, N):
count = 0
for i in range(len(N)-len(M)+1):
if N[i:i+len(M)] == M:
count += 1
return count

Resources