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]
Related
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)
'Original String = 1234 A 56 78 90 B'
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
return ends
The above returns:
['B', 'A']
My next function is supposed to then combine them into 1 string and get value from dictionary. I've tried this with/without the str in mult_ends with the same result.
def func_2(two_dict):
global mult_ends
mult_ends = str(ends[0] + ends[1])
for key in mult_ends:
if key in two_dict:
return two_dict[key]
The results confuse me since I use pretty identical processes in other functions with no issue.
IndexError: list index out of range
Why would the list index be out of range when there is clearly a 0 and 1? I've also added global ends to func_2 and I still received the same error.
*** RESTRUCTURED FUNCTIONS INTO 1 ***
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
mult_ends = ends[0] + ends[1]
for key in two_dict:
if key in mult_ends:
return ends_final_dict[key]
return None
Now, it actually does what I want it to do and returns the correct dictionary key in the event log:
A B
However, it does not return when I try to insert it back into my GUI for the user and it still throws the IndexError: list index out of range.
I have a long list of sources and targets that form a graph as follows:
id_a = [...] #source nodes
id_b = [...] #target nodes
distance = [..] #distance between source and target nodes
G = nx.Graph()
path, length = [], []
for a, b, c in zip(id_a, id_b, distance):
G.add_edge(a, b, weight=c)
cl is a subset of all the nodes in the graph and I want to extract the paths interconnecting all of cl together so I use all_simple_paths()
path = []
for i in range(len(cl)):
for j in range(len(cl)):
if i != j:
path.append(nx.all_simple_paths(G, source=cl[i], target=cl[j]))
I want to be able to list all the simple paths and their lengths so I try:
for i in range(len(path)):
total_length = 0
for j in range(len(path[i])-1):
source, target = path[i][j], path[i][j+1]
edge = G[source][target]
length = edge['weight']
total_length += length
length.append(total_length)
But I keep getting the error
object of type 'generator' has no len()
And I can't figure out how to convert the generator of all_simple_paths() to lists that I can iterate over and extract the full lengths of all the paths.
Any help is appreciated!
If you read the documentation of all_simple_paths, you will see that it returns a generator. So, just use extend instead of append method like this
path = []
for i in range(len(cl)):
for j in range(len(cl)):
if i != j:
path.extend(nx.all_simple_paths(G, source=cl[i], target=cl[j]))
For more info on why extend works in this case, see this answer.
Also I see in the last part of your code, you are setting length as length = edge['weight'], then appending using length.append(total_length). This will return as error, since the edge weight will be an int. Use different variable names something like this
path_weight = [] #<----- List to store all path's weights
for i in range(len(path)):
total_length = 0
for j in range(len(path[i])-1):
source, target = path[i][j], path[i][j+1]
edge = G[source][target]
length = edge['weight'] #<--- Get the weight
total_length += length
path_weight.append(total_length) #Append to the list
I actually need help evaluating what is going on with the code which I wrote.
It is meant to function like this:
input: remove_duple('WubbaLubbaDubDub')
output: 'WubaLubaDubDub'
another example:
input: remove_duple('aabbccdd')
output: 'abcd'
I am still a beginner and I would like to know both what is wrong with my code and an easier way to do it. (There are some lines in the code which were part of my efforts to visualize what was happening and debug it)
def remove_duple(string):
to_test = list(string)
print (to_test)
icount = 0
dcount = icount + 1
for char in to_test:
if to_test[icount] == to_test[dcount]:
del to_test[dcount]
print ('duplicate deleted')
print (to_test)
icount += 1
elif to_test[icount] != to_test[dcount]:
print ('no duplicated deleted')
print (to_test)
icount += 1
print ("".join(to_test))
Don't modify a list (e.g. del to_test[dcount]) that you are iterating over. Your iterator will get screwed up. The appropriate way to deal with this would be to create a new list with only the values you want.
A fix for your code could look like:
In []:
def remove_duple(s):
new_list = []
for i in range(len(s)-1): # one less than length to avoid IndexError
if s[i] != s[i+1]:
new_list.append(s[i])
if s: # handle passing in an empty string
new_list.append(s[-1]) # need to add the last character
return "".join(new_list) # return it (print it outside the function)
remove_duple('WubbaLubbaDubDub')
Out[]:
WubaLubaDubDub
As you are looking to step through the string, sliding 2 characters at a time, you can do that simply by ziping the string with itself shifted one, and adding the first character if the 2 characters are not equal, e.g.:
In []:
import itertools as it
def remove_duple(s):
return ''.join(x for x, y in it.zip_longest(s, s[1:]) if x != y)
remove_duple('WubbaLubbaDubDub')
Out[]:
'WubaLubaDubDub'
In []:
remove_duple('aabbccdd')
Out[]:
'abcd'
Note: you need itertools.zip_longest() or you will drop the last character. The default fillvalue of None is fine for a string.
Below is my code I have printing this in ascending order I now need to print it in descending order but don't know how? I have tried the below code however it is not printing my desired results i.e Jill,8,1,0 first and soon
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(len(sorted_list),2,-3,-1):
des_list.append(sorted_list[i-2])
des_list.append(sorted_list[i - 1])
des_list.append(sorted_list[i])
des_list.append(sorted_list[i+1])
print(des_list)
OP is incredibly vague and I can't determine any way in which the list provided is 'sorted' while a reversal of the list would print out 'jill' first. At any rate, I've assumed:
The strings are supposed to be names
The ints that follow are attributes of the aforementioned names
With that, I created a dict that holds the names and attributes. This would be sorting by alphabetical name with the attributes in their original order.
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
nameDict = {}
tmp = None
for _ in sorted_list:
if isinstance(_, str):
tmp = _
nameDict[tmp] = []
else:
if tmp: nameDict[tmp].append(_)
final = []
for name in list(reversed(sorted(nameDict))):
final += [name] + nameDict[name]
print final
While writing this, OP seems to have responded to my comment and apparently would like the attributes themselves in descending order.
sorted_list = ["jack",4,3,1,"jill",8,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
nameDict = {} # empty dictionary {key1 : value1, key2 : value2 } etc...
tmp = None # temporary variable used to keep track of the name
for _ in sorted_list:
if isinstance(_, str): # if the name is a string...
tmp = _ # ... set the temporary variable to the name
nameDict[tmp] = [] # create an entry in the dictionary where the value is an empty list. Example: { "jill" : [] }
else:
if tmp: nameDict[tmp].append(_) # as long as tmp is not None, append the value to it. For example, after we hit "jill", it will append 8 then 1 then 0.
final = [] # empty list to print out
for name in nameDict: # loop through the keys in nameDict
final += [name] + sorted(nameDict[name], reverse=True) # append the name to the final list as well as the sorted (descending) list in the dictionary
print final
If you need the names in their correct order, that might be a bit different because dicts are unsorted.