Appending item to list - list

I am trying to append an item (card) to a list (player_hand) however it is giving me an error stating "TypeError: 'NoneType' object is not iterable"
My code:
def player_turn(player_hand, deck):
hand_value = get_hand_value(player_hand)
print('Player:', hand_value)
cards.display_cards(player_hand)
if hand_value == MAX:
choice = None
if hand_value < MAX:
choice = get_player_choice()
while choice == HIT:
player_hand = player_hand.append(deck.pop())
hand_value = get_hand_value(player_hand)
if hand_value <= MAX:
print(f"Player: {hand_value}")
get_player_choice()
else:
print(f"Player: {hand_value}, BUSTED!")
Cpde for the get_hand_value function:
def get_hand_value(hand):
total = 0
for card in hand:
total += card.value
for card in hand:
if total > MAX:
if card.is_ace():
total -= 10
return total
error i am receiving:
in player_turn
hand_value = get_hand_value(player_hand)
hand = None
def get_hand_value(hand):
total = 0
> for card in hand:
E TypeError: 'NoneType' object is not iterable
blackjack.py:72: TypeError

Related

Simple function dosen't return what i want

I want this function to give me around 10 values split in 2 list, but it only gives me 1 value. Why?
import random
def chance():
count = 0
while count < 10:
list11 = []
list22 = []
num = random.randint(1,11)
if num > 6:
list11.append(num)
elif num < 6:
list22.append(num)
count += 1
print list11
print list22
chance()

maximum recursion depth error?

So I'm really new to this (3 days) and I'm on code academy, I've written this code for one of the activities but when I run it it displays maximum recursion depth error, I'm running it in the python console of code academy and simultaneously on my own ipython console. The hint on the page is not helpful, can anybody explain how to fix this?
Thanks
def hotel_cost(nights):
return (nights * 140)
def plane_ride_cost(city):
if plane_ride_cost("Charlotte"):
return (183)
if plane_ride_cost("Tampa"):
return (220)
if plane_ride_cost("Pittsburgh"):
return (222)
if plane_ride_cost("Loas Angeles"):
return (475)
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)
Maybe:
def plane_ride_cost(city):
if city == "Charlotte":
return (183)
if city == "Tampa":
return (220)
if city == "Pittsburgh":
return (222)
if city == "Los Angeles":
return (475)
The error was:
The plane_ride_cost(city) called plane_ride_cost("Charlotte") in every recursion step.
Not the best, but a better approach:
def hotel_cost(nights):
return nights * 140
plane_cost = {
'Charlotte' : 183,
'Tampa' : 220,
'Pittsburgh' : 222,
'Los Angeles' : 475,
}
def plane_ride_cost(city):
if city not in plane_cost:
raise Exception('City "%s" not registered.' % city)
else:
return plane_cost[city]
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return hotel_cost(nights) + plane_ride_cost(city) + rental_car_cost(days)

'function' object has no attribute '__getitem__'

This is my first time coding. I'm doing it as ab elective module. I have to program an ai_player to go from playing randomly to winning and I'm stuck. Any advice would be appreciated. The game is Connect 4. i keep getting "object has no attribute" error.
import random
import time
def board():
for i in range(0, 8, 1):
for j in range(0, 10, 1):
board[i][j] = 0
return board
def move(board, valid_move):
start_time = time.time()
x = 0
while x == 0:
i = range(7, -1, -1)
j = range(0, 10, 1)
first_move = board[i][j]
board[7][4] = 1
if board[i-1][j] == 0: #above
first_move = [i, j]
x = 1
print " valid above"
return j
elif (board[i][j+1] == 0 and (i <= 7 and j <= 9)) or (board[i-1][j+1] == 0 and (i <= 7 and j <= 9)) or (board[i-1][j+1] == 0 and (i <= 7 and j <= 9)): #right
first_move = [i, (j+1)]
x = 1
print " valid right"
return (j+1)
elif board[i][j-1] == 0 or board[i-1][j-1] == 0 or board[i-1][j-1] == 0: #left
first_move = [i, (j-1)]
x = 1
print " valid left"
return (j-1)
else:
r = random.randint(0, 7)
c = random.randint(0, 9)
first_move = [r, c]
x = 1
print " random move"
return c
end_time = time.time() - start_time
print end_time
return first_move
File "F:/5. Fifth year/1st Semester/MPR 213 2016/Project 2016/attempts.py", line 20, in board
board[i][j] = 0
TypeError: 'function' object has no attribute '__getitem__'
It looks like you're trying to create a multidimensional list called board. This is not how you do that though, what you've actually done is created a function called board, and then you try to index that function, which fails since it's not a list.
To create board, use something like
board = [[0] * 10 for i in range(0, 8)]

python function to split a list by indexes

I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes)
Am I over-thinking this?
Code:
def lindexsplit(List,*lindex):
index = list(lindex)
index.sort()
templist1 = []
templist2 = []
templist3 = []
breakcounter = 0
itemcounter = 0
finalcounter = 0
numberofbreaks = len(index)
totalitems = len(List)
lastindexval = index[(len(index)-1)]
finalcounttrigger = (totalitems-(lastindexval+1))
for item in List:
itemcounter += 1
indexofitem = itemcounter - 1
nextbreakindex = index[breakcounter]
#Less than the last cut
if breakcounter <= numberofbreaks:
if indexofitem < nextbreakindex:
templist1.append(item)
elif breakcounter < (numberofbreaks - 1):
templist1.append(item)
templist2.append(templist1)
templist1 = []
breakcounter +=1
else:
if indexofitem <= lastindexval and indexofitem <= totalitems:
templist1.append(item)
templist2.append(templist1)
templist1 = []
else:
if indexofitem >= lastindexval and indexofitem < totalitems + 1:
finalcounter += 1
templist3.append(item)
if finalcounter == finalcounttrigger:
templist2.append(templist3)
return templist2

Python (Django) Class that aliases/overloads list index behavior to attributes

I have a class that stores information about a week:
from django.db import models
#A django model, so can't subclass list (at least not easily)
class MyWeek(models.Model):
sunday = "foo"
monday = "foo"
tuesday = "foo"
wednesday = "foo"
thursday = "foo"
friday = "foo"
saturday = "foo"
I'd like to be able to access these attributes as if the class was a list:
aweek = Myweek()
#I want this
aweek[0] = "bar"
myvar = aweek[1]
#To be shorthand for this
aweek.monday = "bar"
myvar = aweek.tuesday
#and of course
aweek[7]
ValueError/IndexError: Week indexes monday to 0 and sunday to 6, there is no 7
Everything about python makes think this is possible and easy, if only I know the right set of things to overload.
I've thought of #property, but that doesn't help so much because I want to be able to use a variable to access it:
#I want to be able to do this
aweek[somevar] = "bar"
#and via property, i'd have to use exec
#and this is just ugly and scary from an "oh god, what could somevar be" perspective
exec("aweek.%s = 'bar'" % somevar)
#Or, as kojiro pointed out below, it could be done like this:
setattr(aweek, "somevar", "bar")
Thanks.
Edit: Working code, hattip to kojiro for helping with the right methods to overload:
# overload []
def __getitem__(self, index):
index = int(index) #will raise value error if uncoercable, this is desired behavior
if index < 0 or index > 6:
raise ValueError("Requires an integer index between 0 and 6, monday is 0 sunday is 6")
if index == 0:
return self.monday
elif index == 1:
return self.tuesday
elif index == 2:
return self.wednesday
elif index == 3:
return self.thursday
elif index == 4:
return self.friday
elif index == 5:
return self.saturday
elif index == 6:
return self.sunday
# overload set []
def __setitem__(self, index, item):
index = int(index) #will raise value error if uncoercable, this is desired behavior
if index < 0 or index > 6:
raise ValueError("Requires an integer index between 0 and 6, monday is 0 sunday is 6")
if index == 0:
self.monday = item
return
elif index == 1:
self.tuesday = item
return
elif index == 2:
self.wednesday = item
return
elif index == 3:
self.thursday = item
return
elif index == 4:
self.friday = item
return
elif index == 5:
self.saturday = item
return
elif index == 6:
self.sunday = item
return
To create a list-like object in python you need to create the following methods:
__len__, __getitem__, __setitem__, __delitem__, __iter__, and __contains__
Link to explanatory example.