I am writing binary search tree for book phone. The problem is when I am trying to write the main code. I tried to use dictionary data structure but I cannot figure out how to make contact name as a key. I want to write any name and get phone number as a value.
It gave me an error
Traceback (most recent call last):
File "FastSort.py", line 22, in <module>
print(binarySearch(phonebook, "John"))
File "FastSort.py", line 8, in binarySearch
if alist[midpoint] == item:
KeyError: 1
This is a code
def binarySearch(alist, item):
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(binarySearch(phonebook, "John"))
print(binarySearch(phonebook, "Jack"))
You solution (if alist as really a sorted list) was pretty close so I thought I would help you out a bit:
import random
def binarySearch(alist, item):
first = 0
last = len(alist)-1
while first<=last:
midpoint = (first + last)//2
print midpoint
if alist[midpoint][0] == item:
return alist[midpoint]
else:
if item < alist[midpoint][0]:
last = midpoint-1
else:
first = midpoint+1
return False
items = []
items.append(("John", 938477566))
items.append(("Jack", 938377264))
items.append(("Jill", 947662781))
items = sorted(items)
print(binarySearch(items, "John"))
print(binarySearch(items, "Jack"))
print(binarySearch(items, "Jill"))
Related
cat Prog4CCM.py
numberArray = []
count = 0
#filename = input("Please enter the file name: ")
filename = "t.txt" # for testing purposes
file = open(filename, "r")
for each_line in file:
numberArray.append(each_line)
for i in numberArray:
print(i)
count = count + 1
def findMaxValue(numberArray, count):
maxval = numberArray[0]
for i in range(0, count):
if numberArray[i] > maxval:
maxval = numberArray[i]
return maxval
def findMinValue(numberArray, count):
minval = numberArray[0]
for i in range(0, count):
if numberArray[i] < minval:
minval = numberArray[i]
return minval
def findFirstOccurence(numberArray, vtf, count):
for i in range(0, count):
if numberArray[i] == vtf:
return i
break
i = i + 1
# Function calls start
print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count)))
print("The minimum value in the file is "+str(findMinValue(numberArray, count)))
vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count)))
This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array.
It should return a proper value, but just returns "None". Why might this be?
The file reading, and max and min value all seem to work perfectly.
You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error with adding one to the iterator and use break, the for loop will do that for you.
The correct code would look like this:
...
def findFirstOccurence(numberArray, vtf, count):
for i in range(0, count):
if numberArray[i] == vtf:
return i
# break # <==
# i = i + 1 # It's errors
return "Can't find =("
# Function calls start
print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count)))
print("The minimum value in the file is "+str(findMinValue(numberArray, count)))
vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count)))
At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt
The purpose is to comment the entire function void test_func with many nested {} using Python.
file = open(path_of_file)
data = file.readlines()
for item in data:
if item.find('void test_func') != -1:
point = data.index(item)
data.insert(point, '/*')
stack = []
for i in data[point+1:]:
if i.find('{') != -1:
stack.append('{')
elif i.find('}') != -1:
stack.pop()
if len(stack) == 0:
point1= data.index(i)
data.insert(point1+1,'*/')
Using the find() method I can find the starting index of the function while iterating over the lines. I was trying to use the balanced parenthesis method, to reach the end of the function, So when my stack is empty I will reach the end of the test_func.
This is not working in this example:
void test_func(arguments,\
arguments)
{
It is inserting */ just after the line:
/*void test_func(arguments,\
*/arguments)
{
Assuming that a "}\n" line only happens at the end of a function and always happens at the end of a function, you want something like:
in_func = False
for line in file.readlines():
line = line.strip('\r\n') # remove line breaks since print will add them
if in_func:
print("// " + line)
if line == "}":
in_func = False
elif line.startswith('void test_func('): # paren required to not match test_func2
print("// " + line)
in_func = True
else:
print(line)
Assuming that both ( / ) pairs and { / } pairs are balanced, you can look for the ) that balances the parameter list's ( and then the } that balances the body's first {.
We want to ensure that void test_func() {} etc is also caught, so I've pulled out the checks into local functions, so we start looking on the same line for the next pair of characters.
file = open(path_of_file)
data = file.readlines()
start = None
params = None
body = None
open = 0
close = 0
for index, line in enumerate(data):
def balanced(o, c):
open += line.count(o)
close += line.count(c)
return open > 0 and open = close
def checkBody():
if balanced('{', '}'):
body = index
def checkParams():
if balanced('(', ')'):
params = index
open = 0
close = 0
checkBody()
def checkStart():
if line.find('void test_func') != -1:
start = index
checkParams()
if start is None:
checkStart()
elif params is None:
checkParams()
elif body is None:
checkBody()
if start is not None and body is not None:
data.insert(start, '/*')
data.insert(body + 1, '*/')
I am working on some practice exercises with linked lists and I got stuck with one function.
My program should create a Node class, take user input with create() function (number n and then takes in n number of elements), and has a function printLinkedList(p) to print it out. So far this works well but then I should create another function where I am going to be deleting the max element (if it occurs more than once, delete the first occurrence).
I found a function findMaxElement(p) that looks for the max, however, it doesn't work along my code (for example I get AttributeError: 'Node' object has no attribute 'head' error)
class Node:
def __init__(self, x = None):
self.data = x
self.next = None
def create():
n = int(input())
if n == 0:
return None
s = input().split()
p = Node(int(s[0]))
k = p
for i in range(1, n):
t = Node(int(s[i]))
k.next = t
k = t
return p
def printLinkedList(p):
if p == None:
print('Empty')
return
s = p
while s != None:
print(s.data, end = " ")
s = s.next
print()
def findMaxElement(p):
current = p.head
#Initializing max to initial node info
maximum = p.head.data
if(p.head == None):
print("List is empty")
else:
while(True):
#If current node's info is greater than max
#Then replace value of max with current node's info
if(maximum < current.info):
maximum = current.info
current= current.next
if(current == p.head):
break
return "Maximum value node in the list: "+ str(maximum)
#Driver code
a = create()
printLinkedList(a)
Input:
6
1 7 4 2 6 7
Expected result:
1 7 4 2 6 7
1 4 2 6 7
You could just define a findMaxElement() that traverses the linked-list in the same way that the printLinkedList() function is doing it (and finds the maximum value while doing so):
def findMaxElement(p):
if p == None:
return 'Empty List!'
current = p
maximum = p.data
while current != None: # Not end of list.
if current.data > maximum:
maximum = current.data
current = current.next
return "Maximum value node in the list: " + str(maximum)
I cant figure out why line 104 keeps returning invalid syntax, can someone please point me in the right direction? Does it have something to do with the way i used elif? Sorry if this is a newbie question!
Line 104 is the else statement in the for item in workingDict.keys() loops inside printGrammar
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#get start symbol
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
start = lines[0].split('=')[0]
start = start.replace(" ", "")
#checks
#print(stringLength)
#print(filename)
#print(start)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip()
result[line[0]].append(line.split('=')[1])
return result
workingDict = str2dict("Binary.txt")
print(workingDict)
def printGrammar(result):
sentenceList = []
workList = []
workList.append(start)
i = 0
firstNT = ""
#While the worklist is not empty:
while(len(workList) != 0):
#Get and delete one potential sentence s from the worklist.
symbol = workList.pop()
#If the | s | > N, continue.
if len(str(symbol).replace(" ", "")) > int(stringLength):
continue
else:
if str(symbol) in workingDict.keys():
#append the right derivation
for item in workingDict.get(symbol):
workList.append(list(item.replace(" ", "")))
#workList.append(str(workingDict.get(symbol)))
#add derivation
print(workingDict.keys())
#If s has no nonterminals, print s and continue.
for item in workingDict.keys():
print("test")
print(''.join(item))
if len(item) != 1:
continue
#if the element is in dictionary, dont print
elif ''.join(item) in workingDict.keys():
continue
print(symbol)
#if element is not in dictionary, print
else:
print("THIS IS A TERMINAL!!")
print(item)
#Choose the leftmost nonterminal NT.
print(workList)
#For all productions NT -> rhs:
#Replace NT in s with rhs; call it tmp.
#Store tmp on worklist.
return workList
print (printGrammar(workingDict))
You need to indent the line
print(symbol)
to the same level as continue.
def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line[:position + 1]
value = running.split('\t')
for k in value:
if k != '':
running_list.append(k)
actor_name_list = value[0].split(',')
actor_name = actor_name_list[0] + actor_name_list[-1]
for i in range(len(running_list)):
if value[0] == running_list[i]:
position2 = i
movie = running_list[position2+1:]
actor_movie[actor_name] = movie
check = actor_movie.keys()
for c in range(len(check)):
if len(check[c]) < 1:
actor_movie.pop(check[c])
return actor_movie
Problem I'm having now is that only the first item of movie is added into the actor_movie anyone can help? i tried so long for this already i seriously have no idea why isn't this working...
Every time you run:
actor_movie[actor_name] = movie
you're overwriting the last movie that was associated with that actor. Try something like this instead where you're storing a list of movies, not just a single value:
try:
actor_movie[actor_name].append(movie)
except KeyError:
actor_movie[actor_name] = [movie]
There are other ways (defaultdict, dict.setdefault, etc.) to do the same thing but that should get you up and running.