Select a random object in a list - python

So I am trying to make a program that selects a random object in a list and then refer to that object.
Here's my code:
for hour in c.routine:
a = hour.hour
if hour.task == "idle":
if c.spouse:
if c.spouse[0].routine[a].task == "idle":
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(family_daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
if c.kids:
for k in range(len(c.kids)):
if c.kids[k].routine[a].task == "idle":
c.kids[k].routine[a].task = x
c.kids[k].routine[y].task = x
else:
x = random.choice(family_nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
elif c.lover:
pick = random.choice(c.lover)
if c.lover[pick].routine[a].task == "idle":
c = random.randint(0,2)
if c == 1:
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
else:
x = random.choice(nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
When I run this code I get an error:
Traceback (most recent call last): File
"C:\Users\Patrick\Pictures\Python\Westhope\2.0\exe.py", line 9, in
<module>
routine_creation() File "C:\Users\Patrick\Pictures\Python\Westhope\2.0\world_init.py", line
721, in routine_creation
if c.lover[pick].routine[a].task == "idle": TypeError: object cannot be interpreted as an index
Seems to be the way I try to refer to the pick but I am not sure why or how to fix it...

That's a lot of code to comb through. Could you make a smaller example?
According to your stack trace, the problem is at
if c.lover[pick].routine[a].task == "idle"
Okay, i see it. Change
pick = random.choice(c.lover)
if c.lover[pick].routine[a].task == "idle":
to:
pick = random.choice(c.lover)
if pick.routine[a].task == "idle":
you already have a random choice made (it is contained in pick), so you can just use that directly.

If you also need the index, use random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])

Related

I want the program to loop every time the sensor detects anything in 15cm

This is the code:
def check_ultra():
global arduinoSerialData, y, i, x
while True:
if arduinoSerialData.inWaiting() > 1:
myData = arduinoSerialData.readline()
myData = str(myData)
myData = myData.replace("b'", '')
myData = myData.replace("\\r\\n'", str(0))
myData = myData.replace("\\r00.000", str(0))
myData = myData.replace("\\r00.000", str(0))
if "c" in myData:
myData = myData.replace("c", str(0))
if y == 1:
y = 3
if float(myData) > 15:
x = 0
return y, x
else:
if float(myData) < 15 and float(myData) > 1:
y = 1
x = 0
return y, x
elif "a" in myData:
myData = myData.replace("a", str(0))
if y == 2:
y = 3
if float(myData) > 15:
x = 0
return y, x
else:
if float(myData) < 15 and float(myData) > 1:
y = 2
x = 0
return y, x
else:
y = 0
return y
set_servo1_angle(0)
set_servo2_angle(90)
go_out_count = 0
m1 = 0
count = 3
y = 0
i = 0
x = 0
while y == None or y == 0 or x == 1:
# i = 0
# y = None
check_ultra()
if y == 1 and x == 0:
print("1")
sleep(2)
elif y == 2 and x == 0:
print('2')
sleep(2)
What this currently does is it prints 1 every time sensor 1 is blocked, but then it ends the code. I want to make it such that every time I block a sensor, it prints the corresponding print statement, no matter how many times I block the sensor. I have tried adding many variables to help but they didnt work. How do I make the loop keep repeating?
Your outer-most loop has the following condition: y==None or y==0 or x==1. The if statements in it are only going to print if all of those conditions are False. That means the loop is guaranteed to terminate on the first printout.
If you want the loop to keep going indefinitely, ignore everything and keep going. Replace the loop with
while True:
check_ultra()
...
On an unrelated note, try to avoid globals. They may have unpredictable side effects when you set them in long-forgotten places, and generally make the code harder to maintain. Use arguments and return values instead.
For example:
def check_ultra(arduinoSerialData, x, y):
while True:
if arduinoSerialData.inWaiting() > 1:
myData = arduinoSerialData.readline()
myData = str(myData)
myData = myData.replace("b'", '')
myData = myData.replace("\\r\\n'", str(0))
myData = myData.replace("\\r00.000", str(0))
myData = myData.replace("\\r00.000", str(0))
if "c" in myData:
myData = float(myData.replace("c", "0"))
if y == 1:
if myData > 15:
return 0, 3
return x, 3
elif 1 < myData < 15:
return 0, 1
return x, y
elif "a" in myData:
myData = float(myData.replace("a", "0"))
if y == 2:
if myData > 15:
return 0, 3
elif 1 < myData < 15:
return 0, 2
return x, y
else:
return x, 0
You would call it as
x, y = check_ultra(arduinoSerialData, x, y)
'break' statement ends the while loop, so try replacing it with 'pass', like this:
elif y == 2:
print('2')
pass

Python, google colab

x=str(input('Where to'))
y=str(input('Which uber'))
if x == ('Cleveland'):
print('400 miles')
if x == ('Detriot'):
print('500 miles')
if x == ('Sandusky'):
print('100 miles')
if x == ('Lakewood'):
print('200 miles')
if x == ('Rocky River'):
print('550 miles')
elif x == ('none'):
print(compares)
compares = x * y
Question: if i made the user type in a new value for x how i would multiply that by the y they gave?
You can use dictionary
Note: by default input() returns string no need to convert it into string.
x = input('Where to: ')
y = input('Which uber: ')
cities = {'Cleveland': 400, 'Detriot': 500, 'Sandusky': 100, 'Lakewood': 200, 'Rocky River': 550}
if x in cities and y in cities:
compares = cities[x] * cities[y]
print(compares)
else:
print('Select valid location')

How do I fix this list being out of range?

I'm making a game in which the player can move on a 8x8 grid, but I'm getting an error in which the values are out of range.
Here is my code:
def player_movement():
grid0 = []
grid1 = []
i = 0
n = 0
while i < 8: #this makes the grid
grid0.append("0")
i += 1
while n < 8:
grid1.append(grid0.copy())
n += 1
grid1[0][0] = "X" # this places the player on the top left of the grid
for l in grid1:
print(l)
while True:
player_movex = int(input("Move right how many?"))# instructions to move the player
player_movey = int(input("Move down how many??"))
for y, row in enumerate(grid1): #this finds the player on the grid
for x, i in enumerate(row):
if i == "X":
grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]
for j in grid1: #prints out the grid in the 8x8 format
print(j)
and I am entering values that are within the lists' range i.e. 0-7.
This is the error that appears on my screen:
Traceback (most recent call last):
File "D:\Python\Treasure Hunt game.py", line 83, in <module>
player_movement()
File "D:\Python\Treasure Hunt game.py", line 78, in player_movement
grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]
IndexError: list index out of range
The reason being the loops are executed even after the movement is made.
def player_movement():
grid0 = []
grid1 = []
i = 0
n = 0
while i < 8: #this makes the grid
grid0.append("0")
i += 1
while n < 8:
grid1.append(grid0.copy())
n += 1
grid1[0][0] = "X" # this places the player on the top left of the grid
for l in grid1:
print(l)
while True:
player_movex = int(input("Move right how many?"))# instructions to move the player
player_movey = int(input("Move down how many??"))
done = False
for y, row in enumerate(grid1): #this finds the player on the grid
for x, i in enumerate(row):
if i == "X":
print(y, x)
grid1[y][x], grid1[y + player_movey][x + player_movex] = "0", "X"
done = True
if done == True:
break
if done == True:
break
for j in grid1: #prints out the grid in the 8x8 format
print(j)
player_movement();
I would rather code as follows:
def player_movement():
n = 8
grid = [['0'] * n for _ in range(n)]
m = 'x'
grid[0][0] = m # this places the player on the top left of the grid
for i in grid:
print(i)
while True:
# instructions to move the player
player_movex = int(input("Move right how many? "))
player_movey = int(input("Move down how many?? "))
move(grid, m, n, player_movey, player_movex)
for j in grid: # prints out the grid in the 8x8 format
print(j)
def move(grid, m, n, move_y, move_x):
for y, row in enumerate(grid): # this finds the player on the grid
for x, i in enumerate(row):
if i == m:
a, b = y + move_y, x + move_x
if a >= n:
print(f'Sorry, move {move_y} down will out of range!\n')
return
if b >= n:
print(f'Sorry, move {move_x} right will out of range!\n')
return
grid[y][x], grid[a][b] = grid[a][b], grid[y][x]
return
player_movement()

TypeError: 'NoneType' object is not iterable when implementing Perceptron, see code below

I have a problem with my perceptron codes.I receive this when I execute my code. I checked my two txt files and I am pretty sure the two of them are definitely ok. So can someone help? Thanks a lot
Traceback (most recent call last):
File "perceptron.py", line 160, in <module>
test()
File "perceptron.py", line 133, in test
w,k,i = p.perceptron_train('train.txt')
TypeError: 'NoneType' object is not iterable
Here is my code
import numpy as np
import matplotlib.pyplot as plt
class Data():
def __init__(self,x,y):
self.len = len(x)
self.x = x
self.y = y
class Perceptron():
def __init__(self,N,X):
self.w = np.array([])
self.N = N
self.X =X
def prepare_training(self,file):
file = open(file,'r').readlines()
self.dic = set([])
y = []
vocab = {}
for i in range(len(file)):
words = file[i].strip().split()
y.append(int(words[0])*2-1)
for w in set(words[1:]):
if w in vocab:
vocab[w].add(i)
if i < self.N and len(vocab[w]) >= self.X:
self.dic.add(w)
elif i < self.N:
vocab[w] = set([i])
x = np.zeros((len(file),len(self.dic)))
self.dic = list(self.dic)
for i in range(len(self.dic)):
for j in vocab[self.dic[i]]:
x[j][i] = 1
self.training = Data(x[:self.N],y[:self.N])
self.validation = Data(x[self.N:],y[self.N:])
return x,y
def update_weight(self,x,y):
self.w = self.w + x * y
def perceptron_train(self,data):
x,y = self.prepare_training(data)
self.w = np.zeros(len(self.dic),int)
passes = 0
total_passes = 100
k = 0
while passes < total_passes:
print('passes:',passes)
mistake = 0
for i in range(self.N):
check = y[i] * np.dot(self.w,x[i])
if (check == 0 and (not
np.array_equal(x[i],np.zeros(len(self.dic),int)))) or (check < 0):
self.update_weight(x[i],y[i])
mistake += 1
k += 1
passes += 1
print('mistake:',mistake)
if mistake == 0:
print('converge at pass:',passes)
print('total mistakes:', k)
return self.w, k, passes
def perceptron_error(self,w,data):
error = 0
for i in range(data.len):
if data.y[i] * np.dot(w,data.x[i]) < 0:
error += 1
return error/data.len
def test(self,report):
x = np.zeros(len(self.dic),int)
for i in range(len(self.dic)):
if self.dic[i] in report:
x[i] = 1
if np.dot(self.w,x) > 0:
return 1
else:
return 0
def perceptron_test(self,data):
test = open(data,'r').readlines()
y = []
mistake = 0
for t in test:
y0 = int(t.strip().split()[0])
report = set(t.strip().split()[1:])
r = self.test(report)
y.append(r)
if (y0 != r):
mistake += 1
return y,mistake/len(test)
def predictive_words(self):
w2d = {}
for i in range(len(self.dic)):
try:
w2d[self.w[i]].append(self.dic[i] + " ")
except:
w2d[self.w[i]] = [self.dic[i] + " "]
key = list(w2d.keys())
key.sort()
count = 0
most_positive = ""
most_negative = ""
for i in range(len(key)):
for j in range(len(w2d[key[i]])):
most_negative += w2d[key[i]][j]
count += 1
if count == 5:
break
if count == 5:
break
count = 0
for i in range(len(key)):
for j in range(len(w2d[key[len(key)-i-1]])):
most_positive += w2d[key[len(key)-i-1]][j]
count += 1
if count == 5:
break
if count == 5:
break
return most_positive,most_negative
def test():
p = Perceptron(500,30)
w,k,i = p.perceptron_train('train.txt')
print(p.perceptron_error(w,p.validation))
normal,abnormal = p.predictive_words()
print('Normal:\n',normal)
print('Abnormal:\n',abnormal)
print(p.perceptron_test('test.txt'))
def plot_error():
x = [100,200,400,500]
y = []
for n in x:
p = Perceptron(n,10)
w,k,i = p.perceptron_train('train.txt')
y.append(p.perceptron_error(w,p.validation))
plt.plot(x,y)
plt.show()
def plot_converge():
x = [100,200,400,500]
y = []
for n in x:
p = Perceptron(n,10)
w,k,i = p.perceptron_train('train.txt')
y.append(i)
plt.plot(x,y)
plt.show()
test()
perceptron_train has the implicit return value None if mistakes!=0, so that's what you're seeing here.

Python: Module returning "None" values into created file

I'm stuck with my program. Basically I have to call a module and have that module create a file with values that I refer back to later on in program. However, the module doesn't work correctly and I'm not sure where I'm going wrong. Thanks in advance. Here is my current program.
import math
import mymath
def main():
getData()
summer()
def getData():
powerfile = open("myfile.dat","w")
fin = open("sample.dat","r")
done = False
while not done:
x = int(fin.readline())
if x < 0:
done = True
else:
y = int(fin.readline())
answer = mymath.powerval(x,y)
answer = str(answer)+'\n'
powerfile.write(answer)
powerfile.close()
def summer():
file_in = open("myfile.dat","r")
total = 0
count = 0
for a in file_in:
number = int(a)
count += 1
total += number
file_in.close()
print("The final sum was", total)
close = input('')
main()
And my mymath module:
import math
def powerval(x,y):
if x > y:
big = x
else:
small = x
if x > y:
small = y
else:
big = y
answer = pow(big, small)
The powerval function has no return statement.
def powerval(x,y):
if x > y:
big = x
else:
small = x
if x > y:
small = y
else:
big = y
answer = pow(big, small)
return answer # <----

Categories

Resources