Tic tac toe- What's the mistake here - python

WHAT'S THE MISTAKE HERE??
Traceback (most recent call last)
<ipython-input-51-cb088c4c5c82> in <module>
17 display_board(the_board)
18 position = player_choice(the_board)
---> 19 place_marker(the_board,Player1_marker,position)
20 if win_check(the_board,Player1_marker):
21 display_board(the_board)
<ipython-input-41-ba563e2cb168> in place_marker(board, marker, position)
1 def place_marker(board, marker, position):
----> 2 board[position] = marker
TypeError: list indices must be integers or slices, not NoneType

The lines shown state exactly what is wrong, and where. You just need to know how to interpret it:
18 position = player_choice(the_board)
---> 19 place_marker(the_board,Player1_marker,position)
1 def place_marker(board, marker, position):
----> 2 board[position] = marker
TypeError: list indices must be integers or slices, not NoneType
What you can glean from all that is that:
the position variable used in line 2 of place_marker() is set to None since that is the actual error (variables set to None are of the type NoneType, and position is the list index being complained about);
that position variable is initialised from a variable of the same name, as part of the call to place_marker() on line 19, so it too must also be set to None;
that variable (the one passed in) came from the function player_choice().
In other words, your line:
position = player_choice(the_board)
has returned None for some reason.
Unfortunately, since you haven't shown us that code for that function, we can't really dive any deeper into the analysis, but you may want to look for paths in that function that return without a value. This is a typical cause of functions returning None, such as with:
def fn(x):
if x == 1:
return 7 # This path returns 7 when 1 is passed in.
# This path returns None (implicitly) for any other value.
print(fn(1)) # Explicitly gets 7.
print(fn(2)) # Implicitly gets None.
The result of running that code is, as per the comments:
7
None

Related

Type Error: "'types.GenericAlias' object is not iterable"

I am working on a project is to convert text into numbers. (For example, "hello world" would be converted to "8 5 12 12 15 27 23 15 18 12 4").
In line 10 of my code, the for loop causes the following error message:
Traceback (most recent call last):
File "C:\Users\gabri\PycharmProjects\padding\main.py", line 15, in <module>
converter(plaintext)
File "C:\Users\gabri\PycharmProjects\padding\main.py", line 10, in converter
for n in plaintext:
TypeError: 'types.GenericAlias' object is not iterable
Process finished with exit code 1
My code is as follows:
alphabet = ("a","b","c","d","e","f","g","h","i","j","k","l","m",'n',"o","p","q","r",'s','t','u','v','w','x','y','z')
def getplaintext():
global plaintext
plaintext = list[input("Enter plaintext:.....")]
print(plaintext)
def converter(plaintext):
for n in plaintext:
print(n)
getplaintext()
converter(plaintext)
Does anybody know what is causing this error?
You need to use list with (), not [].
plaintext = list(input("Enter plaintext:.....")) # With ()
In newer versions of Python, container types such as list can be hinted directly to specify the type of the elements the container holds. By using square braces here, you create a generic type hint of a list (a "generic alias"). A generic alias for a list is not iterable, as it is not actually a list. This is what causes your error.

slice indices must be integers or None or have an __index__ method in udacity self driving

in udacity self driving https://github.com/udacity/self-driving-car/tree/master/vehicle-detection/u-net the method get_mask_seg(img, bb_boxes_f) gives slice indices must be integers or none or have an index method
<ipython-input-58-b0cc385c742b> in <module>()
2
3 training_gen = generate_train_batch(df_vehicles,10)
----> 4 batch_img,batch_mask = next(training_gen)
<ipython-input-55-1399e4d6a92a> in generate_train_batch(data, batch_size)
12 scale_range=50
13 )
---> 14 img_mask = get_mask_seg(img,bb_boxes)
15 batch_images[i_batch] = img
16 batch_masks[i_batch] =img_mask
<ipython-input-51-b5ad142378f0> in get_mask_seg(img, bb_boxes_f)
8 bb_box_i = [bb_boxes_f.iloc[i]['xmin'],bb_boxes_f.iloc[i]['ymin'],
9 bb_boxes_f.iloc[i]['xmax'],bb_boxes_f.iloc[i]['ymax']]
---> 10 img_mask[bb_box_i[1]:bb_box_i[3],bb_box_i[0]:bb_box_i[2]]= 1
11 img_mask = np.reshape(img_mask,(np.shape(img_mask)[0],np.shape(img_mask)[1],1))
12 return img_mask
TypeError: slice indices must be integers or None or have an __index__ method
This code is breaking due to a relatively recent change in NumPy. To fix it, you'll need to ensure that the index array bb_box_i is an integer array. The easiest way to do that is probably to add a line of code that does bb_box_i = bb_box_i.astype('int') before indexing into the img_mask array.
this code works better
img_mask[int(bb_box_i[1]):int(bb_box_i[3]),int(bb_box_i[0]):int(bb_box_i[2])]= 1

Counting the real number of arguments in python

Is there any way to count the real number of arguments passed to a function in python, even when some defaults values are set? I'm trying to write a function, which replaces a certain range of a text file with 0 (or an offset value), but it doesn't work because python returns the number of arguments including the arguments which are not passed.
The input file is like this:
foo.txt
0
1
2
3
4
5
6
7
8
9
10
11
Here is the code:
import os
import numpy as np
from inspect import signature
def substitute_with(FILE, start, end=10, offset=0):
sig = signature(substitute_with)
params = sig.parameters
print('len(params): %d' % len(params))
filename, file_extension = os.path.splitext(FILE)
file_i = FILE
file_o = filename + '_0' + file_extension
Z = np.loadtxt(file_i)
with open(file_o, "w") as fid:
length_Z = len(Z)
print('length_Z: %d' % length_Z)
if(len(params) < 3): # gives me 4, but actually, I need 2 here!
end=length_Z
X = np.concatenate([np.ones((start)), np.zeros((end-start)), np.ones((length_Z-end))])
Y = np.concatenate([np.zeros((start)), np.ones((end-start)), np.zeros((length_Z-end))])*offset
A=Z.T*X+Y
for i in range(0, length_Z):
fid.write('%d\n' % (A[i]))
#substitute_with('foo.txt',4,8)
#substitute_with('foo.txt',4,8,2)
substitute_with('foo.txt',4)
... This works only when the 3rd argument 'end' is passed. Without the 3rd argument, from 4 through the end (11) are supposed to be replaced with 0. But, in reality, from 4 through 9 are replaced with 0.
I reluctantly set a default value (=10) to end, otherwise the compiler gives me the following error:
TypeError: substitute_with() missing 1 required positional argument: 'end'
So, how would you guys solve this? Please don't tell me to check the length of the file first and then give it to the function. It should be done inside the function. In MATLAB, 'nargin' returns the real number of arguments, so this kind of logic would work easily. If python cannot do this, it's gonna be a shame.
Just use None as the default for end:
def substitute_with(FILE, start, end=None, offset=0):
...
if end is None:
end = length_Z
...

Trouble with for loops

We just learned for loops in class for about five minutes and we were already given a lab. I am trying but still not getting what I need to get. What I am trying to do is take a list of integers, and then only take the odd integers and add them up and then return them so if the list of integers was [3,2,4,7,2,4,1,3,2] the returned value would be 14
def f(ls):
ct=0
for x in (f(ls)):
if x%2==1:
ct+=x
return(ct)
print(f[2,5,4,6,7,8,2])
the error code reads
Traceback (most recent call last):
File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable
Just a couple of minor mistakes:
def f(ls):
ct = 0
for x in ls:
# ^ Do not call the method, but just parse through the list
if x % 2 == 1:
ct += x
return(ct)
# ^ ^ parenthesis are not necessary
print(f([2,5,4,6,7,8,2]))
# ^ ^ Missing paranthesis
You're missing the parenthesis in the function call
print(f([2,5,4,6,7,8,2]))
rather than
print(f[2,5,4,6,7,8,2])

Systematically moving through every number in a numpy array

I have a 500x500 array and I am trying to write a variable called "coordinate" that will pick out each value and then apply it to a function but I keep getting the output,
AttributeError Traceback (most recent call last)
/home/graham/<ipython-input-17-cc6ce0649eda> in <module>()
31 pass
32
---> 33 finished_array = rand_array_color(rand_array)
34
35 finished_image = Image.fromarray(finished_array)
/home/graham/<ipython-input-17-cc6ce0649eda> in rand_array_color(rand_array)
23 from PIL import Image
24 for ii in numpy.nditer(rand_array):
---> 25 coordinate = tuple(map(int, rand_image[ii,:]))
26 if ii < 128:
27 print "false"
/usr/lib/python2.7/dist-packages/PIL/Image.pyc in __getattr__(self, name)
510 new['data'] = self.tostring()
511 return new
--> 512 raise AttributeError(name)
513
514 ##
AttributeError: __getitem__
Here is my code
from PIL import Image
from numpy import random
im = Image.open('/home/graham/Desktop/Experiment/gwarner/labeled_photos/photos/003030.png')
rand_array = numpy.random.randint(255, size=(500,500)).astype('uint8')
rand_image = Image.fromarray(rand_array)
def rand_array_color(rand_array):
from PIL import Image
for ii in numpy.nditer(rand_array):
coordinate = tuple(map(int, rand_image[ii,:]))
if ii < 128:
newvalue = rand_image.putpixel(coordinate(a,ii), im.getpixel(coordinate(a,ii)))
return newvalue
else:
pass
finished_array = rand_array_color(rand_array)
I've also been fiddling around with another version of coordinate,
coordinate = tuple(int(rand_array[ii,0]),int(rand_array[ii,1])
but it just returns,
NameError: name 'ii' is not defined
Can anyone tell me how to fix one of these or recommend another one that will work?
The reason you cannot get the iith row of rand_image using rand_image[ii,:] is because rand_image is a PIL Image object, and doesn't have the same indexing access that an array has. If you want to get the iith row, you must use rand_array[ii] (I've left off the trailing colon ,: isn't required)
This appears to be similar to your
another version of coordinate
which should work because you're using the array instead of the Image. My guess is that you've not replaced it in exactly the same place as the first version, perhaps somewhere outside of the for ii in ... loop, because ii is only properly defined within that loop.
As you've defined it, coordinate is not a function, it's a tuple of length 2. But you call it as a function when you write coordinate(a, ii). Rather, you probably just want to use coordinate there (I'm not sure what a is supposed to be.
The function .putpixel does not return anything, so that when you say:
newvalue = rand_image.putpixel(...)
newvalue will be None (the 'empty' object in python). Perhaps you want to do this:
rand_image.putpixel(...)
return rand_image
without setting the newvalue and trying to return it, but instead changing the pixel in the rand_image and returning the new rand_image.
As a side note, you should not call int() on a numpy array, instead, if you want the type of each element in the array to be int, you should either use .astype as you did above, or initiate it as an int in the first place. Once it starts as an int, it should stay that way unless you cast it somehow (which you haven't done in this script).
As a final note this process could probably be done a lot faster using numpy (not using pure python loops) but I'm not sure exactly what you're trying to do. If you edit your question to explain a little bit what you're trying to do so that I can read the code with some context, I could help. For example, what is a supposed to be in the newvalue = ... line?

Categories

Resources