I have the following code based on Python School:
EDIT: fixed the indentation of "position" and "return found", and used "raw_input
def linearSearch(item,my_list):
found = False
position = 0
while position < len(my_list) and not found:
if my_list(position) == item:
found = True
position = position + 1
return found
bag = ['book','pencil','pen','note book','sharpner','rubber']
item = raw_input('What item do you want to check for in the bag?')
itemFound = linearSearch(item,bag)
if itemFound:
print('Yes, the item is in the bag')
else:
print('Your item seems not to be in the bag')
When I ran the program, I got the following:
What item do you want to check for in the bag?pencil
Traceback (most recent call last):
File "test.py", line 11, in <module>
item = input('What item do you want to check for in the bag?')
File "<string>", line 1, in <module>
NameError: name 'pencil' is not defined
EDIT: Getting the following error after the edits, although tried to put the item name between quotes
Traceback (most recent call last):
File "test.py", line 12, in <module>
itemFound = linearSearch(item,bag)
File "test.py", line 5, in linearSearch
if my_list(position) == item:
TypeError: 'list' object is not callable
Why am I getting this error?
Thanks.
my_list is a list, index it not call it as a function, so it should be :
if my_list[position] == item:
Another thing, if you are looking for one particular item in my_list, than just return from linearSearch as soon as you found it, no need to keep iterating through the rest of my_list:
if my_list[position] == item:
found = True
return found
The problem is, that you are using python2 and this is python3 code. So it would be best for you to install python3 and this code should run OK. Or in python2 you could you the raw_input function instead of input.
Replace input with raw_input to get a string: input tells Python 2 to evaluate the input string.
That said, your code has more problems: for instance, you increment the position in the wrong place.
I guess this some kind of homework, otherwise there is no need to implement this function just do item in bag. Anyway about the function, there is no need to keep track of the index like that, use range or xrange for that, or having a variable found, just do return True when found and at the end of the function do return False
def linearSearch(item,my_list):
for position in xrange(len(my_list)):
if my_list[position] == item:
return True
return False
you can also use the fact that a list is iterable and do
def linearSearch(item,my_list):
for elem in my_list:
if elem == item:
return True
return False
Related
Can anyone help me fix this error I keep getting please. I have tried to look for a solution but I can't find any. Below is the error message and also part of my coding
Please enter your class Y or X or Z: Y
Traceback (most recent call last):
File "/Volumes/LIAM'S USB/DEV6 FINAL.py", line 118, in <module>
score=int(items[1])
IndexError: list index out of range
results={
start=True
while (start):
pupil_class=input("\nPlease enter your class Y or X or Z: ")
if pupil_class == ("Y"):
classfile="Class_Y_results.txt"
elif pupil_class == ("X"):
classfile="Class_X_results.txt"
elif pupil_class == ("Z"):
classfile="Class_Z_results.txt"
f=open(classfile,'r')
for line in f:
items=line.split(',')
name=items[0]
score=int(items[1])
if name in results:
results[name].append(score)
else:
results[name]=[]
results[name].append(score)
f.close()
A certain line in your Class_Y_Results.txt only has one entry (not separated by commas), hence the list returned by items=line.split(',') only has a length of 1 (or maybe 0), causing score=int(items[1]) to throw an IndexError.
Sample:
>>> a = "foo,bar"
>>> b = "foo"
>>> len(a.split(','))
2
>>> len(b.split(','))
1
>>> a.split(',')[1]
'bar'
>>> b.split(',')[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
There is probably an empty like in one of your files. This will not contain a comma, so you will not have an item[1], and this produces the error message you see.
Check how many fields you get back from the split to solve this.
I know this question has been asked a lot before, but I can't seem to find any place in my code where I'm binding my list a to an integer value. I've changed all my variable names but to no avail.
Here's the entire code I'm running:
import sys
def powerset(a):
# returns a list of all subsets of the list a
if (len(a) == 0):
return [[]]
else:
allSubsets = [ ]
for subset in powerset(a[1:]):
allSubsets += [subset]
allSubsets += [[a[0]] + subset]
return allSubsets
if __name__ == '__main__':
no_test = int(sys.stdin.readline())
for i in xrange(no_test):
xor_res = 0
len = int(sys.stdin.readline())
numbers_array = map(int,sys.stdin.readline().split())
numbers = []
for i in numbers_array:
numbers.append(i)
maxset = powerset(numbers)
for set in maxset:
if len(set) != 0:
temp = 0
for i in set:
temp = temp^i
xor_res = xor_res ^ temp
print xor_res
And this is the error I'm getting:
Traceback (most recent call last):File "solution.py", line 24, in <module>maxset = powerset(numbers)File "solution.py", line 6, in powerset if (len(a) == 0):TypeError: 'int' object is not callable
Can someone please tell me what's going wrong here?
Thanks!
You've created a variable called len that shadows the built in function len():
len = int(sys.stdin.readline())
When you try to call the len function throughout your code, the interpreter finds the len variable first and tries to call it like a function. Since it's an int, this can't be done and we see the error.
To solve your problem, call your variable something different. In general, avoid creating variables with names like "len", "list", "map", etc, since using these names shadows the built in ones.
while trying to print the sequence of power(3,2^n), i.e, 3^2,3^4,3^8 , I tried using the following line using range function.Is it possible to use the range function to get the desired output? If so please let me know where did I went wrong.
for i in range(3,1000, i*(i-1)): print (i*i)
for example, the following output is expected for i=3,9,81
i*i:=9,81,6561
But the error is :
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
for i in range(3,1000, i*(i-1)): print (i*i)
ValueError: range() arg 3 must not be zero
How can the step value be zero in this case?
You could use a list comprehension to build a list of all of your powers:
mylist = [3**(2**n) for n in range(1,10)] # or whatever range
and then iterate through the comprehension to print all of your results if you want. You can do other stuff with your results in this loop instead of print them.
for item in mylist:
print(item) # print each item on a new line
i = 2
while 3**i < 1000:
print(3**i)
i *= 2
I'm pretty sure what you want to do is very similar to this question. You want to be calling a list comprehension:
powersofthree = [3**(2**i) for i in range(10)]
which returns
[3, 9, 81, ... ]
Then you can print the result at you leisure.
Also, as many in the comments have pointed out, you used i before it was defined, which is why you encountered an error
I have a problem that I am working on. The goal of the problem is to take the string placeholder i. If i is an even placeholder, replace the letter at i with the letter at i -1. If the i place holder is odd, then replace the letter i with the letter at i +1.
Here is my code so far:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
str(s).replace(i,((i-1)))
if i % 2 != 0:
str(s).replace(i,((i+2)))
print (s)
My error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
str(s).replace(i,((i-1)))
TypeError: Can't convert 'int' object to str implicitly
update!!
New code based on answers:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
s = str(s).replace(s(i),(s(i-1)))
else:
s = s.replace(s(i), s(i + 1))
print (s)
However I still have the following errors:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
s = str(s).replace(s(i),(s(i-1)))
TypeError: 'str' object is not callable
Any ideas? thank you
Use s[i] instead of s(i), and likewise for the other indexes.
There are two things here:
str.replace does not automatically stringify its arguments. You need to manually convert them into strings. Remember that: "Explicit is better than implicit."
str.replace does not work in-place because strings are immutable in Python. You need to reassign s to the new string object returned by str.replace.
Your code should be:
s = s.replace(str(i), str(i-1))
Also, you can replace if i % 2 != 0: with else: since the condition of the second if-statement can only be true if the first is false:
if i % 2 == 0:
s = s.replace(str(i), str(i-1))
else:
s = s.replace(str(i), str(i+1))
Regarding your edited question, you are trying to call the string s as a function by placing parenthesis after it. You need to use square brackets to index the string:
>>> 'abcde'[0]
'a'
>>> 'abcde'[3]
'd'
>>>
In your case it would be:
s = s.replace(s[i], s[i-1])
As a general rule of thumb, parenthesis (...) are for calling functions while square brackets [...] are for indexing sequences/containers.
For this function for some reason I get errors, and I can't figure out what's wrong with it.
def bubbleSort(lis):
for pas in lis:
for i in pas:
if lis[i] > lis[i+1]:
lis[i],lis[i+1] = lis[i+1],lis[i]
I get the following errors:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
bubbleSort(hello)
File "C:/Users/albert/Desktop/test.py", line 4, in bubbleSort
for i in pas:
TypeError: 'int' object is not iterable
Assuming lis is a list of integers, pas will be a single integer. for i in pas: fails because there are no is in a single integer.
Bubble sort is typically done with an outer loop that goes while there are any changes, and an inner loop that iterates over n-1 indices, not list elements. You can find a standard implementation in many places, here's the rosetta code one:
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return None