Using a returned array in another function - python-3.x

I have a function that returns an array and a second function that is supposed to use this returned array, but the program returns saying array is not defined. How can I fix this problem?
def popt_reader(filename):
with codecs.open(popt, 'r', encoding='utf-8') as data_file:
rows, cols = [int(c) for c in data_file.readline().split() if c.isnumeric()]
array = np.fromstring(data_file.read(), sep=' ').reshape(rows, cols)
return array
def cleaner():
out = []
en_point = 0
for i in range(1,len(array)):
if np.all((array[i,1::] == 0)):
pass
else:
out.append(array[i,:])
en_point += 1
print(en_point)
cleaner(array)

You never call the function that returns the array. Try this, just input your own file name
...
filename = "my_array_file_here.array"
array = popt_reader(filename)
cleaner(array)

Variable array is defined within the popt_reader function and is not accessible within the cleaner function.
Add this line of code before cleaner(array) to make it work:
array = popt_reader(filename)
Which will assign output of popt_reader method to array variable.
Note that filename should also be defined beforehand
filename = "path to file"

Just add a signature(parameter) to the function cleaner()
second one should be:
def cleaner(array):
out = []
en_point = 0
for i in range(1,len(array)):
if np.all((array[i,1::] == 0)):
pass
else:
out.append(array[i,:])
en_point += 1
print(en_point)
cleaner(array)

Related

myNames gets the list but when trying to get the average, an error saying object is not iterable in the for loop when trying to get the average

def myNames():
b = []
while True:
a = input("whats the name: ")
if a != "done":
b.append(a)
elif a == "done":
break
return b
x = myNames()
print (x)
def getAverageLength(myNames):
total = 0
for i in myNames: #This line of code gives me an error and I cant figure it out
total = total + len(i)
average = float(total) / float(len(myNames))
return average
getAverageLength(myNames)
It takes my first function (myNames) as an argument. Ive been trying to figure this error out but have no idea what to do here
Your last line: getAverageLength(myNames), like you said in your description, is using myNames as a parameter which is only present as a function in the current scope.
This means when you reach your for loop, you end up trying to iterate over a function, since that is what was passed into getAverageLength
Maybe you meant getAverageLength(x)?
Or perhaps getAverageLength(myNames()) since myNames() passes the result of the function as opposed to the function itself.
To correctly calculate the average length of the strings, you could use the following:
averageLength = sum(map(len, x)) / len(x)

Using Python to identify if two words contain the same letter

Problem to solve:
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none.
Solution Tested:
a = ['aabb', 'abcd', 'bbaa', 'dada']
b = ['abab']
listA = []
sorted_defaultword = sorted(b[0])
print (sorted_defaultword)
for i in range (len(a)):
#print(a[i])
sorted_word = sorted(a[i])
#print (sorted_word)
if (sorted_word == sorted_defaultword):
listA.append(a[i])
print (listA)
Test Output:
['a', 'a', 'b', 'b']
['aabb', 'bbaa']
Using the test, I then tried to write my function but apparently it will not work. Can someone please suggest why:
def anagrams(word, words):
sorted_defaultword = sorted(word[0])
anagram_List = []
for i in range (len(words)):
sorted_word = sorted(words[i])
if (sorted_word == sorted_defaultword):
anagram_List.append(words[i])
return anagram_List
Why is this failing when I put it in a function?
You are passing wrong arguments to the function.
Test.assert_equals(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']), ['aabb', 'bbaa']
here you are passing the first parameter as a string. while the function expects a list.
Change your code to:
Test.assert_equals(anagrams(['abba'], ['aabb', 'abcd', 'bbaa', 'dada']), ['aabb', 'bbaa']
note that I have just passed 'abba' in a list, because your function expects it to be a list.
If you want to use your previous code, from your function change this line sorted_defaultword = sorted(word[0]) to sorted_defaultword = sorted(word)
And this should do the job...

using for loop to count list elements in a string

Im beginner in python, learning it for biology purposes.
Ok, lets suppose I want to write a function that will iterate over a list to count how many of its elements in the string using for loop
def counting(string,lista):
for element in lista:
element_count=string.count(element)
return element_count
so when using the above function to find how many A and C in my string
print(counting('AABCDEF',['A','C']))
It seems the function only return the count of C in the string which is 1, what I want to get both elements count. It seems adding a print line inside the loop body will solve the problem,
def counting(string,lista):
for element in lista:
element_count=string.count(element)
print(element_count)
return element_count
is there a way to get the same output without using the print statement?
Thanks in advance
Return the result as a list.
def counting(string,lista):
temp = []
for element in lista:
temp.append(string.count(element))
return temp
print(counting('AABCDEF',['A','C']))
The result is
[2, 1]
To print some verbose,
def counting(string, lista):
temp = []
for element in lista:
temp.append('{} count is {}'.format(element, string.count(element)))
return ', '.join(temp)
print(counting('AABCDEF', ['A','C']))
Then
A count is 2, C count is 1

Python - passing string and specific lists, combined into function

i want to pass string (dirPath + dirName[x]) to a function
i already tried 3 times to combining string and a specific list (only dirName[x])
it seems that python just rejecting it anyway even if i already convert it to another type.
is anyone know how i pass this string to Function?
layer = 0
dirName = []
#dummy value layer = 4, dirName = [/a,/b,/c,/d], dirBruteForce(layer,vault)
def dirBruteForce(layer,dirPath):
if layer > 0 :
#call again to make layered dir
for x in range(len(dirName)):
dirBruteForce(layer - 1, dirPath + dirName[x]) ##this line
#call end of the dir
elif layer is 0 :
for x in range(len(dirName)):
try:
os.makedirs(dirPath)
print(dirPath)
except Exception as e:
pass
###
try1:
dirBruteForce(layer - 1, dirPath + dirName[x])
TypeError: can only concatenate list (not "str") to list
try2:
list = [dirPath,str(dirName[x])]
dir = ''.join(list)
dirBruteForce(layer - 1, dir)
error2:
dir = ''.join(list)
TypeError: sequence item 0: expected str instance, list found
try3:
dir = ''.join([dirPath,dirName[x]])
dirBruteForce(layer - 1, dir)
error3:
dir = '-'.join([dirPath,dirName[x]])
TypeError: sequence item 0: expected str instance, list found
Looks like dirPath is a list. You need to convert it to a string (for example using str.join() if you just want all the elements concatenated) before you concatenate the next part:
''.join(dirPath) + dirName[x]

Function's input appear to be a list

I have a nested list and a header which is the column name.
I want to find maximum in column and print out the maximum's row information.
Here's my code.
def find_col(v):
for i in range(1,31):
if header[i]==v:
return i
def col_list(col):
list = []
for row in linelist:
list.append(row[int(col)])
return list
def M(col):
def max(li):
inf = -float('inf')
maxnumber = inf
for i, value in enumerate(li):
if value>maxnumber:
maxnumber = value
return maxnumber
return max(col_list(col))
def max_row(col):
li = col_list(col)
m = M(col)
for i, j in enumerate(li):
if j == m:
return i
def col_max(name):
col = find_col(name)
return M(col)
def pri(name):
column = find_col(name)
maxima = M(column)
li = col_list(column)
maxrow = max_row(li)
print(linelist[maxrow][1], linelist[maxrow][4], maxima)
pri('MP')
The problem is at function col_list, but I can't figure out how 'col' appear to be a list.
The problem seams to be that in the function pri(name) you call max_row in the statement maxrow = max_row(li) where li is what col_list returns (a list...) so you call max_row(<somelist>). However, max_row then goes ahead and calls col_list with its input parameter (so a list, since it was passed a list...) that's where things go wrong.
How to fix it depends on what exactly you want to do. If I understand your intentions correctly something like:
li = []
for row in <imputParameter>: ## in your case its called col, but its a list...
li.append(max(row)) ## or some other way to compute the value you want from that...
##continue function as in your case...
hope that helps.

Resources