Why is the condition performed when it shouldn't be? - python

I have a sequence of characters that I want to insert into a 2D table. But, despite the if condition : when I reach a character '*', it goes into the if condition, whereas it should go directly into the else.
if str(tab_2D[q + 5][1]) != '*':
print("IN")
if table_transition[int(etat1) + 1][ord(symbole) - ord('a') + 2] == " ":
table_transition[int(etat1) + 1][ord(symbole) - ord('a') + 2] = etat2
else:
table_transition[int(etat1) + 1][ord(symbole) - ord('a') + 2] += ',' + etat2
else: # si le symbole EST epsilon
if table_transition[int(etat1) + 1][int(symbol) + 2] == " ":
table_transition[int(etat1) + 1][int(symbol) + 2] = etat2
else:
table_transition[int(etat1) + 1][int(symbol) + 2] += ',' + etat2
q += 1
Here's the proof that ' * ' does go into the if condition because "IN" is displayed once when it's really a ' * ' character that is being compared. It should not be displayed.
Here's proof:
Do you know why?

I solved the problem, I had forgotten to add q += 1 before the main else

Related

How can i paint over text instead of printing multiple times?

How can I make the program print the CTRL+C to go BACK once down?[Look pictures][Picture][1]
while h < math.inf:
time2 = time.strftime("[%H" + ":%M" + ":%S]")
console = colorama.Fore.WHITE + time2 + '' + defaultname
file = open("Accounts/Failed.txt", "a+")
file2 = open("Accounts/Success.txt", "a+")
x = random.randrange(0, 100)
f = generator()
if x <= 97:
print(console + colorama.Fore.RED + "[FAILED] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file.write(str(j) + ":0x" + f + "\n")
time.sleep(0.15)
j += 1
file.close()
elif x >= 97:
print(console + colorama.Fore.GREEN + "[SUCCESS] " + "0x" + f + ' ETH Wallet' + colorama.Fore.WHITE + ' CTRL+C to go BACK')
file2.write(str(h) + ":0x" + f + "\n")
time.sleep(0.15)
h += 1
file2.close()```
[1]: https://i.stack.imgur.com/Qa7Bw.png
So to print CTRL+C to go BACK only on the last loop iteration, you have too check if h + 1 is going to break the loop condition. To do so, you could check the condition h + 1 >= math.inf.
if h + 1 >= math.inf:
print("CTRL+C to go BACK")
This way you'll have to remove the CTRL+C to go BACK in your infos print functions

Is there a way to solve this TypeError [duplicate]

This question already has answers here:
Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?
(4 answers)
Closed 6 months ago.
I am having trouble figuring out what is wrong with my code. I need help.
next(fhr) # skip header row
customer_list = [] # initialize empty customer list
for line in fhr:
ls = line.split(',')
customer_list.append([ls[0], ls[1], ls[2], ls[3], ls[4], ls[5], ls[6], int(ls[7]), ls[8], ls[9], ls[10].strip('\n')])
from operator import itemgetter
customer_list.sort(key=itemgetter(7), reverse=True)
print(customer_list)
writepath = './loan-data-output-v1.csv'
fwh = open(writepath, 'w', encoding='utf-8')
fwh.write('Name' +','+ 'State' +','+'Age' +','+'Annual Income'+','+ 'Loan Type' +','+' Loan Amount' +','+ 'Length of Loan in Years' +','+ 'Days Delinquent' +','+ 'Interest Rate' +','+ 'Number of Loans Prior' +','+'Years as Customer' + '\n')
for i in customer_list:
if customer_list[i][7] >= 90:
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + customer_list[i][7] + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
I am getting this error for the last for loop and I'm not sure what to do about it. Can someone help.
TypeError: list indices must be integers or slices, not list
You are using lists of lists so when you use for i in list_of_list, i itself becomes a list..
for i in customer_list:
if i[7] >= '90':
fwh.write(i[0] + ',' + i[1] + ',' + i[2] + ',' + i[3] + ',' + i[4] + ',' + i[5] + ',' + i[6] + ',' + str(i[7]) + ',' + i[8] + ',' + i[9] + ','+ i[10] + '\n')
fhr.close()
fwh.close()
Alternatively you can use,
for i in range(0,len(customer_list)):
if customer_list[i][7] >= '90':
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + str(customer_list[i][7]) + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
EDIT: Second method assumes that your length of customer_list is constant or in other words you are not adding anything to customer_list during the loop. Thanks to DanielRoseman for pointing out potential bug in second code..
EDIT 2:
Thanks to quamrana for suggesting this way,
for i in customer_list:
if i[7] >= '90':
i[7] = str(i[7])
fwh.write(','.join(i[0:11]) + '\n')
fhr.close()
fwh.close()

Python : Calculate values and send in email

UPDATE : I have corrected my code and below is working fine as expected
Basically i need an output like below in mail.
I achieved this. but need to know if any efficient code then below one.
name 5001 5010 9000 4 %
name 5002 5010 9000 4 %
name 5003 5010 9000 4 %
name 5004 5010 9000 4 %
Storing the values in list.
Below are dummy values
container = []
for server in range(1,5):
container.append('name')
container.append(server + 5000)
container.append(5000+10)
container.append(4000+5000)
container.append(2500 % 12)
print('\n' + str(container))
Assign list of values to msgBody in order to send it via email
I'm just putting piece of code here. Below also working fine
msgBody1 = ''
for count in range(4):
if count == 0:
tempValue = '\n' + '\n' + str(container[count]) + '\t' + str(container[count+1]) + '\t' + str(container[count+2]) + '\t'
+ str(container[count+3]) + '\t' + str(container[count+4])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 1:
tempValue = '\n' + '\n' + str(container[count+4]) + '\t' + str(container[count+5]) + '\t' + str(container[count+6]) + '\t'
+ str(container[count+7]) + '\t' + str(container[count+8])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 2:
tempValue = '\n' + '\n' + str(container[count+8]) + '\t' + str(container[count+9]) + '\t' + str(container[count+10]) + '\t'
+ str(container[count+11]) + '\t' + str(container[count+12])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 3:
tempValue = '\n' + '\n' + str(container[count+12]) + '\t' + str(container[count+13]) + '\t' + str(container[count+14]) + '\t'
+ str(container[count+15]) + '\t' + str(container[count+16])
msgBody1 = msgBody1 + str(tempValue) + ' %'
Any other better and short code to replace msgBody1
Thanks in advance
Your question is not clear; the code example does not make any sense. But from the structure of it, it seems like you are trying to use dict, but you are defining or sourcing lists.
Not sure why for server in servers, I hope your servers list is collection of numerical value, which does not make any sense.
Please go through list Vs dict, and list.append() and how to add new key, value pairs to dictionary.

Python string wrong characters

let me start by saying that I attempted to create a minimal example but was unable to replicate the results. I try to not make it a habbit to dump all my code on here but I am not sure of another way to illustrate the issue. I am writing a class to output data from my application to a specific format and I am getting the wrong results in the code.
The format I am attempting to output should look like this:
Nodestyle "nodeType" "name"
"attribute-type attribute-name" [value]
If the attribute is linked to another node
"refrence attribute-type attribute-name" ["nodename:output-attribute-name"]
Example:
Bxdf "PxrDisney" "7fcfd465-87c3-4092-98b9-b67d1655bc32"
"color baseColor" [0.20.50.8]
"color emitColor" [0.00.00.0]
"float subsurface" [0]
"reference color subsurfaceColor" ["a3bb37f2-dbb8-407b8a1ac93822ebef7c:resultRGB"]
"float metallic" [0]
"float specular" [.5]
"float specularTint" [0]
"float roughness" [.25]
"float anisotropic" [0]
"float sheen" [0]
"float sheenTint" [.5]
"float clearcoat" [0]
"float clearcoatGloss" [1]
"float presence" [1]
"int inputAOV" [0]
Pattern "PxrHSL" "a3bb37f2-dbb8-407b-8a1a-c93822ebef7c"
"color inputRGB" [0.00.00.0]
"float hue" [0.0]
"float saturation" [1.0]
"float luminance" [1.0]
The results I am getting look like this:
('Bxdf "PxrDisney" "7fcfd465-87c3-4092-98b9-b67d1655bc32" \n "color baseColor" [0.20.50.8] \n "color emitColor" [0.00.00.0] \n "float subsurface" [0] \n "reference color subsurfaceColor"', '["a3bb37f2-dbb8-407b-8a1a-c93822ebef7c:resultRGB"] \n ')"float metallic" [0]
"float specular" [.5]
"float specularTint" [0]
"float roughness" [.25]
"float anisotropic" [0]
"float sheen" [0]
"float sheenTint" [.5]
"float clearcoat" [0]
"float clearcoatGloss" [1]
"float presence" [1]
"int inputAOV" [0]
Pattern "PxrHSL" "a3bb37f2-dbb8-407b-8a1a-c93822ebef7c"
"color inputRGB" [0.00.00.0]
"float hue" [0.0]
"float saturation" [1.0]
"float luminance" [1.0]
It looks like it if outputting special characters and extra items in the string up to where there is a reference to another node. if I link to another attribute lets say basecolor it will only give the wrong results up to basecolor. If there is no connections at all there is no issue. Why would a string give this behaviour? Here is the class in question. The class take an array of node objects I step through.
#This will handel the export of the RIB contaning all the shader calls
class exporter ():
nodes = None
dicNodes = {}
outStream = []
#Method Two: Use shader as a starting point
#Find the shader
#go through each attribute on the shader
#if connected check attrs on connected node
def __init__(self, incomenodes):
self.nodes = incomenodes
dicNodes = {}
outStream = []
#create a dic using nids as keys
for node in self.nodes:
self.dicNodes[str(node.nid)] = node
#Run Export Command for each shader
x = 0
for node in self.nodes:
print str(node.nodeType.nType)
if str(node.nodeType.nType) == 'bxdf':
self.streamMe(node)
target = open('/home/jspada20/outStream.RIB', 'w')
print 'JAMES! There are ', len(self.outStream), 'items in the out stream'
for line in self.outStream:
target.write(line)
print line
target.close()
def streamMe(self, node):
#Layout for the header of a node call is....
#Pattern "PxrThinFilm" "PxrThinFilm1"
#Bxdf "PxrDisney" "PxrDisney1"
#{Type} "{Identifyer}" "{Name/UID}"
moreNodes = []
#need to fix lower case letters comming in from XML source
nodefunction = None
if str(node.nodeType.nType[0]) == 'p':
nodefunction = 'Pattern'
elif str(node.nodeType.nType[0]) == 'b':
nodefunction = "Bxdf"
else:
nodefunction = str(node.nodeType.nType)
self.outStream.append(nodefunction + ' "' + str(node.nodeType.nName) + '" ' + '"' + str(node.nid) + '" \n ')
for attr in node.inputs:
#Check to see if it is connected
#if not connected:
if attr.currentConnectedNode is None:
#Check to see what type the value is. This will govern the export scheme
if str(attr.argType) == "int":
#print '"'+ str(attr.argType), attr.name + '" [' + str(attr.value) + ']'
self.outStream[len(self.outStream) - 1] = self.outStream[len(self.outStream) - 1] + '"' + str(attr.argType) + " " + attr.name + '" [' + str(attr.value) + '] \n '
elif str(attr.argType) == "float":
if str(attr.value[len(str(attr.value))-1]) == '.':
outVal = str(attr.value) + '0'
else:
outVal = str(attr.value)
#print '"'+ str(attr.argType), attr.name + '" [' + outVal + ']'
self.outStream[len(self.outStream) - 1] = str(self.outStream[len(self.outStream) - 1]) + '"' + str(attr.argType) + " " + attr.name + '" [' + str(attr.value) + '] \n '
elif str(attr.argType) == "color":
#print '"'+ str(attr.argType), attr.name + '" [' + str(attr.value.r), str(attr.value.g), str(attr.value.b) + ']'
self.outStream[len(self.outStream) - 1] = str(self.outStream[len(self.outStream) - 1]) + '"' + str(attr.argType) + " " + attr.name + '" [' + str(attr.value.r) + str(attr.value.g) + str(attr.value.b) + '] \n '
elif str(attr.argType) == "string":
#print '"'+ str(attr.argType), attr.name + '" ["' + attr.value + '"]'
self.outStream[len(self.outStream) - 1] = str(self.outStream[len(self.outStream) - 1]) + '"' + str(attr.argType) + " " + attr.name + '" [' + str(attr.value) + '] \n '
else:
self.outStream[len(self.outStream) - 1] = str(self.outStream[len(self.outStream) - 1]) + '"reference ' + str(attr.argType) + " " + attr.name + '"', '["' + str(attr.currentConnectedNode.nid) + ':' + attr.currentConnectedOutput.name + '"] \n '
moreNodes.append(str(attr.currentConnectedNode.nid))
for ids in moreNodes:
self.streamMe(self.dicNodes[ids])
When I was converting this code from print statements to storing the information in a list, I missed a comma. Tuples can be declared like this:
myTuple = "1", "2", "3"
By having a comma in the statement I was converting the string.
Changing the comma to a + in this statement resolved the issue. Coming from c++ I was not used to mutable data types!
self.outStream[len(self.outStream) - 1] = str(self.outStream[len(self.outStream) - 1]) + '"reference ' + str(attr.argType) + " " + attr.name + '"' '["' + str(attr.currentConnectedNode.nid) + ':' + attr.currentConnectedOutput.name + '"] \n '

how to calculate 24?

I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
def calc(oprands, result) :
ret=[]
if len(oprands)==1 :
if oprands[0]!=result :
return ret
else :
ret.append(str(oprands[0]))
return ret
for idx, x in enumerate(oprands) :
if x in oprands[0:idx] :
continue
remaining=oprands[0:idx]+oprands[idx+1:]
temp = calc(remaining, result-x) # try addition
for s in temp :
ret.append(str(x) + ' + ' + s)
if(result%x == 0) : # try multiplication
temp = calc(remaining, result/x)
for s in temp :
ret.append(str(x) + ' * (' + s + ')')
temp = calc(remaining, result+x) # try subtraction
for s in temp :
ret.append(s + ' - ' + str(x))
temp = calc(remaining, x-result)
for s in temp :
ret.append(str(x) + ' - (' + s + ')')
temp = calc(remaining, result*x) # try division
for s in temp :
ret.append('(' + s + ') / ' + str(x))
if result!=0 and x%result==0 and x/result!=0 :
temp = calc(remaining, x/result)
for s in temp :
ret.append(str(x) + ' / ' + '(' +s +')')
return ret
if __name__ == '__main__' :
nums = raw_input("Please input numbers seperated by space: ")
rslt = int(raw_input("Please input result: "))
oprds = map(int, nums.split(' '))
rr = calc(oprds, rslt)
for s in rr :
print s
print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.

Categories

Resources