Linear Search Python - python

I am new to python and we were given an assignment to create a linear search program that does not use "in" or index. The program compiles but says that every number I input is not in the list. I also have to do the same thing for a binary search but I'm doing things one at a time ha. Any help is appreciated!
PS: How could I show what index it is in without using the "index" function?
def linearSearch(intList,target):
found = False
position = 0
while position < len(intList) and not found:
if intList[position] == target:
found = True
position = position + 1
return found
linearList = [3,5,9,7,6,12,15,9,1]
numInput = input("What number are you looking for? ")
numFound = linearSearch(linearList, numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")

1) Start position = -1
2) return position
3) You want to position+=1 before if intList[position] == target: and you want to break when you do find the element. You then don't need found
Something is found when linearSearch(linearList, numInput) > 0
Then, your code just doesn't work because the list contains ints whereas input will always return a string. You must use int(input(".."))

This method uses list comprehension, and it will account for any duplicates in the list as well. It assigns a list of index/indices where the key occurs in the list. Read more about list comprehension here.
l = [1, 2, 3, 4, 4, 6]
el = 4
search = [i for i in range(len(l)) if el==l[i]]
print(search)
output:
[3, 4]
alternatively,
def LinSearch(target, intList):
search = [i for i in range(len(intList)) if target==intList[i]]
return search

def linearSearch(intList,target):
#print (target)
found = False
position = 0
while position < len(intList):
#print(intList[position])
if intList[position] == target:
found = True
break
position = position + 1
return found
linearList = [3,5,9,7,6,12,15,9,1]
numInput = int(input("What number are you looking for? "))
numFound = linearSearch(linearList,numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")
Please take care of type conversion...

Linear Search :
// funtion which rturns true if item found inside list.
def linearSearch(list, value):
for i in range(len(list)):
if i == value:
return True
// Call above function pass list of values and item to search
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
item = 10
print(linearSearch(list, item)) // item to search

def target(list,num):
for x in list:
if x == str(num):
print("match found:"+x)
break
else:
print('no match found')
list1 = ['6','4','7','9','0','2','3','1']
inp = input('Enter number to search:')
target(list1,inp)

def linear_search(list, key):
for i, item in enumerate(list):
if item == key:
return i
return -1
print(linear_search([4,5,2,7,1,8],7))
#If key is in the list returns its position in the list, otherwise returns -1.

n=int(input("Enter the number:"))
list,n=[10,11,12,13,14,15],n
if n in list:
print("Element found at",list.index(n))
else:
print("Not Found")
Advice: In python index starts from 0. To start from 1 format the code like this: list.index(n)+1

def linearSearch(array,k):
flag = False
position = 0
while position < len(intList) and not flag:
if array[position] == k:
flag = True
else:
position += 1
return position
array = [3,5,9,7,6,12,15,9,1]
numInput = int(input("What number are you looking for? "))
numFound = linearSearch(linearList,numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")

Related

Pyhton - trying to create a function that recives a positive number and checking if the number can be created from list numbers (in order)

so for example i have this list: [1,2,3,1,5,7,8,8,0]
i want to check if some integer number can be created from this list by the order of the list.
for example the integer 12358 will print TRUE but the integer 315782 will print False.
i got stuck, thats what i did but i just dont know how to continue
lst = [1,2,3,1,5,7,8,8,0]
lst_lenght = len(lst)
num1 = 0
num2 = 0
index = 0
max_index = 0
flag = True
while (flag == True):
num = int(input('\nEnter Positive integer (0 to stop):'))
num1 = num
num2 = num
if (num <= 0):
print('Finish')
flag = False
else:
for i in range (lst_lenght):
i just dont know how to continue, i've tried to get the last digit every time and to test if the index is higher then the next digits index (num % 10 , num // 10) but i struggle
I would convert everything to a string and then use some built-in methods:
def check(lst, n):
lst = ''.join(map(str, lst))
n = str(n)
pos = 0
for ch in lst:
if pos < len(n) and ch == n[pos]:
pos += 1
return pos == len(n)
Another very smart option using iterators:
def check(lst, n):
lst = ''.join(map(str, lst))
n = str(n)
it = iter(lst)
return all(x in it for x in n)
Examples:
>>> check([1,2,3,1,5,7,8,8,0], 12358)
True
>>> check([1,2,3,1,5,7,8,8,0], 315782)
False
You could convert the integer to a string, then to a list. Then for each element in the new list, check if it is in the number list. If it is, remove the element from both lists, removing just the element in the input number, and removing the element and every element before it on the list. Repeat for every element in the list. If the length of the input string at the end is 0, then you can construct the list
How about taking your input value (num), and converting it into a list of digits? For example, making the number '123' into an array, [1,2,3]. Then check the first member of the array, 1, to see if its in your list '1st'? If it isn't, you fail. If it is, you take note of where in the list '1st' the number one is found, and then search from that index number, in '1st' to the end of '1st' for the second digit. And repeat? If you get to the end of '1st', before you get to the end of the [1,2,3] array, you fail. If you get to the end of the [1,2,3] array before (or equal to) when you arrive at the end of the '1st' array.. you succeed!
I think this code helps you.
lst = [1,2,3,1,5,7,8,8,0]
def check(num):
try:
letter_index = [lst.index(int(a)) for a in str(num)]
except ValueError: # if value not in list return False
return False
result = False
greater = letter_index[0]
for i in letter_index:
if i>=greater:
lesser= i
result =True
else:
return False
return result
num = int(input('\nEnter Positive integer (0 to stop):'))
if check(num):
print('True')
else:
print("False")
You can convert your list into string then find substring in that string like that:
lst = [1,2,3,1,5,7,8,8,0]
list_as_string = ''.join(str(e) for e in lst)
lst_lenght = len(lst)
num1 = 0
num2 = 0
index = 0
max_index = 0
flag = True
while (flag == True):
num = int(input('\nEnter Positive integer (0 to stop):'))
num1 = num
num2 = num
if (num <= 0):
print('Finish')
flag = False
else:
checking_number = input(f"Enter {lst_lenght} number: ")
if len(checking_number) == lst_lenght:
if checking_number in list_as_string:
print(True)
else:
print(False)
else:
print(f"Wrong length: Please! Enter {lst_lenght} number: ")
A couple of other options (besides the already great answers):
Compare lists:
You convert your string number to a list and then check if it's in your starting list of numbers. As they are found, you pop the value from the starting list into a new list. Then check your new list at the end to see if it matches your input string:
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
outlist = []
for num in list(yournumber):
print(num)
if int(num) in yourlist:
outlist.append(str(yourlist.pop(yourlist.index(int(num)))))
print("".join(outlist) == yournumber)
>>>True
You may recognize the pattern (for: if: somelist.append()) that can be converted to list comprehension to shorten your code:
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
outlist = [str(yourlist.pop(yourlist.index(int(x)))) for x in list(yournumber) if int(x) in yourlist]
print("".join(outlist) == yournumber)
>>>True
Use Regex:
Another option here is to use regex. You can split your input string into a list, and then join it back together using .* as a delimiter. Then perform a regex match:
import re
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
#turn `yournumber` into "1.*2.*3.*5.*8" regex string
rex=".*".join(list(yournumber))
#join your starting list into a string and test it with the regex:
print(bool(re.match(rex, "".join(map(str, yourlist)))))
>>>True
Note that if your list elements are more than a single digit or character this can fail:
yourlist = [10, 23, 5, 8]
yournumber = '12358'
This will say "True" even though "10" isn't in the yournumber variable.

How to find the second lowest and second highest element in a list?

So, the function works with no errors, but the output for min2(2nd lowest value) in the list is incorrect. I cant seem to find the solution.
Python 3.8.6
def max2min2(list1):
max1=list1[0]
min1=list1[0]
max2=None
min2=None
for item in list1:
if item>max1:
max2=max1
max1=item
elif max2==None or max2<item:
max2=item
if item<min1:
min2=min1
min1=item
elif min2==None or min2>item:
min2=item
return max2,min2
list1 = [1,2,3]
max2,min2=max2min2(list1)
print(min2,max2) # 1 2
With the simple input list of [1,2,3] the output of maxmin2 is (1,2), although the expected output is (2,2).
Now if this does not to need to be speed optimized, simple way would be just take a set of the numbers, sort them, and take the second element from each end:
vals = [1,1,3,2,2]
filtered_vals = sorted(set(vals))
and then
# Second lowest
In [37]: filtered_vals[1]
Out[37]: 2
# Second highest
In [36]: filtered_vals[-2]
Out[36]: 2
add some Exception and special case handling if needed.
A simple and readable solution is to sort the list first, then directly index the values you want. I added a unique argument which specifies whether you want to look at the number values (most intuitive) or keep duplicate values in the list (so that the second highest number in [1,2,2] is 2).
def second_lowest_and_highest_using_sort(nums, unique=True):
if unique:
nums = list(set(nums))
if len(nums) == 1:
raise ValueError('Second lowest/highest number is undefined for a list of length 1.')
nums = sorted(nums)
return (nums[1], nums[-2])
A more verbose approach without sorting first:
def second_lowest_and_highest(nums, unique=True):
if unique:
nums = list(set(nums))
if len(nums) == 1:
raise ValueError('Second lowest/highest number is undefined for a list of length 1.')
lowest, highest = float('inf'), float('-inf')
second_lowest, second_highest = None, None
low_delta, high_delta = float('inf'), float('inf')
for num in nums:
low_delta_new = num - lowest
if low_delta_new < 0:
second_lowest = lowest
lowest = num
elif low_delta_new <= low_delta:
second_lowest = num
low_delta = low_delta_new
high_delta_new = num - highest
if high_delta_new > 0:
second_highest = highest
highest = num
elif high_delta_new <= high_delta:
second_highest = num
high_delta = high_delta_new
return (second_lowest, second_highest)

Python Sorting and Binary Search IndexError: list index out of range

I'm struggling to understand where the error is in this code:
def arr_sort_binsearch(ar):
ar.sort()
first = 0
last = len(ar)-1
found = False
item = 8
for num in ar:
while first<=last and not found:
midpoint = (first + last)//2
if ar[midpoint] + num == item:
found = True
else:
if item < ar[midpoint]:
last = midpoint-1
else:
first = midpoint+1
print("{} and {} is: {}".format(num, ar[num], item))
ar = [1,3,5,7]
arr_sort_binsearch(ar)
I'm getting an exception that says my index is out of range. I understand the theory of what an index overflow is it's just that I can't find it in my code.
the error is in this statement i think:
print("{} and {} is: {}".format(num, ar[num], item))
num should not be an argument in ar
cheers
If you try to write a binary search, your code is incorrect.
1, answer your question, why IndexError: list index out of range:
the code for loop over the input list ar as num, and at last print, the element will be the index of ar[num], this raise the error, eg:
you have ar=[1,2,3,4,5,8,9,11,6], when loop to 9, the printtry to use ar[9], but there is only 9 element in the list ar, exceed the maximum index 8, this will raise IndexError: list index out of range.
2, your binary search can be amended like this:
def arr_sort_binsearch(ar,item):
ar.sort()
first = 0
last = len(ar)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if ar[midpoint] == item:
found = True
else:
if item < ar[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
This will return the True or False, if you call function:
arr_sort_binsearch([1,2,3,4,5,8,9,11,6],12) Return False
arr_sort_binsearch([1,2,3,4,5,8,9,11,6],8) Return True

Binary Search python 3.5

I'm trying to write binary search in python 3.5 but it wont work I'm not sure why.
def binarySearch(alist, value):
first = 0
last = len(alist)-1
midpoint = (last//2)
while binarySearch:
if value == alist[midpoint]:
return True and print ("found")
else:
if value < midpoint:
last = midpoint-1
else:
if value > midpoint:
first = midpoint+1
binarySearch([1,2,3,4,5,6,7,8],3)
if I put value as 4 it displays found, if I put anything else nothing happens and its stuck running doing nothing.
Thanks for your help.
User1915011 beat me to my answer. In line with his answer and #wim's comment, I have made the following changes your binarySearch method.
Changed the loop to use the found variable
Added an additional assignment to midpoint inside the loop
Ensure the loop terminates by adding first<=last
Return found after the while loop to indicate success or failure.
def binarySearch(alist, value):
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if value == alist[midpoint]:
found = True
else:
if value < alist[midpoint]:
last = midpoint-1
else:
if value > midpoint:
first = midpoint+1
return found
if binarySearch([1,2,3,4,5,6,7,8],3):
print "found"
Your looping condition is just wrong while binarySearch?
You change value of midpoint only once instead you should be changing it every loop iteration.
You compare value with index (midpoint) and should be comparing with
list value (alist[midpoint])
This is wrong: return True and print ("found") it will always return None.
Here is a detailed explanation how it works:
def binarySearch(array, i):
## Binary search is the algorithm which is used to search an element in a sorted array
## The time complexity of the binary search is O(log n)
## Which means that in an array of length(2^(n-1)) elements we need to look at only n elements
## That is why we say that binary search algorithm runs in logarithmic time, which is much faster than linear time
start = 0
last = len(array)-1
result = False
count = 0 ## to debug
print("\n******************************************************************\n")
while(start <= last and not result):
## Debugger Begin
mid = 0
print("Loop number: ", count)
print("Start element: ", array[start], " Position of Start Element: ", start)
print("Last element: ", array[last], " Position of Last Element: ", last)
## Debugger End
mid = (start + last)//2 ## '//' indicates the floor division(ignores the value after the period)
if(array[mid] == i):
print("***Mid***")
result = True;
else:
if(i < array[mid]):
print("***The value of the item:",i," we are searching for is LESS than the current middle element***")
last = mid - 1
else:
print("***The value of the item:",i," we are searching for is GREATER than the current middle element***")
start = mid + 1
## Debugger
count = count+1
print("Mid element: ", array[mid], " Position of Mid Element: ", mid, "\n")
## Debugger
print("******************************************************************")
if(result == True):
print("\nThe element:",i ,"is in the array")
else:
print("\nItem is not in the array")
return result
## Array you want to search
array = [9, 11, 12, 21, 23, 34, 45, 49, 65, 98]
## Item you want to search in the array
i = 21
print("Searching the element: ",i , "\nIn the Array: ", array)
print("Length of the array is: ", len(array))
## Binary Search
binarySearch(array, i)
binary converters are also cool
num = int(input('please enter your number: '))
list = []
for i in (128, 64, 32, 16, 8, 4, 2, 1):
if num >= i:
list.append(1)
num = num-i
else:
list.append(0)
print(list)

Generate triangular numbers

This function is supposed to take an integer, generate the list of triangular numbers within range of that integer, check that list for the longest list of numbers whose sum == number and return them in a list, otherwise if there is no such list within that range of triangular numbers, return an empty list. I thought I had it somewhat, and it runs on python tutor.com, but when I run it in IDLE, nothing happens.
def checkio(number):
x = 4
lst = [1, 3, 6]
new = []
if number == 0:
return []
elif number == 1:
return [1]
elif number == 3:
return []
elif number == 6:
return []
elif number == 4:
return [1, 3]
elif number == 7:
return [1, 6]
elif number == 10:
return [1, 3, 6]
elif number > 10:
while number > lst[-1]: # Generates a list of all the triangular numbers up to number
for item in range(lst[-1]):
lst.append(x + lst[-1])
x += 1
go = []
start = 0
end = 0
count = 0
while count < len(lst) * 2:
if sum(lst[start:end+1]) < number:
end += 1
count += 1
elif sum(lst[start:end+1]) > number:
start += 1
count += 1
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
if count >= len(lst) * 2:
return []
In the code you post you are just declaring a function. In order to run it, you have to make a call to that function. In your case, it receives one argument, so you have to pass it inside the parentheses ():
number = 5 # for example
checkio(number) # this is the function call
As Bakuriu commented: If you want to get a result change the order of this lines:
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
To :
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
return go
break
This will return a value before escaping the while loop. As noted in the comments (thanks Andrea Corbellini) you can also remove the break statement and it will work well. Because after the return statement by definition escapes the function.
Also to run in idle once defined (you copied the code and pressed return), call it as Christian says.
This way you will check if works.
Note that you don't check in the ifelse clauses for the numbers 2, 5, 8 and 9. If you call this function with checkio(5), like suggested by Crhistian, it will not return anything because it doesn't have anything to return!

Categories

Resources