def printPairs(arr, n, sum):
for i in range(0, n ):
for j in range(i + 1, n ):
if (arr[i] + arr[j] == sum):
print("(", arr[i], ", ", arr[j], ")", sep = "")
# Driver Code
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)
Does this look like it will do the job for you?
def printPairs (array, total) :
used = []
for number1 in array :
for number2 in array :
if number1 + number2 == total and number2 not in used :
print (f'({number1}, {number2})')
used.extend ([number1, number2])
test_array = [1, 5, 7, -1, 5]
# test_array = [4, 2, 1, 3, 6]
target = 6
printPairs (test_array, target)
Related
My implementation:
def merge_sort(arr):
if len(arr) <= 1:
return arr
left = arr[:len(arr)//2]
right = arr[len(arr)//2:]
merge_sort(left)
merge_sort(right)
return merge(left, right)
def merge(left, right):
leftI = rightI = 0
merged = []
while (leftI < len(left) and rightI < len(right)):
if left[leftI] < right[rightI]:
merged.append(left[leftI])
leftI += 1
else:
merged.append(right[rightI])
rightI += 1
merged.extend(left[leftI:])
merged.extend(right[rightI:])
return merged
if __name__ == '__main__':
arr = [1,2,5,5,9,22,6,3,6,8,1,43,5]
print(merge_sort(arr))
For some reason I am obtaining:
[1, 2, 5, 5, 6, 3, 6, 8, 1, 9, 22, 43, 5]
Working Implementation (Got from a friend):
def merge_sort(list):
list_length = len(list)
if list_length == 1:
return list
mid_point = list_length // 2
left_partition = merge_sort(list[:mid_point])
right_partition = merge_sort(list[mid_point:])
return merge(left_partition, right_partition)
def merge(left, right):
output = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
output.append(left[i])
i += 1
else:
output.append(right[j])
j += 1
output.extend(left[i:])
output.extend(right[j:])
return output
if __name__ == '__main__':
arr = [1,2,5,5,9,22,6,3,6,8,1,43,5]
print(merge_sort(arr))
This code yeilds:
[1, 1, 2, 3, 5, 5, 5, 6, 6, 8, 9, 22, 43]
I just can't figure out what's wrong. It'd be a great help if someone could take a few moments to help me out :)
In your merge_sort function, you do not change the values of left and right depending on what merge_sort returns.
You have :
merge_sort(left)
merge_sort(right)
Where it should be :
left = merge_sort(left)
right = merge_sort(right)
This is my code to find values common between 2 arrays.
li1 = [int(x) for x in input().split()]
li2 = [int(h) for h in input().split()]
for m in li1 :
for j in li2 :
if m == j :
print(m, end=" ")
j = float("-inf")
break
When I do li1 = [5, 5, 5] and li2 = [5, 5], it returns 5 5 5. I want this to be 5 as li2 only has two 5. How can I do this.
You can do the same more simply by using sets and intersection:
li1 = [1, 2, 3]
li2 = [2, 3, 4]
shared = list(set(li1).intersection(set(li2))
print(shared) # prints [2, 3]
I would like to count the number of instances of a given number N in an array using recursion. For example, given:
array = [1, 2, 3, 1, 1, 4, 5, 2, 1, 8, 1]
and N = 1, the function should return 5.
This problem can be solved using the .counter attribute as shown here. However, I am looking to not use any in-built functions or attributes.
Here's my attempt to solve this using recursion but I get a count of 1 and not 5. What am I doing wrong?
def count_val(array, n, count=0):
if len(array) == 0:
return None
# Base Case
if len(array) == 1:
if array[0] == n:
count += 1
else:
count_val(array[1:], n, count)
if array[0] == n:
count += 1
return count
print(count_val2(array, 1))
1
I think for an empty array, the value should be 0 (len == 0 should be the base case), and, you don't need to have a count parameter if you just return the count, your function could be reduced to this:
def count_val(array, n):
if len(array) == 0:
return 0
return (array[0] == n) + count_val(array[1:], n)
array = [1, 2, 3, 1, 1, 4, 5, 2, 1, 8, 1]
print(count_val(array, 1))
Output:
5
You can have it as a one-liner as well (as suggested by #blhsing):
def count_val(array, n):
return len(array) and (array[0] == n) + count_val(array[1:], n)
What am I doing wrong?
The function you wrote will always keep only the last few characters, so after a while it will be [1, 8, 1], after that [8, 1] and after that [1], which returns 1. The array never contains just any of the other 1s.
An easy way to do this is to loop over all elements in a list and test if they are equal to N.
array = [1, 2, 3, 1, 1, 4, 5, 2, 1, 8, 1]
def count_val(array, n):
if len(array) == 0:
return 0
count=0
for i in array:
if i==n:
count += 1
return count
print(count_val(array, 1))
This returns 5.
I am currently taking discrete structures and algorithms and have to work with python for the first time.
I am having a little trouble with the syntax and having a problem with my bubble sort and insertion sort function printing
def insertion_sort(numbers):
numbers = [1, 5, 9, 3, 4, 6]
for index in range(1, len(numbers)):
value = numbers[index]
i = index - 1
while i >= 0:
if value < numbers[i]:
numbers[i+1] = numbers[i]
numbers[i] = value
i = i - 1
print(numbers)
else:
break
def bubble_sort(numbers):
for i in range(0, len(numbers) - 1, 1):
for j in range(0, len(numbers) - 1 - i, 1):
if numbers[j] < numbers[j + 1]:
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
numbers = [1, 5, 9, 3, 4, 6]
print(numbers)
You've defined two functions but never call them. Therefore, they are not getting executed.
You've defined your two functions such that they expect a numbers parameter. So you need to call them with a list of numbers as input. eg. insertion_sort([1, 5, 9, 3, 4, 6])
Your functions are not returning any value. So they are simply taking the numbers list parameter, and sorting it. In order to access the result from outside the function, you need to add return numbers at the end of each function.
All in all, your code should look something like this:
def insertion_sort(numbers):
for index in range(1, len(numbers)):
value = numbers[index]
i = index - 1
while i >= 0:
if value < numbers[i]:
numbers[i+1] = numbers[i]
numbers[i] = value
i = i - 1
else:
break
return numbers
def bubble_sort(numbers):
for i in range(0, len(numbers) - 1, 1):
for j in range(0, len(numbers) - 1 - i, 1):
if numbers[j] < numbers[j + 1]:
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
return numbers
numberstosort = [1, 5, 9, 3, 4, 6]
print(insertion_sort(numberstosort))
print(bubble_sort(numberstosort))
This will print the output of each function. Output:
[1, 3, 4, 5, 6, 9]
[9, 6, 5, 4, 3, 1]
I have an error in this code as I want to calculate the variance between the values in the(x1) and (x2) list. any recommendation?!
def my_var(L):
s = 0
t = 0
u = 0
for i in range(0, len(L)):
s += L[i]
t = s/len(L)
u += ((L[i]-t)*(L[i]-t))
return u / len(L)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)
You're doing many things incorrectly based on how I learned prob and stats. You need to calculate the average (mean) and then sum each value subtracted by the mean, squared. Then finally take that numerator and divide by 1 less than the sample size (n-1).
def my_var(L):
mean = float(sum(L) / Len(L))
numerator = 0
for i in range(0, len(L)):
numerator += (L[i]-mean)**2
return numerator / (len(L) - 1)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)
Without using sum:
def my_var(L):
my_sum = 0
mean = 0
numerator = 0
for i in range(0, len(L)):
my_sum += L[i]
mean = float(my_sum / len(L))
for i in range(0, len(L)):
numerator += (L[i]-mean)**2
return numerator / (len(L) - 1)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)
Try numpy.
import numpy as np
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = np.var(x1)
v2 = np.var(x2)
Thank you #billy_ferguson. I have modified your code and it works. Execuse me, I am still an amateur but could you replace float and sum function and use simpler arithmetic operators as len(L) and += in this line mean = float(sum(L) / len(L))
def my_var(L):
mean = 0
numerator = 0
for i in range(0, len(L)):
mean = float(sum(L) / len(L))
numerator += (L[i]-mean)**2
return numerator / len(L)
x1 = [1, 3, 4, -3, 8]
x2 = [1, -4, 7, 2]
v1 = my_var(x1)
v2 = my_var(x2)
print(v1)
print(v2)