I am trying to write a function to compare the letters in 2 strings.
If the 2 letters are in same position then replace it with '!' and '^' if otherwise.
S1: 'ABACADABRA'
S2: 'ACABADACCD'
This is my code using iterative method:
enter image description here
def Compare_String_I(S1,S2):
difference = ''
if len(S1) == len(S2):
for i in range(0, len(S1)) and range(0,len(S2)):
if S1[i] != S2[i]:
difference += str('^')
else:
difference += str('!')
return difference
I am trying to learn how to write the code recursively, but I am not sure how to do it.
How about this:
def compare_string(S1, S2):
if len(S1) != len(S2):
return
diff = ''
for s1, s2 in zip(S1, S2):
diff += '!' if s1 == s2 else '^'
return diff
print(compare_string('aaa', 'aba')) # !^!
if len(s1) != len(s2):
quit()
else:
i = 0
while i < len(s1):
if s1[i] == s2[i]:
s1 = s1.replace(s1[i], "!")
s2 = s2.replace(s2[i], "^")
i += 1
print(f"{s1}\n{s2}")
Related
I'm trying to make and anagram checker without any built-in functions. So far, I've managed this:
def isa1(s1, s2):
a = s1.lower()
b = s2.lower()
c = list(a)
d = list(b)
l = len(s1)
counter = 0
for i in range(l):
if c[i] == d[0]:
del d[0]
counter += 1
elif c[i] == d[1]:
del d[1]
counter += 1
elif c[i] == d[2]:
del d[2]
counter += 1
elif c[i] == d[3]:
del d[3]
counter += 1
elif c[i] == d[4]:
del d[4]
counter += 1
elif c[i] == d[5]:
del d[5]
counter += 1
else:
pass
if counter == len(s1):
return True
else:
return False
I'm happy with the start, bar the assignment naming, but I cant figure out how to iterate through my second string, s2, without the for-loop being ridiculous. Plus this code will only work for a string/list 6 characters long.
Sorry if this seems simply, I'm just starting Python and programming in general
Thanks!
if you are okay with using for in side of for you can do:
def isa1(s1, s2):
a = s1.lower()
b = s2.lower()
c = list(a)
d = list(b)
l = len(s1)
counter = 0
for i in range(l):
for j in range(len(d)):
if c[i] == d[j]:
del d[j]
counter += 1
break # to continue to the next letter
if counter == len(s1):
return True
else:
return False
this solution will check against each letter in the second list, and if it finds a match it will break the inner loop going to the next letter.
For example if s = "1000000111" and t = "0111000001" the output should be 11. Below is my solution but it gives a time limit exceeded error so I am looking for a faster method. The length of string is less than 10^6.
T = int(input())
for _ in range(0,T):
n = int(input())
s = input()
source = []
for letter in s:
source.append(letter)
#source[0],source[1] = source[1],source[0]
#print(source)
t = input()
target = []
for letter in t:
target.append(letter)
if source.count("1") != target.count("1") or source.count("0") != target.count("0"):
print(-1)
continue
else:
ans = 0
for i in range(0,n):
if source[i] != target[i]:
#print("".join(source),"".join(target))
if source[i] == "0":
j = i
while source[j] != "1":
j += 1
ans += j-i
source[i],source[j] = source[j],source[i]
else:
#print(source)
j = i
while source[j] != "0":
#print(j,ans)
j+=1
ans += j-i
source[i],source[j] = source[j],source[i]
print(ans)
Here's the code. The idea is that you count the location of '1's and then calculate the difference between the pairs. Time complexity O(n), space complexity O(n), but can be done O(1) with a careful indexing.
def foo(str1, str2):
if len(str1) != len(str2):
return -1
n = len(str1)
arr1 = [i for i in range(n) if str1[i] == '1']
arr2 = [i for i in range(n) if str2[i] == '1']
if len(arr1) != len(arr2):
return -1
res = 0
for i in range(len(arr1)):
res += abs(arr1[i] - arr2[i])
return res
I have two strings
e.g.
str1 = "Come"
str2 = "Rome"
I want the program to output ome.
How can I do that?
This is what I tried:
def getString(x):
return x
def solve(s1, s2):
a = getString(s1[0])
b = getString(s2[0])
for i in range(1, len(s1)):
if s1[i] != s1[i - 1]:
a += getString(s1[i])
for i in range(1, len(s2)):
if s2[i] != s2[i - 1]:
b += getString(s2[i])
if a == b:
print(a)
return True
return False
Edit: gave a wrong answer. This answer works but not the most efficent, although simple
for i in range(len(a)):
if b.endswith(a[i:]):
print(a[i:])
return
I want to split my string using python 3+ which is having commas. I don't want string to split based on commas inside brackets.
For example:-
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
I want to split this into two string elements.
I tried splitting based on commas but it is taking inside commas as well.
import re
import csv
from StringIO import StringIO
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
b = re.split(r',(?=")', cstr)
print(b)
c = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', cstr)
print(c)
data = StringIO(cstr)
reader = csv.reader(data, delimiter=';')
for row in reader:
print(row)
def split_with_commas_outside_of_quotes(string):
arr = []
start, flag = 0, False
for pos, x in enumerate(string):
if x == '(' and x == ')':
flag= not(flag)
if flag == False and x == ',':
arr.append(string[start:pos])
start = pos+1
arr.append(string[start:pos])
return arr
print(split_with_commas_outside_of_quotes(cstr))
print(cstr.replace('(','$')).replace(')','#').split(',')
Expected result is splitting of string into two different strings of list that is:-
outputlist - ['animal_tiger','(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))']
remember the length of the list is 2.
Here you go. Use this function:
def split_with_commas_outside_of_quotes(string):
arr = []
bracketCount = 0
currentItem = ""
for i in range(len(string)):
if i == len(string)-1:
currentItem += string[i]
arr.append(currentItem)
elif string[i] == "(":
bracketCount += 1
currentItem += string[i]
elif string[i] == ")":
bracketCount -= 1
currentItem += string[i]
elif bracketCount == 0 and string[i] == ",":
arr.append(currentItem)
currentItem = ""
else:
currentItem += string[i]
return arr
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
print(split_with_commas_outside_of_quotes(cstr))
Output:
['animal_tiger', '(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",)),1,3) AS INT))']
You can use split():
data = """animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))"""
data.split(',', 1)
>>> ['animal_tiger',
'(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",\'\')),1,3) AS INT))']
I am having some issues with this question for which i have tried to make 2 solutions.The first one works partially but the second one does not.Here is the question
Question with which i am having the issue.Has sample input and output
Here are the 2 codes which i have written
number=int(input())
S=input()
w=list(S[:])
w_count=0
other_count=0
v_count=0
vv_count=0
i=0
while(i<(len(w))):
try:
if w[i]=='w':
w_count+=1
elif w[i]=='v' and w[i+1]=='v':
vv_count+=1
i+=1
else:
other_count+=1
except IndexError:
pass
i+=1
max_length=w_count*2+other_count+v_count
min_length=0
min_length=w_count+other_count+vv_count
print(min_length,max_length)
The other Logic has been implemented with the help of a for loop for which 3 test cases are passing
for value in range(len(w)):
try:
if w[value]=='w':
w_count+=1
elif w[value]=='v' and w[value+1]=='v':
vv_count+=1
else:
other_count+=1
except IndexError:
pass
If think you can keep it simple with:
my_string = "avwvb"
max_len = len(my_string.replace("w", "vv"))
min_len = len(my_string.replace("w", "vv").replace("vv", "w"))
print(max_len, min_len)
Or a little faster:
my_string = "avwvb"
max_string = my_string.replace("w", "vv")
min_string = max_string.replace("vv", "w")
max_len = len(max_string)
min_len = len(min_string)
print(max_len, min_len)
You can try this. It's similar to your for loop solution but uses string indexing a bit better.
For the first problem I'm just expanding the string as much as possible changing all ws into 2 vs.
The second is a bit trickier. I first expand the string using the previous method, and then build a new string where any vv combinations can be turned into w. I use 2 indexes, i for the longer string and j for the shorter version of the string, in order to avoid index errors.
def longer(s):
for i in range(0,len(s)):
x = s[i]
if x == 'w':
new_str = s[:i] + 'v' + s[i+1:]
if (i + 1 >= len(s)):
new_str = new_str + 'v'
else:
new_str = new_str[:i] + 'v' + new_str[i:]
s = new_str
return s
def shorter(s):
long_str = longer(s)
short_str = long_str[0]
j = 1
for i in range(1,len(long_str)):
x = long_str[i]
if x == 'v' and short_str[j-1] == 'v':
short_str = short_str[:j-1] + 'w'
j = j -1
else:
short_str = short_str + x
j = j +1
return short_str
print len(longer("avwvb"))
print len(shorter("avwvb"))