How to set variable value to be a new row python - python

My code:
test_str = '''
(()(code)())
((t(e(x(t(()
()(co)de)('''
countofrightbrackets = 0
countofleftbrackets = 0
blockcount = 0
myDict = {};
for i in test_str:
if i == '(':
countofrightbrackets = countofrightbrackets + 1
if i == ')':
countofleftbrackets = countofleftbrackets + 1
if i == '':
blockcount = blockcount + 1
if countofrightbrackets == countofleftbrackets:
myDict.update({blockcount:'True'});
else:
myDict.update({blockcount:'False'});
print (myDict)
My program is counting () and if count of ( = ) then save to dictionary True. Else false. In test_str I have some blocks - they are dissociated with 2 new rows. In if i == '': I want to show, that if I = 2 new rows, then compete the code. Also I need to check are brackets are at correct positions - like ()()() is true and ())( is false. How to do this?
Example:
Input:
(()()())
((((((()
()())(
Output:
1: True 2: False 3: False

Related

Finding a 'hello' word in a different string, which it has 'hello' in it(additional)

Finding a 'hello' word in a different string, which it has 'hello' in it
I should find a 'hello' word in a string, which I gave it from input too .I wrote this code by looking at the answer that someone gave to the below link's question.
firststring = input() #ahhellllloou
to_find = "hello"
def check_string(firststring, to_find):
c = 0
for i in firststring:
#print(i)
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(firststring, to_find))
but I don't want to use a def to solve the problem.
hello = "hello"
counter_hello = 0
bool_hello = False
for letter in string:
if letter == hello[counter_hello]:
counter_hello += 1
if counter_hello == len(hello):
bool_hello = True
if bool_hello == True:
print("YES")
else:
print("NO")
for hello string it works correct. also for pnnepelqomhhheollvlo.
but when I give it ahhellllloou it doesn't work.
I can't see where the bug is.
Your code is not the same. The return statement needs to be accounted for by breaking the loop
string = "ahhellllloou"
to_find = "hello"
match = False
c = 0
for i in string:
if i == to_find[c]:
c += 1
if c == len(to_find):
match = True
break
print("YES" if match else "NO")
Note that a loop isn't needed
>>> import re
>>> m = re.search('.*'.join('hello'), 'ahhellllloou')
>>> m is not None
True
>>> m = re.search('.*'.join('hello'), 'ahhellllliu')
>>> m is None
True
counter_hello = 0
bool_hello = False
for letter in 'ahhellllloou':
#print('letter: ', letter);
#print(hello[counter_hello])
if letter == hello[counter_hello] and counter_hello != len(hello) - 1:
counter_hello += 1
if counter_hello == len(hello) - 1:
bool_hello = True
if bool_hello == True:
print("YES")
else:
print("NO")

Annotating adjacent values in a list

It's supposed to be a roll of dice (random) then adjacent values (runs) are supposed to be in ( ). One challenge is using the current - 1 with the 0 index (think I got that resolved by using range(len(dieRun) -1). But another challenge is using 'current + 1' as it tends to 'out of range' errors.
One thought I have is to maybe build a function to compare the values for adjacents? Then use whatever return I get from that to reference a variable, then use that variable in a formatted Print of the dieRun? But, I don't see how that would be better as then I'd still have to figure out how to place that variable as a "(" or ")" with the print(dieRun) list.
Still a newb.
def main():
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun) # just to see what I'm working with
while counter < len(dieRun):
for i in range(0, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")" , end= "")
inRun = False
counter = counter + 1
if dieRun[i] == dieRun[i+1]:
inRun = True
print("(")
counter = counter + 1
print(dieRun[i])
if inRun:
print("(")
if inRun :
print(")", end="")
main()
if you want the output like: 1(3 3) 4 5 (6 6 6) 2 1 3 (2 2) 1 (4 4) 5 6 1 2
from random import randint
dieRun = []
for i in range(20):
roll = randint(0,6)
dieRun.append(roll)
inRun = False
print(dieRun)
for i, n in enumerate(dieRun):
if i < len(dieRun)-1:
if not inRun:
if n == dieRun[i+1]:
print('(', n,' ', end='')
inRun = True
else:
print(n,' ', end='')
else:
if n != dieRun[i+1]:
print(n, ')',' ', end='')
inRun = False
else:
print(n,' ', end='')
else:
if dieRun[i-1] == n:
print(n, ')')
else:
print(n)
just a thought, hope it help.
Just a quick fix, I have commented in the code.
For the inline print, you have provided the solution 'print(")" , end= "")', but I don't know why you didn't make it for every print().
if dieRun[i] != dieRun[i-1]: # will check the first number with last number
dieRun[0] != dieRun[-1]: # [-1] is the last item in the list
if dieRun[i] == dieRun[i+1]: # will index out of length
dieRun[len(..)-1] != dieRun[len(..)]: # [len(..)] wil be out of range
Since the head and tail of the list will always cause problem, I just chopped them off from the for loop, and do it manually.
There must be some cleaner solution:
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun)
# while counter < len(dieRun): # while loop is redundant with the for loop
print('(', dieRun[0],' ', end='') # print the first number manually
for i in range(1, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")(" , end= "") # change ")" to ")("
inRun = False
counter = counter + 1
"""
these are redundant, just like if True, don't need elif not True
# if dieRun[i] == dieRun[i+1]:
# inRun == True
# print("(", end='')
# counter = counter + 1
"""
print(dieRun[i],' ', end='')
print(dieRun[-1],')', end='') # print the last number manually

Debugging a function that tries to merge two strings but sometimes does not return

The function is supposed to return True if the parameter s can be formed solely from the parameters part1 and part2, and returns False otherwise. My function works when it is supposed to return True, but when False, it doesn't return anything at all.
def is_merge(s, part1, part2):
list = []
v1 = 0
v2 = 0
i = 0
while i < len(s):
if v1 < len(part1) and s[i] == part1[v1] :
list.append(s[i])
i += 1
v1 += 1
elif v2 < len(part2) and s[i] == part2[v2] :
list.append(s[i])
i += 1
v2 += 1
list = ''.join(list)
if list == s:
return True
else:
return False
right = (is_merge('codewars', 'cdw', 'oears'))
wrong = (is_merge('codewarse', 'cdw', 'oears'))
if right == True:
print("true")
if wrong == False:
print("false")

How could I write this function the pythonic way? [duplicate]

I have a string like '....(((...((...' for which I have to generate another string 'ss(4)h5(3)ss(3)h2(2)ss(3)'.
'.' corresponds to 'ss' and the number of continous '.' is in the bracket.
'(' corresponds to 'h5' and the number of continuos '(' is in the bracket.
Currently I'm able to get the output 'ss(4)h5(3)ss(3)' and my code ignores the last two character sequences.
This is what I have done so far
def main():
stringInput = raw_input("Enter the string:")
ssCount = 0
h5Count = 0
finalString = ""
ssString = ""
h5String = ""
ssCont = True
h5Cont = True
for i in range(0, len(stringInput), 1):
if stringInput[i] == ".":
h5Cont = False
if ssCont:
ssCount = ssCount + 1
ssString = "ss(" + str(ssCount) + ")"
ssCont = True
else:
finalString = finalString + ssString
ssCont = True
ssCount = 1
elif stringInput[i] == "(":
ssCont = False
if h5Cont:
h5Count = h5Count + 1
h5String = "h5(" + str(h5Count) + ")"
h5Cont = True
else:
finalString = finalString + h5String
h5Cont = True
h5Count = 1
print finalString
main()
How to modify the code to get the desired output?
I don’t know about modifying your existing code, but to me this can be done very succinctly and pythonically using itertools.groupby. Note that I’m not sure if the 'h2' in your expected output is a typo or if it should be 'h5', which I’m assuming.
from itertools import chain, groupby
string = '....(((...((...'
def character_count(S, labels): # this allows you to customize the labels you want to use
for K, G in groupby(S):
yield labels[K], '(', str(sum(1 for c in G)), ')' # sum() counts the number of items in the iterator G
output = ''.join(chain.from_iterable(character_count(string, {'.': 'ss', '(': 'h5'}))) # joins the components into a single string
print(output)
# >>> ss(4)h5(3)ss(3)h5(2)ss(3)
#Kelvin 's answer is great, however if you want to define a function yourself, you could do it like this:
def h5ss(x):
names = {".": "ss", "(": "h5"}
count = 0
current = None
out = ""
for i in x:
if i == current:
count += 1
else:
if current is not None:
out += "{}({})".format(names[current], count)
count = 1
current = i
if current is not None:
out += "{}({})".format(names[current], count)
return out

Binary Subtraction - Python

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]

Categories

Resources