updating value of argument passed in function - python-3.x

I am trying merge sort but the values in the list is not updating . I know arguments are passed by assignments .but how this code is not working
def mergeSort(arr):
#add code here
if len(arr) <2 :
return
mid = len(arr)//2
s1 = arr[:mid]
s2 = arr[mid:]
mergeSort(s1)
mergeSort(s2)
i= 0 ; j =0
while i+j < len(arr):
if i<len(s1) or j ==len(s2) and s1[i] <s2[j] :
arr[i+j] = s1[i]
i +=1
else :
arr[i+j] = s2[j]
j +=1
return arr
mergeSort(arr)
for ex arr =[5,4,3,2,1]
the output is same arr,
but this code is working fine
def mergeSort(arr):
#add code here
if len(arr)>1:
mid=len(arr)//2
l=arr[:mid]
r=arr[mid:]
mergeSort(l)
mergeSort(r)
i=j=k=0
while i<len(l) and j<len(r):
if l[i]<r[j]:
arr[k]=l[i]
i+=1
else:
arr[k]=r[j]
j+=1
k+=1
while i<len(l):
arr[k]=l[i]
i+=1
k+=1
while j<len(r):
arr[k]=r[j]
j+=1
k+=1
return arr
mergeSort(arr)
I don't know what i'm missing ? How the one is updating outer array and one not.

Related

Comparing the values of 2 lists without built-ins

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.

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

i keep getting "Invalid result type, int expected, <class 'NoneType'> found"

def solution(A):
# write your code in Python 3.6
count=0
for i in range(len(A)):
for j in range(len(A)):
if j!=i:
if A[i]==A[j]:
count = count+1
else:
count = count+0
if count==0:
return A[i]
pass
It looks like the purpose of this code is to loop through list A and return the first value if it does not have a duplicate.
else:
count = count+0
This is redundant, and you can merge the two if statements above it.
def solution(A):
# write your code in Python 3.6
count=0
for i in range(len(A)):
for j in range(len(A)):
if j != i and A[i] == A[j]:
count += 1
if count==0:
return A[i]
The issue is that if count never equals 0, you don't return anything.
Have you found an answer yet? I was just working on the same question on Codility. It has to do with the fact that you're only checking for a value of one. The description was very vague, but it basically comes down to also checking for odd values.
def solution(A):
# write your code in Python 3.6
count=0
for i in range(len(A)):
for j in range(len(A)):
if j != i and A[i] == A[j]:
count += 1
if count % 2 == 1:
return A[i]
return -1
https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/

Buggy merge sort implementation

My merge sort implementation is buggy since i am not getting two sorted list before calling merge.I am not sure what is wrong with it.
def mergeSort(arr):
if len(arr) == 1 : return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
mergeSort(left_half)
mergeSort(right_half)
return merge(left_half,right_half)
def merge(list1,list2):
res = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
res.append(list1[i])
i += 1
elif list1[i] > list2[j]:
res.append(list2[j])
j += 1
#Add remaining to res if any
while i < len(list1):
res.append(list1[i])
i += 1
while j < len(list2):
res.append(list2[j])
j += 1
return res
A = [5,1,2,15]
print(mergeSort(A))
My understanding of merge sort is that the space complexity is O(n) since n items in memory (in the final merge).Is quick sort preferred over merge sort just because quick sort is in-place?
I not python expert, but you should write
left_half = arr[:mid]
right_half = arr[mid:]
left_half = mergeSort(left_half)
right_half = mergeSort(right_half)
Because your mergeSort return copy of sorted array.
You have 3 mistakes in your code.
The first is that you don't handle the empty list. You need a <= instead of an == in your second line.
The second is that by simply calling mergeSort(left_half) you suppose that it will sort left_half “by reference”, which it doesn't (same with right_half).
The third is that you aren't doing anything in the case list1[i] == list2[j]. Actually you don't need that elif, you simply need an else. It doesn't matter whether you append list1[i] or list2[j] if they are equal, but you must append one of the two.
Your code should rather be:
def mergeSort(arr):
if len(arr) <= 1 : return arr
mid = len(arr) // 2
left_half = mergeSort(arr[:mid])
right_half = mergeSort(arr[mid:])
return merge(left_half, right_half)
def merge(list1, list2):
res = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
res.append(list1[i])
i += 1
else:
res.append(list2[j])
j += 1
#Add remaining to res if any
...
As for your questions about space complexity and comparison with quicksort, there are already answers here on StackOverflow (here and here).

Unable to solve this issue with the code

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"))

Resources