Errors When Formatting Code In Python - python

I know this is probably quite a simple problem but I am having an issue with the formatting of my function. I am getting a lot of 'unexpected indent' and also 'unexpected token'. I keep trying to format the function correctly but I have no idea why these errors keep on appearing. Here is my function:
def stringCheck(stringForCheck, letterOrNumber):
valid = True
x = 0
a = int(ord(stringForCheck)
length = len(stringForCheck)
if LetterOrNumber == 'Letter':
lowerBoundary = 65
upperBoundary = 90
elif LetterOrNumber == 'Number':
lowerBoundary = 48
upperBoundary = 57
while valid == True and x < length:
if a < lowerBoundary or a > upperBoundary:
valid = False
else:
valid = True
x = x + 1
stringCheck = valid
stringCheck('2','Number')

Remove the unnecessary blank lines
You are missing a closing bracket here: a = int(ord(stringForCheck)
From the line if LetterOrNumber == 'Letter': to your while loop the lines have one indentation level too much.
After fixing the code it should look something like this:
def stringCheck(stringForCheck, letterOrNumber):
valid = True
x = 0
a = int(ord(stringForCheck))
length = len(stringForCheck)
if LetterOrNumber == 'Letter':
lowerBoundary = 65
upperBoundary = 90
elif LetterOrNumber == 'Number':
lowerBoundary = 48
upperBoundary = 57
while valid is True and x < length:
if a < lowerBoundary or a > upperBoundary:
valid = False
else:
valid = True
x = x + 1
stringCheck = valid
stringCheck('2', 'Number')

Try adding a close bracket after the line
a = int(ord(stringForCheck))

Related

Inserting a newline every 40 characters isn't working (but no errors)

I'm trying to insert a newline every 40 characters. I'm very new to Python so I apologize if my code is messed up.
def wrap(msg):
pos = 0
end = msg
for i in end:
pos += 1
if pos % 40 == 0:
print(pos)
end = end[:pos] + "\n" + end[:pos + 2]
return end
This code doesn't work and there isn't any errors. I'm not sure why this happens. It seems to just return the full string??
def wrap(msg):
res = ''
t = len(msg)//40
for i in range(t):
start = i*40
end = (i+1)*40
res += msg[start:end]+'\n'
res += msg[t*40:(t+1)*40]
return res

How to find runtime error bug on python program

so i try to solve https://open.kattis.com/problems/10kindsofpeople with my python code, i think the code is good and passed 22/25 test case, but there is a runtime error in testcase 23.
the code is here:
if __name__ == "__main__":
def walk(arr,r1,c1,r2,c2,rows,cols, history):
history['{0},{1}'.format(r1,c1)] = True
# print('{},{}-{},{}'.format(r1,c1,r2,c2))
if arr[r1][c1] == arr[r2][c2]:
if r1 == r2 and c1 == c2:
return True
if r1-1 >= 0 and '{0},{1}'.format(r1-1, c1) not in history:
atas = walk(arr, r1-1,c1,r2,c2,rows,cols,history)
else:
atas=False
if r1+1 < rows and '{0},{1}'.format(r1+1, c1) not in history:
bawah = walk(arr,r1+1,c1,r2,c2,rows,cols,history)
else:
bawah=False
if c1-1 >= 0 and '{0},{1}'.format(r1, c1-1) not in history:
kiri = walk(arr,r1,c1-1,r2,c2,rows,cols,history)
else:
kiri=False
if c1+1 < cols and '{0},{1}'.format(r1, c1+1) not in history:
kanan = walk(arr,r1,c1+1,r2,c2,rows,cols,history)
else:
kanan = False
# if one of them == true , there is a path to destination
if atas or bawah or kiri or kanan:
return True
else:
return False
else:
return False
map = input()
rows, cols = map.split(" ")
rows = int(rows)
cols = int(cols)
arr_row = []
for i in range(int(rows)):
str_inp = input()
list_int = [int(i) for i in str_inp]
arr_row.append(list_int)
coord_row=input()
coord_pair=[]
for i in range(int(coord_row)):
r1,c1,r2,c2 = input().split(" ")
coord_pair.append([r1,c1,r2,c2])
# print(arr_row)
for c in coord_pair:
r1 = int(c[0]) - 1
c1 = int(c[1]) - 1
r2 = int(c[2]) - 1
c2 = int(c[3]) - 1
history = {}
if arr_row[r1][c1] != arr_row[r2][c2]:
print("neither")
elif walk(arr_row, r1, c1, r2, c2, rows, cols, history):
ret = 'binary' if arr_row[r1][c1] == 0 else 'decimal'
print(ret)
else:
print('neither')
i think there is an error in input with the hidden test case, i would appreciate if anyone can find the bugs, thank you

adding and iterating through linked list backwards to produce backwards sum

I am trying to add two linked lists backward such that they produce a third. I am running into an issue in which I am missing the middle value in my expected out output. I don't understand why this is happening.
Example: 342 + 465 = 807(expected output)
input =
[2]->[4]->[3],
[5]->[6]->[4]
expected = [7]->[0]->[8]
actual = [7]->[8]
carryOver = 0
current1 = l1
current2 = l2
result = None
resultC = None
while current1 is not None:
val = current1.val + current2.val+ carryOver
if val>= 10:
carryOver = val//10
else:
carryOver = 0
val = val%10
if result == None:
result = ListNode(val)
resultC = result
else:
resultC.next = ListNode(val)
current1 = current1.next
current2 = current2.next
if carryOver != 0:
resultC.next = ListNode(carryOver)
return result
This might be what you are looking for.
def add_list(l1,l2):
max_length=max(len(l1),len(l2))
l1,l2=[[0]]*(max_length-len(l1))+l1,[[0]]*(max_length-len(l2))+l2 # padding zeros
l1,l2=l1[::-1],l2[::-1]#temporary reversing of list
carry=0
d=[]
for x in zip(l1,l2):
tempsum=x[0][0]+x[1][0]+carry
carry=0
if tempsum>9:
carry,tempsum=tempsum//10,tempsum%10
d.append([tempsum])
if carry !=0:
d.append([carry])
return d[::-1]

How to find byte sequence in file?

I have a binary file, in which I need to change certain bit.
That bit's byte's address is relative to some byte sequence (some ASCII string):
content = array('B')
with open(filename, mode="r+b") as file:
content.fromfile(file, os.fstat(file.fileno()).st_size)
abc = [ord(letter) for letter in "ABC"]
i = content.index(abc) // ValueError: array.index(x): x not in list
content[i + 0x16] |= 1
content.tofile(file)
However as I must confess to my shame, that after Googling far and wide, I couldn't find the method to get the index of that "ABC" string...
Sure, I can write a function that does it with loops, but I can't believe there is no one-liner (OK, even two...) that accomplishes it.
How can it be done?
Not sure if this is the most Pythonic way, but this works. In this file
$ cat so.bin
���ABC̻�X��w
$ hexdump so.bin
0000000 eeff 41dd 4342 bbcc 58aa 8899 0a77
000000e
Edit: New solution starts here.
import string
char_ints = [ord(c) for c in string.ascii_letters]
with open("so.out.bin", "wb") as fo:
with open("so.bin", "rb") as fi:
# Read bytes but only keep letters.
chars = []
for b in fi.read():
if b in char_ints:
chars.append(chr(b))
else:
chars.append(" ")
# Search for 'ABC' in the read letters.
pos = "".join(chars).index("ABC")
# We now know the position of the intersting byte.
pos_x = pos + len("ABC") + 3 # known offset
# Now copy all bytes from the input to the output, ...
fi.seek(0)
i = 0
for b in fi.read():
# ... but replace the intersting byte.
if i == pos_x:
fo.write(b"Y")
else:
fo.write(bytes([b]))
i = i + 1
Edit: New solution ends here.
I want to get the X four positions after ABC. A little state keeping locates the position of ABC, skips the offset, prints the interesting bytes.
foundA = False
foundB = False
foundC = False
found = False
offsetAfterC = 3
lengthAfterC = 1
with open("so.bin", "rb") as f:
pos = 0
for b in f.read():
pos = pos + 1
if not found:
if b == 0x41:
foundA = True
elif foundA and b == 0x42:
foundB = True
elif foundA and foundB and b == 0x43:
foundC = True
else:
foundA, foundB, foundC = False, False, False
if foundA and foundB and foundC:
found = True
break
f.seek(0)
i = 0
while i < pos + offsetAfterC:
b = f.read(1)
i = i + 1
while i < pos + offsetAfterC + lengthAfterC:
b = f.read(1)
print(hex(int.from_bytes(b, byteorder="big")))
i = i + 1
Output:
0x58

how to resolve the Memory Error

This is for my python code
enter code herefileName = open(flename,"r")
dccount = 0
dcCycles = []
ccCycles = []
temp=0
ccCY = []
dcCY = []
for line in fileName:
length = len(line)
for i in range(length):
if i >=4:
x = line[i-1]
y = line[i]
bcValue = x+y
if bcValue == "IV":
ivval = float(int(line[i+2:i+7]))
if ivval > 0:
if temp == 1:
dcCY.append(dcCycles)
dcCycles=[]
cc = line[dccount:i-5]
ccCycles.append(cc)
dccount = i
temp =0
else:
cc = line[dccount:i-5]
ccCycles.append(cc)
else:
if temp == 0:
ccCY.append(ccCycles)
ccCycles=[]
dc = line[dccount:i-6]
dcCycles.append(dc)
dccount = i
temp = 1
else:
dc = line[dccount:i-6]
dcCycles.append(dc)
fileName.close()
in memory error got in cc = line[dccount:i-5] this ling how to resolve please help me
It looks like dccount was not yet defined at that point. You should have gotten a NameError

Categories

Resources