why Lists in a class were changed without my operate? - python-3.x

i run a class in a for cycle.
the code is:
graph_all = []
graph_now = graph_exc(-1)
for lin in res_str:
if lin.strip():
print(lin)
if lin[0] == 't' :
if graph_now.numbering != (-1) :
graph_all.append(graph_now)
graph_now = graph_exc(int(lin[4:-1]))
if lin[0] == 'v' :
graph_now.add_vertex(lin[2],lin[4])
if lin[0] == 'e' :
graph_now.add_edges(lin[2],lin[4],lin[6])
else:
continue
res_str is a list full of sentences.
I use graph_all to accommdate all the class.
when the first letter is 'v' or 'e',i put something in graph_now's lists.
when the first letter is 't',i put graph_now to graph_all and re-define the graph_all.but i find a problem:when i define graph_all again,the lists in class in graph_all will be nothing,too!
the code of graph_exc is :
class graph_exc:
edges_on_1 = []
edges_on_2 = []
edges_on_edges = []
vertex_on = {}
def __init__(self,numbering):
self.num_edge = 0
self.num_vertex = 0
self.numbering = numbering
self.edges_on_edges.clear()
self.edges_on_2.clear()
self.edges_on_1.clear()
self.vertex_on.clear()
def add_vertex(self,ver,ver_num):
self.vertex_on[ver] = ver_num
self.num_vertex += 1
def add_edges(self,point_1,edges,point_2):
self.edges_on_1.append(point_1)
self.edges_on_edges.append(edges)
self.edges_on_2.append(point_2)
self.num_edge += 1
the problem is : edges_on_1,edges_on_edges,edges_on_2 and vertex will be influenced.the data in here will disappear.but the num_edge and num_vertex are not.
I try to use deepcopy method to solve it.but it does not work.

Related

Unable to Iterate Integer in list using selenium python

I am trying to build a code which automatically fill the text field in textbox,These codes are working as string in list but cant able to iterate integer .
I have tried to do many steps but this is not working ,however code is working in python .
elem = browser.find_element_by_name("pwd")
elem.send_keys("oyo#1234")
time.sleep(2)
elem = browser.find_element_by_name('Submit').click()
elem = browser.find_element_by_name('login_existing_agent').click()
time.sleep(2)
browser.find_element_by_xpath("/html/body/table/tbody/tr/td[2]/div/img").click()
#browser.find_element_by_xpath("/html/body/div[4]/table/tbody/tr/td[1]/table/tbody/tr[2]/td/ul[2]/li[3]/a").click()
time.sleep(1)
browser.find_element_by_xpath("/html/body/div[4]/table/tbody/tr/td[1]/table/tbody/tr[2]/td/ul[2]/li[3]/a").click()
agent_id = [4600000 ,4600001 , 4600002]
a = len(agent_id)
agent_name = [ "saurav" ,"nishant", "vikash"]
b = len(agent_name)
sip_pass = ["Oyo4600000" ,"Oyo4600001" , "Oyo4600002"]
c = len(sip_pass)
i = 0
j =0
k =0
while ( i< a and j<b and k<c ) :
elem = browser.find_element_by_name('agent_add_ui').click()
elem = browser.find_element_by_name('agent_secret')
elem.send_keys("123456")
dropdown = browser.find_element_by_xpath("//*[#id='campaign_id']")
select =Select(dropdown)
select.select_by_visible_text('GOOGLE')
elem = browser.find_element_by_name('agent_id')
elem.send_keys(agent_id[i])
elem = browser.find_element_by_name('agent_name')
elem.send_keys(agent_name[j])
elem = browser.find_element_by_name('sip_pass')
elem.send_keys(sip_pass[k])
elem = browser.find_element_by_name('add_agent').click()
i += 1
j += 1
k += 1
browser.close()
You'll have to first convert each item in your list of integers, into a string, before specifying the item via its index within 'send_keys', not to worry, str() will do the trick :)
elem.send_keys(str(agent_id[i]))

Groovy : Can I use assert in conjuction with elvis operator?

I would like to increment the values based on assert results :
def a = 1
def b = 1
def c = 0
def d = 0
(assert a==b, "Mismatch") ? (c++) : (d++)
Is it possible?
You misunderstood one important part - assert is not a function and it does not return any value. It is a Groovy's (and Java) keyword (statement) that throws an exception if the expression on the right side evaluates to false, but it does not return any result. However, you can achieve expected result using ternary operator in the way it was designed to use:
def a = 1
def b = 1
def c = 0
def d = 0
a == b ? (c++) : (d++)
println "c = ${c}, d = ${d}"
Output:
c = 1, d = 0
You can read more about using assertions in Groovy's official "Testing Guide, chapter 2.1 Power Assertions".
If you really want to "ignore" the assert and continue, you can catch the exception it throws. E.g.
def a = 1
def b = 1
def c = 0
def d = 0
try {
assert a==b, 'Mismatch'
c++
}
catch (AssertionError e) {
d++
}
println([a,b,c,d])
I'd only use tactics like that, if some foreign code dictates that on me. This is very convoluted code unless you want to abuse the power-assert to generate a nice "warning" log message for you.

Python KeyError on second passing of .format()

I'm using .format() to autogenerate a menu. But I also need to format it as users run more tests to indicate those tests are already done.
Example test dict:
menuDict = {
"1":
{"testDataDict": "testDataDict1",
"testName": "testName1",
"testGroupName":"testGroupName1"},
"2":
{"testDataDict": "testDataDict2",
"testName": "testName2",
"testGroupName":"testGroupName2"
},
"3":
{"testDataDict": "testDataDict3",
"testName": "testName3",
"testGroupName":"testGroupName3"
},
"4":
{"testDataDict": "testDataDict4",
"testName": "testName4",
"testGroupName":"testGroupName3"
}
}
Actual code:
def menuAutoCreate(menuDict):
testGroupDict = {}
for testNum in menuDict.keys():
try:
testGroupDict[menuDict[testNum]["testGroupName"]].append(testNum)
except:
testGroupDict[menuDict[testNum]["testGroupName"]] = [testNum]
#Groups the tests under the group names
from natsort import natsorted as nt
testGroupNamesList = nt(testGroupDict.keys(), key=lambda y: y.lower())
#Naturally sorts group names so they look orderly
textDump = " "
i = 0
while i < len(testGroupNamesList):
howManyLinesEven = 0
evenList = []
howManyLinesOdd = 0
oddList = []
testGroupNameEven = testGroupNamesList[i]
textDump += "|{:44} |".format(testGroupNameEven)
howManyLinesEven = len(testGroupDict[testGroupNameEven])
evenList = nt(testGroupDict[testGroupNameEven], key=lambda y: y.lower())
#If it's an even number, it puts the menu template on the left side of the screen
if i != len(testGroupNamesList)-1:
testGroupNameOdd = testGroupNamesList[i+1]
textDump += "{:45} |".format(testGroupNameOdd) + "\n"
howManyLinesOdd = len(testGroupDict[testGroupNameOdd])
oddList = nt(testGroupDict[testGroupNameOdd], key=lambda y: y.lower())
#If it's odd, on the right side.
if i == len(testGroupNamesList)-1:
textDump += "{:45} |".format("") + "\n"
#Ensures everything is correctly whitespaced
howManyLines = max(howManyLinesEven, howManyLinesOdd)
#Checks how many lines there are, so if a group has less tests, it will have extra whitespaces
for line in range(howManyLines):
if line < howManyLinesEven:
data = {"testNum": evenList[line], "testName": menuDict[evenList[line]]["testName"]}
textDump += "|({d[testNum]}) {d[testName]:40} {{doneTests[{d[testNum]!r}]:^8}} |".format(d=data)
else:
textDump += "|{:44} |".format("")
if line < howManyLinesOdd:
data = {"testNum": oddList[line], "testName": menuDict[oddList[line]]["testName"]}
textDump += "({d[testNum]}) {d[testName]:41} {{doneTests[{d[testNum]!r}]:^8}} |".format(d=data) + "\n"
else:
textDump += "{:45} |".format("") + "\n"
#Automatically creates a menu
i += 2
print(textDump)
print("\n")
Output of this, as expected:
|testGroupName1 |testGroupName2 |
|(1) testName1 {doneTests['1']:^8} |(2) testName2 {doneTests['2']:^8} |
|testGroupName3 | |
|(3) testName3 {doneTests['3']:^8} | |
|(4) testName4 {doneTests['4']:^8} | | |
This last step will be done elsewhere, but put here for demonstration:
doneTests = {}
for testNum in menuDict.keys():
doneTests[testNum] = "(-)"
print(doneTests)
#textDump.format(**doneTests)
#This doesn't work for some reason?
textDump.format(doneTests = doneTests)
#This step will be repeated as the user does more tests, as an indicator of
which tests are completed.
The expected output would be this:
|testGroupName1 |testGroupName2 |
|(1) testName1 (-) |(2) testName2 (-) |
|testGroupName3 | |
|(3) testName3 (-) | |
|(4) testName4 (-) | | |
But here it throws a:
KeyError: "'1'"
If you remove !r from:
{{doneTests[{d[testNum]!r}]:^8}}
It throws a
KeyError: 1
instead.
I tried formatting with !s. Using lists/tuples. Adding and removing brackets. Out of ideas at this point...
Just tried your example.
I used the function sorted() instead of natsorted() and added the line
textDump = ''
to initialize the textDump variable before the line
i = 0
As a result I got no errors and got the expected output.
EDIT
Now I reproduced your error. I removed !r from {{doneTests[{d[testNum]!r}]:^8}} and used integer keys in doneTests variable
doneTests[int(testNum)] = "(-)"
to solve the problem. I guess the origin of the problem is how format() method works.

"deepcopy" issues in Python

I was writing an AI solution to the TJ Wriggler problem and I'm having an issue that's causing my program to hang. I'm not exactly sure what it is since I should have more than enough memory to run the code. Rather, I think I'm changing a reference somewhere that I shouldn't be but I can't seem to figure out the exact place.
I'll run through execution up to the point where the program hangs:
First, the search function:
def BFTS(the_frontier):
index = 0
frontier = [the_frontier]
while(True):
if (not frontier):
return None
leaf = frontier.pop(0)
if (leaf.GoalTest()):
return leaf
index = index + 1
moves_list = leaf.FindMoves(index)
while(len(moves_list) > 0):
frontier.append(moves_list.pop(0))
This calls the FindMoves() function:
def FindMoves(self, current_index):
moves_list = []
for wriggler in self.State.Wrigglers:
for seg in [wriggler.Head(), wriggler.Tail()]:
is_head = {
wriggler.Head() : True,
wriggler.Tail() : False}[seg]
for move in self.State.FindEmptySpaces(seg):
if (move is not None):
moves_list.append(self.Move(wriggler.Index,
is_head, move['x'], move['y'], current_index))
return moves_list
FindEmptySpaces() finds all spaces that can be moved into and returns a list of dictionaries represent Cartesian coordinates. The FindMoves() function then calls the Move() function:
def Move(self, wriggler_id, is_head, new_x, new_y, current_index):
head_or_tail = {True : 0, False : 1}[is_head]
# Find action
new_action = ("%s %s %s %s" % (wriggler_id, head_or_tail, new_x, new_y))
new_node = self.CopyNode()
new_index = current_index
new_node.State.MoveWriggler(wriggler_id, new_y, new_x, is_head)
return Node(new_node.State, new_action, new_index, self.Cost + Node.Step_Cost)
This function calls the CopyNode() function:
def CopyNode(self):
# Create new Spaces List-of-List
new_spaces = DataStructures.CopyListOfLists(self.State.Spaces)
new_state = Board(new_spaces)
# Create new List of Actions
new_action = []
for action in self.Action:
new_action.append(action)
# Create new Node
return Node(new_state, new_action, self.Parent, self.Cost)
The CopyNode() function calls the CopyListOfLists() function:
def CopyListOfLists(the_list_of_list):
new_list = []
for lists in the_list_of_list:
temp_list = []
for items in lists:
temp_list.append(items)
new_list.append(temp_list)
return new_list
As far as I can tell, the program hangs in the function CopyNode() but the strange thing is that it only does this on the second pass through Search_BFTS(). As I say, I probably changed a reference somewhere but I'm not experienced enough in Python to know for sure if this is the actual problem.
Any help that could be offered would be great.
Thanks,

groovy Hashmap - get the value count from a map

my following code
def traineeDetails = session.traineeDetailsForAuto
on printing gives:
traineeDetails = [name:[Hus, Vin], email:[hus#gmail.com, vin#gmail.com], phone:[9908877654, 9987655432], jobTitle:[SE, ST]]
def count = traineeDetails.name.size() gives correct value =2
but when the map key contains one value
def traineeDetails = session.traineeDetailsForAuto
on printing gives:
traineeDetails = [name:Hus, email:hus#gmail.com, phone:9987766543, jobTitle:SE]
def count= traineeDetails.name.size() gives wrong answer 3 which is the total number of character in name
but here i need to get total count of value that the key name holds..
how to do it?
If you're going to mix types in a map, then you're going to need to check the type:
def count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
Using your examples, it works fine:
traineeDetails = [name:['Hus', 'Vin'], email:['hus#gmail.com', 'vin#gmail.com'], phone:['9908877654', '9987655432'], jobTitle:['SE', 'ST']]
count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
assert count == 2
traineeDetails = [name:'Hus', email:'hus#gmail.com', phone:'9987766543', jobTitle:'SE']
count = traineeDetails.name.with { it instanceof Collection ? it.size() : 1 }
assert count == 1
Can you provide actual non-working examples?

Resources