Reputation: 35
This piece of code runs fine for the first runthrough, yet when it gets to the second iteration an error appears saying "list index out of range", despite it being happy with it the first time.Does the indexing need resetting?
while pile_counter < 3:
pile_one= operator.itemgetter(0,3,6,9,12,15,18)(cards)
pile_two= operator.itemgetter(1,4,7,10,13,16,19)(cards)
pile_three= operator.itemgetter(2,5,8,11,14,17,20)(cards)
print("pile one is", pile_one, "pile two is", pile_two, "pile three is", pile_three)
user_pile= input("which pile is your card in? ")
##check one two or three
if user_pile== "one":
cards= [pile_two+ pile_one + pile_three]
elif user_pile== "two":
cards= [pile_one+ pile_two+pile_three]
else:
cards=[pile_one+ pile_three+ pile_two]
print(cards)
pile_counter= pile_counter+ 1
The full code runs like this:
import random
import operator
def cards_random_shuffle():
with open('cards.txt') as f:
for word in f:
cards = word.strip().split(":")
random.shuffle(cards)
return cards
#print(cards_random_shuffle())
cards= cards_random_shuffle()
def cards_sort(cards):
pile_counter= 0
while pile_counter < 3:
pile_one= operator.itemgetter(0,3,6,9,12,15,18)(cards)
pile_two= operator.itemgetter(1,4,7,10,13,16,19)(cards)
pile_three= operator.itemgetter(2,5,8,11,14,17,20)(cards)
print("pile one is", pile_one, "pile two is", pile_two, "pile three
is", pile_three)
user_pile= input("which pile is your card in? ")
if user_pile== "one":
cards= [pile_two+ pile_one + pile_three]
elif user_pile== "two":
cards= [pile_one+ pile_two+pile_three]
else:
cards=[pile_one+ pile_three+ pile_two]
print(cards)
pile_counter= pile_counter+ 1
print(cards_sort(cards))
And the file "cards.txt" contains this:
Ace of Hearts:Two of Hearts:Three of Hearts:Four of Hearts:Five of Hearts:Six of Hearts:Seven of Hearts:Eight of Hearts:Nine of Hearts:Ten of Hearts:Jack of Hearts:Queen of Hearts:King of Hearts:Ace of Clubs:Two of Clubs:Three of Clubs:Four of Clubs :Five of Clubs:Six of Clubs:Seven of Clubs:Eight of Clubs
Upvotes: 0
Views: 46
Reputation: 1494
In the lines like cards= [pile_one+ pile_two+pile_three]
, you are creating a new list with only one element, which is a list. So you're getting something like this:
[[card1, card2, ...]]
instead of [card1, card2, ...]
You can use cards = pile_one + pile_two + pile_three
to do what you want.
Upvotes: 2