Can any one explain me this Question?
I am not understanding what it is asking me to do!
Question:
Consider the searching problem.
Input: a sequence of n numbers A = [A1,A2,...An] and a value v.
Output: an index i such that v = A[i] or the special value NIL if v does not appear in A.
Write pseudo-code for linear search, which scans the sequence, looking for v. Using a loop invariant fulfilling the three necessary properties.
My Answer:
a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
n = int(input("Enter a number :"))
if n in a:
print(f"{n} is in the sequence")
else:
print("NIL")
Is this answer correct?
You must work with the indexes of the list so the answer might be a code like:
A = [11,10,0,13,6,25,9,17,2,19]
v = 6
for i in range(len(A)):
if A[i] == v:
print(i)
break
else:
print("NIL")
For this example the answer will be 4 because the number that is given from the input is 6 and we can find that number ( v ) at the 4th index of our list ( A ).
Hope that was helpful.
Related
numbers=[0,1,2,3,4,5,0]
print(numbers)
bbb=int(input("Enter the number at the list"))
for i, n in enumerate(numbers):
if n == bbb :
print(numbers.index(bbb))
numbers[i] = None
numbers = [n for n in numbers if n is not None]
As you can see by executing the code that I entered above,
For the index value of the input value, in the first case, it operates normally with 'X'. (X is the index value for the input value.)
However, if the input value is duplicated, X will have several.
At this time, a problem arises.
When operating with the code I created, the value is output as 'X-1' from the second value.
I think it will be difficult to understand, so there is an example below.
When the code is operating normally:
[0,1,2,3,4,5,0]
input: 0
index: 0, 6
In the case of the code I wrote:
[0,1,2,3,4,5,0]
input: 0
index: 0, 5
I would appreciate it if you could give me even a little advice. Can you tell me how to solve this problem? please help..
You need to find all indices first. And then remove the values:
numbers=[0,1,2,3,4,5,0]
bbb=int(input("Enter the number at the list"))
indices = [i for i, n in enumerate(numbers) if n == bbb]
numbers = [n for n in numbers if n != bbb]
print(*indices, sep='\n') # prints all indices one per line
The first parameter in your loop is index, so most of the code is unnecessary
numbers = [0,1,2,3,4,5,0]
to_check = int(input("Enter the number at the list "))
for ind, val in enumerate(numbers):
if val == to_check:
print(ind)
what i get from your question is you want the input value to get check from your list at what index does they exists :
So here is the solution:
numbers=[0,1,2,3,4,5,0]
bbb=int(input("Enter the number at the list"))
for i, n in enumerate(numbers):
if n==bbb:
print(i)
else:
print('number not there in the list')
Output img with two case :
with the number which exist in list eg(0)
with the number that does not exist in list eg(7)
:
If this help you plz vote my ans up
I am curious to find out a function to check if a given list is periodic or not and return the periodic elements. lists are not loaded rather their elements are generated and added on the fly, if this note will make the algorithm easier anyhow.
For example, if the input to the function is [1,2,1,2,1,2,1,2], the output shall be (1,2).
I am looking for some tips and hints on the easier methods to achieve this.
Thanks in advance,
This problem can be solved with the Knuth-Morris-Pratt algorithm for string matching. Please get familiar with the way the fail-links are calculated before you proceed.
Lets consider the list as something like a sequence of values (like a String). Let the size of the list/sequence is n.
Then, you can:
Find the length of the longest proper prefix of your list which is also a suffix. Let the length of the longest proper prefix suffix be len.
If n is divisible by n - len, then the list is periodic and the period is of size len. In this case you can print the first len values.
More info:
GeeksForGeeks article.
Knuth-Morris-Pratt algorithm
NOTE: the original question had python and python-3.x tags, they were edited not by OP, that's why my answer is in python.
I use itertools.cycle and zip to determine if the list is k-periodic for a given k, then just iterate all possible k values (up to half the length of the list).
try this:
from itertools import cycle
def is_k_periodic(lst, k):
if len(lst) < k // 2: # we want the returned part to repaet at least twice... otherwise every list is periodic (1 period of its full self)
return False
return all(x == y for x, y in zip(lst, cycle(lst[:k])))
def is_periodic(lst):
for k in range(1, (len(lst) // 2) + 1):
if is_k_periodic(lst, k):
return tuple(lst[:k])
return None
print(is_periodic([1, 2, 1, 2, 1, 2, 1, 2]))
Output:
(1, 2)
Thank you all for answering my question. Neverthelss, I came up with an implementation that suits my needs.
I will share it here with you looking forward your inputs to optimize it for better performance.
The algorithm is:
assume the input list is periodic.
initialize a pattern list.
go over the list up to its half, for each element i in this first half:
add the element to the pattern list.
check if the pattern is matched throughout the list.
if it matches, declare success and return the pattern list.
else break and start the loop again adding the next element to the pattern list.
If a pattern list is found, check the last k elements of the list where k is len(list) - len(list) modulo the length of the pattern list, if so, return the pattern list, else declare failure.
The code in python:
def check_pattern(nums):
p = []
i = 0
pattern = True
while i < len(nums)//2:
p.append(nums[i])
for j in range(0, len(nums)-(len(nums) % len(p)), len(p)):
if nums[j:j+len(p)] != p:
pattern = False
break
else:
pattern = True
# print(nums[-(len(nums) % len(p)):], p[:(len(nums) % len(p))])
if pattern and nums[-(len(nums) % len(p)) if (len(nums) % len(p)) > 0 else -len(p):] ==\
p[:(len(nums) % len(p)) if (len(nums) % len(p)) > 0 else len(p)]:
return p
i += 1
return 0
This algorithm might be inefficient in terms of performance but it checks the list even if the last elements did not form a complete period.
Any hints or suggestions are highly appreciated.
Thanks in advance,,,
Let L the list. Classic method is: use your favorite algorithm to search the second occurence of the sublist L in the list L+L. If the list is present at index k, then the period is L[:k]:
L L
1 2 1 2 1 2 1 2 | 1 2 1 2 1 2 1 2
1 2 1 2 1 2 1 2
(This is conceptually identical to #KonstantinYovkov's answer). In Python: example with strings (because Python has no builtin sublist search method):
>>> L = "12121212"
>>> k = (L+L).find(L, 1) # skip the first occurrence
>>> L[:k]
'12'
But:
>>> L = "12121"
>>> k = (L+L).find(L, 1)
>>> L[:k] # k is None => return the whole list
'12121'
Given a set of integers 1,2, and 3, find the number of ways that these can add up to n. (The order matters, i.e. say n is 5. 1+2+1+1 and 2+1+1+1 are two distinct solutions)
My solution involves splitting n into a list of 1s so if n = 5, A = [1,1,1,1,1]. And I will generate more sublists recursively from each list by adding adjacent numbers. So A will generate 4 more lists: [2,1,1,1], [1,2,1,1], [1,1,2,1],[1,1,1,2], and each of these lists will generate further sublists until it reaches a terminating case like [3,2] or [2,3]
Here is my proposed solution (in Python)
ways = []
def check_terminating(A,n):
# check for terminating case
for i in range(len(A)-1):
if A[i] + A[i+1] <= 3:
return False # means still can compute
return True
def count_ways(n,A=[]):
if A in ways:
# check if alr computed if yes then don't compute
return True
if A not in ways: # check for duplicates
ways.append(A) # global ways
if check_terminating(A,n):
return True # end of the tree
for i in range(len(A)-1):
# for each index i,
# combine with the next element and form a new list
total = A[i] + A[i+1]
print(total)
if total <= 3:
# form new list and compute
newA = A[:i] + [total] + A[i+2:]
count_ways(A,newA)
# recursive call
# main
n = 5
A = [1 for _ in range(n)]
count_ways(5,A)
print("No. of ways for n = {} is {}".format(n,len(ways)))
May I know if I'm on the right track, and if so, is there any way to make this code more efficient?
Please note that this is not a coin change problem. In coin change, order of occurrence is not important. In my problem, 1+2+1+1 is different from 1+1+1+2 but in coin change, both are same. Please don't post coin change solutions for this answer.
Edit: My code is working but I would like to know if there are better solutions. Thank you for all your help :)
The recurrence relation is F(n+3)=F(n+2)+F(n+1)+F(n) with F(0)=1, F(-1)=F(-2)=0. These are the tribonacci numbers (a variant of the Fibonacci numbers):
It's possible to write an easy O(n) solution:
def count_ways(n):
a, b, c = 1, 0, 0
for _ in xrange(n):
a, b, c = a+b+c, a, b
return a
It's harder, but possible to compute the result in relatively few arithmetic operations:
def count_ways(n):
A = 3**(n+3)
P = A**3-A**2-A-1
return pow(A, n+3, P) % A
for i in xrange(20):
print i, count_ways(i)
The idea that you describe sounds right. It is easy to write a recursive function that produces the correct answer..slowly.
You can then make it faster by memoizing the answer. Just keep a dictionary of answers that you've already calculated. In your recursive function look at whether you have a precalculated answer. If so, return it. If not, calculate it, save that answer in the dictionary, then return the answer.
That version should run quickly.
An O(n) method is possible:
def countways(n):
A=[1,1,2]
while len(A)<=n:
A.append(A[-1]+A[-2]+A[-3])
return A[n]
The idea is that we can work out how many ways of making a sequence with n by considering each choice (1,2,3) for the last partition size.
e.g. to count choices for (1,1,1,1) consider:
choices for (1,1,1) followed by a 1
choices for (1,1) followed by a 2
choices for (1) followed by a 3
If you need the results (instead of just the count) you can adapt this approach as follows:
cache = {}
def countwaysb(n):
if n < 0:
return []
if n == 0:
return [[]]
if n in cache:
return cache[n]
A = []
for last in range(1,4):
for B in countwaysb(n-last):
A.append(B+[last])
cache[n] = A
return A
This is a practice problem I am solving:
Given a set S of distinct integers, print the size of a maximal subset S' of S where the sum of any 2 numbers in S' are not evenly divisible by k.
My approach was to limit the problem to the subset S[0...i] where 0 < i <= n-1 and determine the length of the maximal subset for that subproblem, then extend the subproblem by 1. I know there is a different approach to this problem but I am confused why my solution does not work.
ex) for n = 10, k = 5, and S = [770528134, 663501748, 384261537, 800309024, 103668401, 538539662, 385488901, 101262949, 557792122, 46058493]
dp = [0 for _ in range(n)]
dp[0] = 1
for i in range(1, n):
flag = 0
for j in range(i):
if s[j] == "#":
pass
elif (not s[j] == "#") and (s[j] + s[i])%k==0:
dp[i] = dp[i-1]
flag = 1
s[i] = "#"
break
if not flag == 1:
dp[i] = dp[i-1] + 1
print dp[-1]
The output should be 6 but my function prints 5. What I try to do is iterate from j=0 to i and check if for any j < i if (s[j] + s[i])%k==0. If so, then considering s[i] in S' would be erroneous so instead mark s[i] with a # to indicate it is not in S'.
Your lack of comments and explanatory names makes your code very hard to follow, so I do not understand it. (Your example using a list when you talk of sets, and the use of both s and S for your "set", do not help.) However, the basic idea of your algorithm is flawed: this problem for a given set cannot be solved by extending the solution for a proper subset.
For example, take k=3, set S=[1,4,2,5,8]. For the first three elements [1,4,2], the solution is [1,4]. For the first four elements [1,4,2,5], the solution is either [1,4] or [2,5]. For the entire set, the solution is [2,5,8]. You see there is no "path" from the solution from the first three elements through the first five: you need to "restart" at either the first four or the entire set.
A solution that does work partitions the entire set S into equivalence classes where the elements in each class have the same remainder when divided by k. Examining these equivalence classes gives the final result. Let me know if you need more details. Note that you will need to decide clearly if any 2 numbers in S' means any 2 distinct numbers in S': this changes what you do at one or two of the equivalence classes.
NOTE: This is for a homework assignment, but the portion I have a question on is ok to ask help for.
I have to script out a sequence 11110000111000110010 (i am using python) without using switches or if statements and only a maximum of 5 for and whiles.
I already have my script laid out to iterate, I just can't figure out the algorithm as recursive or explicit let alone whether the element's are 1's 2's or 4's =/
As much as we have learned so far there is no equation or algorithm to use to figure OUT the algorithm for sequence. Just a set of instructions for defining one once we figure it out. Does anyone see a pattern here I am missing?
EDIT: What I am looking for is the algorithm to determine the sequence.
IE the sequence 1,3,6,10,15 would come out to be a[n]=(a[n-1]+n) where n is the index of the sequence. This would be a recursive sequence because it relies on a previous element's value or index. In this case a[n-1] refers to the previous index's value.
Another sequence would be 2, 4, 6, 8 would come out to be a[n] = (n*2) which is an explicit sequence because you only require the current index or value.
EDIT: Figured it out thanks to all the helpful people that replied.... I can't believe I didn't see it =/
There are many possible solutions to this problem. Here's a reusable solution that simply decrements from 4 to 1 and adds the expected number of 1's and 0's.
Loops used : 1
def sequence(n):
string = ""
for i in range(n):
string+='1'*(n-i)
string+='0'*(n-i)
return string
print sequence(4)
There's another single-line elegant and more pythonic way to do this:
print ''.join(['1'*x+'0'*x for x in range(4,0,-1)])
Loops used : 1, Lines of code : 1
;)
Note how there's a nested structure here. In pseudocode (so you do the python yourself):
for i in 4 .. 1:
for b in 1 .. 0:
for j in 1 .. i:
print b
You could try this:
print ''.join(['1'*i+'0'*i for i in range(4,0,-1)])
b_len = 4
ones = '1111'
zeros = '0000'
s = ''
for n in range(b_len, -1, -1):
s = s + ones[:n] + zeros[:n]
print s
prints:
11110000111000110010
I see. Four "1" - four "0", three "1" - three "0", two "1" - two "0", one "1" - one "0". 20 digits in total. What it means I have no clue.
#!/usr/bin/python
s=''
i=4
while i >0:
s=s+'1'*i+'0'*i
i -=1
print s
11110000111000110010
Is it exactly this sequence or do you want to be abble to change the length of the 1st sequence of 1?
you can use a reversed iteration loop like in this code:
def askedseq(max1):
seq = [] # declaring temporary sequence
for i in range(max1,0,-1): # decreasing iteration loop
seq += i*[1] + i*[0] # adding the correctly sized subseq
return seq
print askedseq(4) #prints the required sequence
print askedseq(5) #prints the equivalent sequence with 11111
prints:
11110000111000110010
111110000011110000111000110010
you can also look at numpy to do such things