I have a code which first sorts the emails into alphabetical order and then attempts to use binary search to search a user inputted email from a list. However, I have been stuck on how to do this for so long and haven't found any solutions on the error I get and how to fix it. Here is my code
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,ItemSought):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint] == ItemSought:
ItemFound = True
print("Item Found")
break
elif logindata[Midpoint] > ItemSought:
Last = Midpoint - 1
else:
First = Midpoint + 1
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
ItemSought=input("Enter username")
BinarySearch(logindata,ItemSought)
The error I currently get is :
elif logindata[Midpoint] > ItemSought:
TypeError: unorderable types: list() > str()
You're comparing a username/password pair (e.g. ["tom#gmail.com","Password1"]) with a username (e.g. "tom#gmail.com").
You need to extract the username from logindata[Midpoint] before comparing it to ItemSought.
Related
This is my code for a programming problem in a CS course that involves tokenizing a string by its opening and closing parentheses.
def expand(S):
if "(" in S:
open, close = parentheses_pair(S)
open = int(int(open) + int(1))
samp = S[open, close]
currstr = samp
innerstr = ""
if "(" in samp:
open, close = parentheses_pair(S)
currstr = samp[:open]
innerstr = samp[open, close+1]
innerstr = expand(innerstr)
output = ""
for i in range(1, len(currstr), 2):
letter = currstr[i-1]
number = currstr[i]
output += letter*number
output += innerstr
sorted_out = sorted(output)
output = "".join(sorted_out)
return output
else:
return ""
def parentheses_pair(S):
counter = 0
openpar = S.find("(")
currind = S.find("(")
found = False
while not found:
if S[currind] == "(":
counter += 1
elif S[currind] == ")":
if counter == 1:
found = True
break
else:
counter -= 1
currind += 1
return int(openpar), int(currind)
When I used type on both open and close, <class 'int'> was returned by the terminal so I really don't know why it won't accept the variables as the string indices on samp = S[open, close].
Write a python function, check_anagram() which accepts two strings and returns True, if one string is an anagram of another string. Otherwise returns False.
The two strings are considered to be an anagram if they contain repeating characters but none of the characters repeat at the same position. The length of the strings should be the same.
Note: Perform case insensitive comparison wherever applicable.
This is my code:
def check_anagram(data1,data2):
first = data1.lower()
second = data2.lower()
d1 = []
d2 = []
for i in range(0, len(first)):
d1.append(first[i])
for i in range(0, len(second)):
d2.append(second[i])
for_check1 = sorted(d1)
for_check2 = sorted(d2)
if (for_check1 != for_check2):
return False
count = 0
if (len(d1) == len(d2)):
for i in d1:
for j in d2:
if(i == j):
a = d1.index(i)
b = d2.index(j)
if(a == b):
return False
else:
count += 1
if(count == len(first)):
return True
else:
return False
print(check_anagram("Schoolmaster", "Theclassroom"))
The output I am getting is "False"
Although this program is giving relevant output for string values like {silent, listen}{Moonstarrer, Astronomer}{apple, mango} but not for the above two strings(in code)
What cases am I missing in this code?? How to rectify this thing?
Your function could be simplified as:
def check_anagram(data1, data2):
data1 = data1.lower()
data2 = data2.lower()
if sorted(data1) != sorted(data2):
return False
return all(data1[i] != data2[i] for i in range(len(data1)))
Which actually works for the case you specified.
your code is correct just write len(second) instead of count.
def check_anagram(data1,data2):
first = data1.lower()
second = data2.lower()
d1 = []
d2 = []
for i in range(0, len(first)):
d1.append(first[i])
for i in range(0, len(second)):
d2.append(second[i])
for_check1 = sorted(d1)
for_check2 = sorted(d2)
if (for_check1 != for_check2):
return False
count = 0
if (len(d1) == len(d2)):
for i in d1:
for j in d2:
if(i == j):
a = d1.index(i)
b = d2.index(j)
if(a == b):
return False
else:
count += 1
if(len(second) == len(first)):
return True
else:
return False
print(check_anagram("Schoolmaster", "Theclassroom"))
This program of mine is clearing all possible test cases.
def check_anagram(data1,data2):
data1=data1.lower()
data2=data2.lower()
if(len(data1)==len(data2)):
if(sorted(data1)!=sorted(data2)):
return False
else:
if(data1[i]!=data2[i] for i in range(len(data1))):
return True
else:
return False
else:
return False
print(check_anagram("eat","tea"))
I have this code in python and selenium to find the deleted records and verify that the record is deleted.
def find_deleted_device(self, mac, serialno):
index = 0
loopNext = True
matched = False
while loopNext:
index = 0
if not element_locator.find_elements_by_css(driver_obj, self.no_device):
record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)
for facility_mac, serialnumber in zip(macaarray, serialnum):
if facility_mac.text == mac and serialnumber.text == serialno:
loopNext = False
matched = True
break
elif index == len(record) - 1:
if index >= 19:
next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
if next_page.is_enabled():
next_page.click()
else:
loopNext = False
index = index + 1
else:
loopNext = False
else:
print('No matching macaddress and serial number, No device message appears')
assert True
loopNext = False
if matched:
print "The mac and serial number matched, should have been deleted"
assert False
else:
print('No matching macaddress and serial number found')
assert True
sleep(2)
But the problem is there are two scenarios:
1) If only one record exists and we delete that then I get a message "No Records exist"
2) second scenario is a few records exists and I can loop through and verify that the record is deleted.
In case of scenario 1, it works fine.
In case of scenario 2 , it passes but with an error something like "1496424768.39". How do I escape this error.
I fixed my issue using the following alternative approach.
#This method is used to search deleted group
def find_deleted_device_with_paging(self, mac, serialno):
page_num = element_locator.find_element_by_css(driver_obj, ".test-grid-pagination-summary")
if page_num.text < 1:
print('No matching macaddress and serial number found')
assert True
else:
index = 0
loopNext = True
matched = False
print "The mac and serial number matched, should have been deleted"
while loopNext:
index = 0
record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)
for facility_mac, serialnumber in zip(macaarray, serialnum):
if facility_mac.text == mac and serialnumber.text == serialno:
loopNext = False
matched = True
break
elif index == len(record) - 1:
if index >= 19:
next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
if next_page.is_enabled():
next_page.click()
else:
loopNext = False
index = index + 1
else:
loopNext = False
if matched:
print "The mac and serial number matched, should have been deleted"
assert False
else:
print('No matching macaddress and serial number found')
assert True
So, Instead of verifying the message ,I am comparing the number of records that exist on that page for pagination purpose. This fixed my code.
I have a binary search to search a list of emails from a user input. However when the user inputted email isnt found in the list I want the user to be able to enter another time. However I dont know how to return it to the start of the while loop again.
Here is my Code:
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,email):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint][0] == email:
ItemFound = True
print("Email Found")
break
elif logindata[Midpoint][0] > email:
Last = Midpoint - 1
print("Not Found")
else:
First = Midpoint + 1
print("Not Found")
return False
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
email=input("Enter username")
BinarySearch(logindata,email)
Just add the part you need to repeat in another while loop:
email=input("Enter username")
BinarySearch(logindata,email)
to:
while True:
email=input("Enter username")
res = BinarySearch(logindata,email)
if res:
break
print("Done")
and work with the return value of your BinarySearch function.
You also need to change the implementation of BinarySearch to return the appropriate values. Also, your condition is faulty, binary searching is ends when First <= Last, you can drop the other flags you're using:
def BinarySearch(logindata,email):
First=0
Last=len(logindata)-1
while First <= Last:
Midpoint = (First + Last) // 2
if logindata[Midpoint][0] == email:
print("Email Found")
return True
elif logindata[Midpoint][0] > email:
Last = Midpoint - 1
else:
First = Midpoint + 1
print("Not found")
return False
You shouldn't be printing Not Found whenever one of the else clause is executed, it hasn't been found yet since the search hasn't rerminated. Print that out in the end, after the while loop of BinarySearch has been exited.
I am asked to binary search a list of names and if these names start with a particular letter, for example A, then I am to print that name.
I can complete this task by doing much more simple code such as
for i in list:
if i[0] == "A":
print(i)
but instead I am asked to use a binary search and I'm struggling to understand the process behind it. We are given base code which can output the position a given string. My problem is not knowing what to edit so that I can achieve the desired outcome
name_list = ["Adolphus of Helborne", "Aldric Foxe", "Amanita Maleficant", "Aphra the Vicious", "Arachne the Gruesome", "Astarte Hellebore", "Brutus the Gruesome", "Cain of Avernus"]
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
found = False
while low_b <= up_b and found == False:
midPos = ((low_b + up_b) // 2)
if list[midPos] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
if found:
print("The name is at positon " + str(midPos))
return midPos
else:
print("The name was not in the list.")
Desired outcome
bin_search(name_list,"A")
Prints all the names starting with A (Adolphus of HelBorne, Aldric Foxe .... etc)
EDIT:
I was just doing some guess and check and found out how to do it. This is the solution code
def bin_search(list, item):
low_b = 0
up_b = len(list) - 1
true_list = []
count = 100
while low_b <= up_b and count > 0:
midPos = ((low_b + up_b) // 2)
if list[midPos][0] == item:
true_list.append(list[midPos])
list.remove(list[midPos])
count -= 1
elif list[midPos] < item:
low_b = midPos + 1
count -= 1
else:
up_b = midPos - 1
count -= 1
print(true_list)
Not too sure if this is what you want as it seems inefficient... as you mention it seems a lot more intuitive to just iterate over the entire list but using binary search i found here i have:
def binary_search(seq, t):
min = 0
max = len(seq) - 1
while True:
if max < min:
return -1
m = (min + max) // 2
if seq[m][0] < t:
min = m + 1
elif seq[m][0] > t:
max = m - 1
else:
return m
index=0
while True:
index=binary_search(name_list,"A")
if index!=-1:
print(name_list[index])
else:
break
del name_list[index]
Output i get:
Aphra the Vicious
Arachne the Gruesome
Amanita Maleficant
Astarte Hellebore
Aldric Foxe
Adolphus of Helborne
You just need to found one item starting with the letter, then you need to identify the range. This approach should be fast and memory efficient.
def binary_search(list,item):
low_b = 0
up_b = len(list) - 1
found = False
midPos = ((low_b + up_b) // 2)
if list[low_b][0]==item:
midPos=low_b
found=True
elif list[up_b][0]==item:
midPos = up_b
found=True
while True:
if found:
break;
if list[low_b][0]>item:
break
if list[up_b][0]<item:
break
if up_b<low_b:
break;
midPos = ((low_b + up_b) // 2)
if list[midPos][0] < item:
low_b = midPos + 1
elif list[midPos] > item:
up_b = midPos - 1
else:
found = True
break
if found:
while True:
if midPos>0:
if list[midPos][0]==item:
midPos=midPos-1
continue
break;
while True:
if midPos<len(list):
if list[midPos][0]==item:
print list[midPos]
midPos=midPos+1
continue
break
else:
print("The name was not in the list.")
the output is
>>> binary_search(name_list,"A")
Adolphus of Helborne
Aldric Foxe
Amanita Maleficant
Aphra the Vicious
Arachne the Gruesome
Astarte Hellebore