I'm trying to create a function that takes a list (a) and integer (x) as input and returns true if the list contains 3 elements that sum to the value of x. I'm getting a semantic error when I execute the code that I've written - please advise!
def sum_tri(a, x):
for i in range(len(a) - 1):
for j in range(i, len(a)):
for k in range(j, len(a)):
if a[i] + a[j] + a[k] == x:
return True
else:
return False
>>> a = [1, 5, 8, 2, 6, 55, 90]
>>> x = 103
>>> sum_tri(a, x)
False # However it should return True
You are returning False on the first failure, but you should do it only when all the options fail:
def sum_tri(a, x):
for i in range(len(a) - 1):
for j in range(i, len(a)):
for k in range(j, len(a)):
if a[i] + a[j] + a[k] == x:
return True
return False
a = [1, 5, 8, 2, 6, 55, 90]
x = 103
print sum_tri(a, x)
>>>True
Also you'll need to change the limits of your inner for loops from len(a) to len(a) - 1 or else you'll get:
a,x = [1,2,3],8
print sum_tri(a, x)
>>>True
because the 2nd and 3rd loops will accept the last element (3 in this case)...
The final function should look like:
def sum_tri(a, x):
for i in range(len(a) - 1):
for j in range(i, len(a) - 1):
for k in range(j, len(a) - 1):
if a[i] + a[j] + a[k] == x:
return True
return False
Related
I need to define a function with Python where given a non-empty array A of N (sorted in non-decreasing order) integers and integer K, checks whether A contains numbers 1, 2, …, K (every number from 1 to K at least once) and no other numbers.
This is the function I wrote, but I am getting some unexpected errors as:
print(solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15))
True
Above should be FALSE, 12 is missing
Function:
def solution(A, K):
n = len(A)
for i in range(K-1):
if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
return False
if (A[0] != 1 or A[n - 1] != K):
return False
else:
return True
Any ideas how to solve it changing a max of 2 lines from the code above? Thank you
PD: Working for the moment
def solution(A, K):
n = len(A)
for i in range(n - 1):
if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
return False
if (A[0] != 1 or A[n - 1] != K):
return False
else:
return True
This works:
def isInArray(el, arr):
for i in arr:
if el == i: return True
return False
def solution(arr, k):
l = len(A)
if l < k: return False
for i in range(1, k+1):
if not isInArray(i, arr): return False
return True
Use sets:
set(A) == set(range(1, K+1))
Example:
A = [1, 3, 2, 2, 4, 5, 1]
B = [1, 2, 2, 4, 5, 1] # 3 is missing
C = [1, 3, 9, 2, 4, 5, 1] # 9 is extra
K = 5
set(A) == set(range(1, K+1))
# True
set(B) == set(range(1, K+1))
# False
set(C) == set(range(1, K+1))
# False
using a loop
This is assuming that the input list is sorted!
def solution(l, k):
prev = 0
for x in l:
if x > k or x > prev+1:
return False
prev = x
return True
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15)
# False
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,12,13,14,14,15], 15)
# True
solution([1,2,3,4,5,6], 5)
# False
if space complexity of O(N) is allowed then here is a solution
# your code goes here
def solution(A, K):
array = [0 for i in range(K+1)]
for i in A:
if i>K or i<1:
return False
array[i] += 1
count = 0
for i in array[1:]:
if i==0:
return False
return True
I need to find out the first duplicated number in a list (the index of the second occurrence must be the smallest). Here is my code:
def firstDuplicate(a):
b = []
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] == a[j]:
b.append(j)
if len(b) == 0:
return -1
else:
return a[min(b)]
for example if I have a = [2, 1, 3, 5, 3, 2], it should return 3, but it returns 2 instead.
I verified with this code:
a = [2, 1, 3, 5, 3, 2]
b = []
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] == a[j]:
b.append(j)
print(b)
it turned out with the correct answer which is [5,4].
So I don't know what's wrong here. Can anybody help? Thanks!!
Here is the screenshots:
Everytime the condition a[i] == a[j] is met, you are returning and stoping the loop. Return after the loop is finished:
def firstDuplicate(a):
b = []
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] == a[j]:
b.append(j)
if len(b) == 0:
return -1
else:
return a[min(b)]
print(firstDuplicate([2, 1, 3, 5, 3, 2]))
Out:
3
It seems you have written return condition inside for loop. So it returning on first iteraton. Try this
def firstDuplicate(a):
b = []
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] == a[j]:
b.append(j)
if len(b) == 0:
return -1
else:
return a[min(b)]
I think we can identify duplicate with single iteration of array.
def first_duplicate(arr):
d = dict()
n = len(arr)
for i, v in enumerate(arr):
if v in d:
d[v] = i
else:
d[v] = n
# print(d)
return min(d, key=d.get)
arr = [2, 1, 3, 5, 3, 2]
print(first_duplicate(arr))
n = 10
s = [True] * (n)
a = []
def dfs(m):
if m == 0:
print(s) #(1)
if s not in a:
print(s) #(2)
a.append(s)
return
for x in range(0, n, 2):
s[x] = not s[x]
dfs(m - 1)
for x in range(0, n, 2):
s[x] = not s[x]
for x in range(1, n, 2):
s[x] = not s[x]
dfs(m - 1)
for x in range(1, n, 2):
s[x] = not s[x]
for x in range(0, n, 3):
s[x] = not s[x]
dfs(m - 1)
for x in range(0, n, 3):
s[x] = not s[x]
dfs(10)
why the first print(s) has many kinds of different s, but the second print(s) only have the initial s. I can't understand.How can I avoid this
problem when I use recursion when I use python
When s gets appended to a the first time m is equal to zero, it is NOT appending a copy of the list s to a. It is appending a reference to s, so each time s changes, the contents of a change along with it. Your print #2 is only ever done once and if not s in a is only True the very first time.
Try this in a Python console to see a simpler example of this:
>>> a = [1,2,3,4]
>>> b = []
>>> b.append(a)
>>> a[2] = 7
>>> b
[[1, 2, 7, 4]]
I am trying to permute a list but I cannot do it, it goes infinite cycle. I tried different things but somehow the only thing that it shows me is 1 2 3 ... 1 2 3 etc
This is the code:
def prints(v,k):
s = ''
for i in range(k + 1):
s += str(v[i]) + ' '
print(s)
def continuare(v,k):
ok = True
for i in range(k):
if v[i] == v[k]:
ok = False
break
return ok
def back(v,a):
k = 0
caut = False
while k>-1:
caut = False
pos = 0
while pos < len(a) and caut == False:
v[k] = a[pos]
pos += 1
if continuare(v,k):
caut = True
if caut == False:
k -= 1
elif k == len(a) - 1:
prints(v,k)
else:
k += 1
a = [1,2,3]
v = []
for x in range(len(a)):
v.append(a[0])
back(v,a)
Here's a trivial Python transcription from http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ :
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def permute(a, i, n):
if i == n:
print(a)
return
for j in range(i, n+1):
swap(a, i, j)
permute(a, i+1, n)
swap(a, i, j) # backtrack
def main():
a = list('ABC')
permute(a, 0, 2)
if __name__ == '__main__':
main()
I'd rather have permute be a generator yielding the permutations, with main looping on them and printing them, but this may be closer to the C original and thus easier to follow. Note that one difference is a must: what's being permuted here is a list, not a string as in the C original, because strings are immutable in Python (so swap would require substantially different logic, returning the "string with swapped characters" rather than being able to work in-place as the "backtracking" logic requires).
def insertion_sort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while (i >= 0) and (A[i] > key):
A[i+1] = A[i]
i = i-1
A[i+1] = key
return A
print insertion_sort([8, 1, 3, 4, 9, 5, 2])
Now this prints: [8, 1, 3, 4, 9, 5, 2]
But I assume, I am mutating the list A, then why is the return value the same?
Your code is wrong with current indentation. It should be like this, right?
def insertion_sort(A):
for j in range(1, len(A)):
key = A[j]
i = j - 1
while (i >= 0) and (A[i] > key):
A[i+1] = A[i]
i = i-1
A[i+1] = key
return A
As already mentioned, the indentation is incorrect.
And lists are mutable!