How to find the smallest and largest freq or word in an list of objects represented by an object python - object

I have an object that represents a list of objects. Each of these represents a word and its frequency of occurrence in a file.
each object in the list has a word, and the frequency that it shows up in a file. Currently i'm getting an error that says "object is not iterable".
#each object in the list looks like this
#word = "hello", 4
def max(self):
max_list = [None, 0]
for item in WordList:
if item.get_freq() > max_list[1]:
max_list[0] = item.get_word()
max_list[1] = item.get_freq()
return max_list
how do i find the max and min frequency of these objects
Note: this is in a class WordList and that get_word and get_freq is in the class that created the objects in the list.

You question is not clear to me. Using 'object' in the title is at least once too many. The function does not use self. If WordList is a class, you cannot iterate it. Etc. However, I will try to give you an answer to what I think you are asking, which you might be able to adapt.
def minmax(items)
"""Return min and max frequency words in iterable items.
Items represent a word and frequency accessed as indicated.
"""
it = iter(items)
# Initialize result variables
try:
item = next(items)
min_item = max_item = item.get_word(), item.get_freq()
except StopIteration:
raise ValueError('cannon minmax empty iterable')
# Update result variables
for item in it:
word = item.get_word()
freq = item.get_freq()
if freq < min_item[1]:
min_item = word, freq
elif freq > max_item[1]:
max_item = word, freq
return min_item, max_item

Related

can anyone explain How Sorted function is working here especially that second part " -items[0] "

# code to print elements in a list on the basis of frequency they occurr
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
hashMap = {}
res = []
# getting the frequency
for i in nums:
if i in hashMap:
hashMap[i] = hashMap.get(i) + 1
else:
hashMap[i] = 1
# sorting on the basis of value in dictionary
hashMap = sorted(hashMap.items(), key=lambda item: (item[1], -item[0]))
for k,v in hashMap:
res.extend([k]*v)
return res
this code returns a list on the basis of the frequency the element appears in the list
it stores the count of each element
then sorts the elements on the basis of their frequency
and then append the elements the time they appear

Calculating the occurrence of unknown values in a list

I very often face the following problem:
I have a list with unknown elements in it (but each element is of the same type, e.g.: str) and I want to count the occurrence of each element. Sometime I also want to do something with the occurrence values, so I usually store them in a dictionary.
My problem is, that I cannot "auto initialize" a dictionary with +=1, so I first I have to do a check, if the given element is still in the dictionary.
My usual go to solution:
dct = {}
for i in iterable:
if i in dct:
dct[i] += 1
else:
dct[i] = 1
Is there a simpler colution to this problem?
Yes! A defaultdict.
from collections import defaultdict
dct = defaultdict(int)
for i in iterable:
dict[i] += 1
You can auto-initialise with other types too:
Docs: https://docs.python.org/3.3/library/collections.html#collections.defaultdict
d = defaultdict(str)
d[i] += 'hello'
If you're just counting things, you could use a Counter instead:
from collections import Counter
c = Counter(iterable) # c is a subclass of dict

TypeError-'function' object is not iterable

I have a program where by a teahcer can view the her student's squiz results and sort them in a avruiety way:
if role == 2:
class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
filename = (str(class_number) + "txt")
sort_or_not = prompt_int_small("Would youlike to sort these scores in any way? Press 1 if the answer is no or 2 if the answer is yes")
if sort_or_not == 1:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
lines.sort()
for line in lines:
print (line)
if sort_or_not == 2:
type_of_sort = prompt_int_big("How would you like to sort these scores? Press 1 for scores in alphabetical order with each student's highest score for the tests, 2 if you would like to see the students' highest scores sorted from highest to lowest and 3 if you like to see these student's average scores sorted from highest to lowest")
if type_of_sort == 1:
with open(filename , 'r') as r:
for line in sorted(r):
print(line, end='')
if type_of_sort == 2:
with open (filename,'r') as r:
def score(line):
return int(line.split(':')[1])
for line in sorted(r, key=score, reverse = True):
print(line)
if type_of_sort == 3:
with open (filename,'r') as r:
def score(line):
returnint(line.split(':')[1])
average = sum(map(int, score))/len(score)
print(name,"--",average)
However when the third option is selected an error comes up:
average = sum(map(int, score))/len(score)
TypeError-'function' object is not iterable
map() in Python-3.x returns an iterator (unlike Python-2.x where it returns a list of the result). Hence, you need to generate the list from the iterator and then pass it to the sum() function.
average = sum(list(map(int, score)))/len(score)
In the above, example score should be iterable like a list or a tuple.
EDIT: Well, map takes an iterable as an argument (like list, tuple) but in this case the argument passed, score, is a function. And you are passing the function name and not calling the function. Hence, a function gets passed to the map() function. So, you need to call the function. Eg:
score_list = score(r.readline())
average = sum(list(map(int, score_list)))/len(score_list)

No Print Statement in Mutant DNA Generator

So I have a code that is a mutant dna generator - more specifically, it yields 100 strands with a point mutation frequency of 0.066% for any base, derived from an original strand I have specified in the code. The problem I'm having with it, however, is the print statement. I don't get an output, and I'm not sure why. Here's my code:
import random
class DNA_mutant_generator:
def __init__ (self, dna):
self.dna = dna
self.bases = bases
def mutate(self, mutation_rate=0.0066): #add a specification of the mutation rate of 0.066%
result = []
mutations = []
for base in self.dna:
if random.random() < mutation_rate: #random.random() returns the next random floating point number in range [0.0,1.0)
new_base = bases[bases.index(base) - random.randint(1, 3)] # subtracts the position of a certain base from a random integer within the range of 1 to 3 in the bases list. This creates the newly mutated base.
result.append(new_base)#append that new base to the result list
mutations.append((base, new_base))#appends the original base, as well as the new mutated base to a list of tuples
else:
result.append(base)#
return "".join(result), mutations # returns mutated strands, as well as mutations
for result_string, mutations in results:
if mutations: # skip writing out unmutated strings
print(result_string, mutations)
bases = "ACTG" #specifies the bases in the DNA strand
orig_dna = "GGCTCTCCAACAGgtaagcactgaagggtagaaggcatcgtctgtctcagacatgtctggcaccatccgctaagacattaccacgtgggtctcgagtatagctaacacccttctgtttggcagCTTACAGGAGCGAACGTTGG"
dna = orig_dna.upper()
dna_mutants = DNA_mutant_generator(dna)
dna_mutants.mutate()
Does anybody know what else I should add in order to get the output I specified in my function? I did include a print statement, so I'm not sure why the code is not yielding anything.
EDIT 2:
Should the code look something like this, then?
import random
class DNA_mutant_generator:
def __init__ (self, dna):
self.dna = dna
self.bases = bases
def mutate(self, mutation_rate=0.0066): #add a specification of the mutation rate of 0.066%
result = []
mutations = []
for base in self.dna:
if random.random() < mutation_rate: #random.random() returns the next random floating point number in range [0.0,1.0)
new_base = bases[bases.index(base) - random.randint(1, 3)] # subtracts the position of a certain base from a random integer within the range of 1 to 3 in the bases list. This creates the newly mutated base.
result.append(new_base)#append that new base to the result list
mutations.append((base, new_base))#appends the original base, as well as the new mutated base to a list of tuples
else:
result.append(base)#
return_value = "".join(result), mutations # returns mutated strands, as well as mutations
for result_string in results:
if mutations: # skip writing out unmutated strings
print(result_string, mutations)
return return_value
results = [dna_mutants.mutate() for _ in range(100)] #prints 100 strands
bases = "ACTG" #specifies the bases in the DNA strand
orig_dna = "GGCTCTCCAACAGgtaagcactgaagggtagaaggcatcgtctgtctcagacatgtctggcaccatccgctaagacattaccacgtgggtctcgagtatagctaacacccttctgtttggcagCTTACAGGAGCGAACGTTGG"
dna = orig_dna.upper()
dna_mutants = DNA_mutant_generator(dna)
dna_mutants.mutate()
but if I move results outside of the fnction, so that mutate is not repeated within the function, I get this error message:
results = [dna_mutants.mutate() for _ in range(100)] #prints 100 strands
NameError: global name 'dna_mutants' is not defined
You are returning before your print statement with the following line:
return "".join(result), mutations # returns mutated strands, as well as mutations
If you want to print information after this line, remove the return statement assign the expression to a variable instead, and then return that variable at the end of the function.
return_value = "".join(result), mutations # returns mutated strands, as well as mutations
for result_string in result:
if mutations: # skip writing out unmutated strings
print(result_string, mutations)
return return_value
Edit: Your new problem is because you've created a recursive function that is calling itself over and over and over again. Everytime a function calls itself, it requires more space on the stack, and you called it so many times your stack "overflowed".

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources