i have just made a simple linear search program in python3.. but somehow it is working strangely..idk why?
here is my code :
def linear_Search(Transaction_list,n,amount):
for i in range(0,n)::
if (Transaction_list[i] ==amount):
return i
else:
return -1
n=int(input("Enter the total number of days\n"))
Transaction_list=list(map(int,input(f"Enter all {n} Transactions made each day seperated by spaces :").strip().split()))[:n]
amount=int(input("Enter the Amount u want to search :"))
result=linear_Search(Transaction_list,n,amount)
if (result==-1):
print(f"Transaction of ${amount} is not made in last {n} days")
else:
print(f"Transaction of ${amount} is made on day {result 1}")
CodePudding user response:
You can't return -1
until you have searched through the ENTIRE list. Right now, you just check the first item and fail if not present. You never check the rest of the list.
Also, i
will be the VALUE of the element, not the INDEX. You can use enumerate
to solve that:
def linear_Search(Transaction_list,n,amount):
for n,i in enumerate(Transaction_list):
if i == amount:
return n
return -1
Or, since Python has this ability built-in:
def linear_Search(Transaction_list,n,amount):
if amount in Transaction_list:
return Transaction_list.index(amount)
return -1
CodePudding user response:
Try with this:
def linear_search(transaction_list, n, amount):
for i in range(n):
if (transaction_list[i] == amount):
return i
return -1