Related
import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns
Im currently trying to add a player to a board in python to be able to command the player but I cant seem to figure it out.
def GenPlayer(level):
player = {}
player['name'] = GenName()
player['history'] = GenHistory() #history
player['attack'] = DieRoller(3,6) + DieRoller(level,4)
player['defense'] = DieRoller(3,6) + DieRoller(level,4)
player['health'] = DieRoller(5,6) + DieRoller(level,4)
player['row'] = 0
player['col'] = 0
character =(player['name']) + ("Health: "+str(player['health'])) + (" Defense: "+str(player['defense'])) + (" Attack: "+str(player['attack']))
return character
def CreateBoard():
board = []
while True:
x = int(input("Number of Rows: "))
y = x
break
for row in range(0,x):
board.append(["()"]*y)
return board
def ShowBoard(board):
for row in board:
print(" ".join(row))
def PlacePlayer(board,player):
row = DieRoller(1,6)
col = DieRoller(1,6)
board[row][col] = 'player'
return board,player
print(PlacePlayer(ShowBoard(CreateBoard()),GenPlayer(1)))
I keep getting this error when trying this code:
Exception has occurred: TypeError
'NoneType' object is not subscriptable
If you want to place the player object at the selected position, remove the quote marks:
board[row][col] = player
Update:
A player object is a dictionary, so you need to place the player['name'] on the board to be able to print it in the ShowBoard() function you have, as the function uses .join() , which is a string method. I made a slight change to PlacePlayer(), and simplified the code to make it a bit easier to understand what's happening:
def PlacePlayer(board,player):
row = 5
col = 4
board[row][col] = player['name']
return board
newboard= CreateBoard()
characterDescripiton , playerobject = GenPlayer(1)
boardafterPlacePlayer = PlacePlayer(newboard,playerobject)
ShowBoard(boardafterPlacePlayer)
I have created a multiplayer game of Noughts and Crosses using Python 3.
I have got all of my code to work except for the check loop.
The check loop will each time a new symbol is entered if it is a winning move or if the board is full.
Currently, my code does not finish after one player inputs 3 symbols in a row or the board becomes full.
This is my code so far:
import random
def start_player():
startplayer = random.randint(1,2)
if startplayer == 1:
turn = 'X'
print("Player One (X) will start the game.")
else:
startplayer == 2
turn = 'O'
print("Player Two (O) will start the game.")
return turn
def getmove():
row = int(input("Please enter a number between 0 and 2: "))
column = int(input("Please enter a number between 0 and 2: "))
while grid[row][column] != "":
print("Invalid move.")
row = int(input("Please enter a number between 0 and 2: "))
column = int(input("Please enter a number between 0 and 2: "))
return row, column
def mainturn(row, column):
global countmove
countmove = countmove + 1
global symbol
grid[row][column] = symbol
for y in range(0,(len(grid))):
print(grid[y])
if symbol == 'X':
symbol = 'O'
elif symbol == 'O':
symbol = 'X'
return countmove
def check_win(row, column, symbol):
if (grid[0][0] and grid[0][1] and grid[0][2] == symbol) or (grid[1][0] and grid[1][1] and grid[1][2] == symbol) or (grid[2][0] and grid[2][1] and grid[2][2] == symbol) or (grid[0][0] and grid[1][0] and grid[2][0] == symbol) or (grid[0][1] and grid[1][1] and grid[2][1] == symbol)or (grid[0][2] and grid[1][2] and grid[2][2] == symbol)or (grid[0][0] and grid[1][1] and grid[2][2] == symbol) or (grid[2][0] and grid[1][1] and grid[0][2] == symbol):
print("Well done!",symbol," won the game.")
return true
elif countmove == 9:
print("Board Full. Game over.")
#main program
grid = [["","",""],["","",""],["","",""]]
countmove = 0
win = 'false'
for y in range(0,(len(grid))):
print(grid[y])
symbol = start_player()
while countmove != 9 or win == 'false':
countmove = 0
row, column = getmove()
mainturn(row,column)
win = check_win(row,column, symbol)
It is because of two things. Firstly you are resetting count_move value in the loop, hence it is always zero and goes in an infinite loop. Secondly you are changing the symbol before checking if it is a win, check_win routine was checking for the next symbol not the current symbol of the player. Here is the working code:
while countmove != 9 or win == 'false':
row, column = getmove()
mainturn(row,column)
win = check_win(row,column, symbol)
symbol = change_symbol(symbol)
The sub-routine change_symbol is here:
def change_symbol(symbol):
if symbol == 'X':
symbol = 'O'
elif symbol == 'O':
symbol = 'X'
return symbol
As part of good coding practice, avoid using global variables inside subroutines, it will just add up the confusion.
I did my best to comment on why I did things and why I removed things. I hope this example helps you see why it cant be better to use classes when working with python. I added some other features that I think may help you as you continue to learn programming
import random
# Lets put all these functions into a class
class Game:
# Lets set up the game
def __init__(self, player_one="X", player_two="O"):
self.player_one = player_one
self.player_two = player_two
# Where the game board is stored
# Using periods instead of spaces so the players can see the possible moves
self.game_board = [
[".", ".", "."],
[".", ".", "."],
[".", ".", "."]
]
# This value is to check if the game is still going
self.running = True
# Whos turn is it?
self.active_player = ""
# The tasks we HAVE to do to make the game work
self.start_player()
self.run_game()
# The function is part of the Game class so we have to pass self into it.
def start_player(self):
# Randomly Choose a starting player
startplayer = random.randint(1,2)
if startplayer == 1:
# We declared the string values in the __init__ function
player = self.player_one
print("Player One ({}) will start the game.".format(player))
else:
startplayer == 2
player = self.player_two
print("Player Two ({}) will start the game.".format(player))
# Set the initial player
self.active_player = player
def get_move(self):
# Seems silly to have them enter the rows and columns one by one
#row = int(input("Please enter a number between 0 and 2: "))
#column = int(input("Please enter a number between 0 and 2: "))
# Show the player whos turn it is
input_data = input("Player ({}) please choose a Column and a Row: ".format(self.active_player))
# Default values that aren't in the game, if they arent changed they will be caught
row = -1
column = -1
# Users entry all types of funky data, lets make sure its right
try:
r, c = input_data.split(" ")
r = int(r)
c = int(c)
if r >= 0 and r <= 3:
row = int(r)
if c >= 0 and c <= 3:
column = int(c)
except:
print("Enter only two numbers (0, 1, or 2) seperated by a space")
return row, column
# This check for the grid should be its own function
#while grid[row][column] != "":
# print("Invalid move.")
# row = int(input("Please enter a number between 0 and 2: "))
# column = int(input("Please enter a number between 0 and 2: "))
def check_move(self, row, column):
if row == -1 or column == -1:
return False
# If the space is blank return True
if self.game_board[row][column] == ".":
return True
print("{} {} is an invalid move, try again".format(row, column))
return False
# Add another function to print out the board for us
def show_board(self):
for row in self.game_board:
row_string = ""
for cell in row:
row_string = "{} {} ".format(row_string, cell)
print(row_string)
#def mainturn(row, column):
# Try to avoid using globals. We'll store these in our class
#global countmove
#countmove = countmove + 1
#global symbol
#grid[row][column] = symbol
#for y in range(0,(len(grid))):
# print(grid[y])
#if symbol == 'X':
# symbol = 'O'
#elif symbol == 'O':
# symbol = 'X'
#return countmove
# This is one heck of an if statement. Lets turn it into a function
# if (grid[0][0] and grid[0][1] and grid[0][2] == symbol) or (grid[1][0] and grid[1][1] and grid[1][2] == symbol) or (grid[2][0] and grid[2][1] and grid[2][2] == symbol) or (grid[0][0] and grid[1][0] and grid[2][0] == symbol) or (grid[0][1] and grid[1][1] and grid[2][1] == symbol)or (grid[0][2] and grid[1][2] and grid[2][2] == symbol)or (grid[0][0] and grid[1][1] and grid[2][2] == symbol) or (grid[2][0] and grid[1][1] and grid[0][2] == symbol):
def check_win(self, symbol):
combinations = [
# horizontal
[(0,0), (1,0), (2,0)],
[(0,1), (1,1), (2,1)],
[(0,2), (1,2), (2,2)],
# vertical
[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
# crossed
[(0,0), (1,1), (2,2)],
[(2,0), (1,1), (0,2)]
]
for coordinates in combinations:
letters = [self.game_board[x][y] for x, y in coordinates]
# If all the letters match
if "." not in letters:
if len(set(letters)) <= 1:
# returns corresponding letter for winner (X/O)
print("Well done {}! You won the game!".format(symbol))
self.running = False
return True
return False
# Lets try another method of checking if the board is full
#elif countmove == 9:
# print("Board Full. Game over.")
#main program
def board_full(self):
for row in self.game_board:
if "." in row:
return False
print("The game is a draw :( ")
# Stop the game
self.running = False
return True
def run_game(self):
# While the game is not over
while self.running != False:
# Show the player the board
self.show_board()
row, column = self.get_move()
# Is the move valid?
if self.check_move(row, column):
self.game_board[row][column] = self.active_player
# Did they win?
self.check_win(self.active_player)
# Change Players
if self.active_player == self.player_one:
self.active_player = self.player_two
else:
self.active_player = self.player_one
# Print the winning game board
self.show_board()
g = Game("X", "O")
# Handled this in the class
#grid = [["","",""],["","",""],["","",""]]
#countmove = 0
#win = 'false'
# Turned this code into the show_board function
#for y in range(0,(len(grid))):
#print(grid[y])
#symbol = start_player()
#while countmove != 9 or win == 'false':
# Shouldnt reset the countmove inside of the loop thats checking the countmove
#countmove = 0
#row, column = getmove()
#mainturn(row,column)
#win = check_win(row,column, symbol)
Example Output:
Player One (X) will start the game.
. . .
. . .
. . .
Player (X) please choose a Column and a Row: 0 1
. X .
. . .
. . .
Player (O) please choose a Column and a Row: 2 2
. X .
. . .
. . O
Player (X) please choose a Column and a Row: 0 0
X X .
. . .
. . O
Player (O) please choose a Column and a Row: 2 1
X X .
. . .
. O O
Player (X) please choose a Column and a Row: 0 2
Well done X! You won the game!
X X X
. . .
. O O
I am trying to write a program for connect 4 but am having a lot of trouble getting past the directions. Everything under the comment, "#everything works up to here" works but then it all explodes and I have no idea even where to start to fix it.
#connect 4
import random
#define global variables
X = "X"
O = "O"
EMPTY = "_"
TIE = "TIE"
NUM_ROWS = 6
NUM_COLS = 8
def display_instruct():
"""Display game instructions."""
print(
"""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you! \n
"""
)
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question,low,high):
"""Ask for a number within range."""
#using range in Python sense-i.e., to ask for
#a number between 1 and 7, call ask_number with low=1, high=8
low=1
high=NUM_COLS
response = None
while response not in range (low,high):
response=int(input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = X
computer = O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = X
human = O
return computer, human
def new_board():
board = []
for x in range (NUM_COLS):
board.append([" "]*NUM_ROWS)
return board
def display_board(board):
"""Display game board on screen."""
for r in range(NUM_ROWS):
print_row(board,r)
print("\n")
def print_row(board, num):
"""Print specified row from current board"""
this_row = board[num]
print("\n\t| ", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num],"|")
print("\t", "|---|---|---|---|---|---|---|")
# everything works up to here!
def legal_moves(board):
"""Create list of column numbers where a player can drop piece"""
legal=True
while not legal:
col = input("What column would you like to move into (1-7)?")
for row in range (6,0,1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row][col]==" "):
board[row][col] = turn
legal = True
else:
print("Sorry, that is not a legal move.")
def human_move(board,human):
"""Get human move"""
try:
legals = legal_moves(board)
move = None
while move not in legals:
move = ask_number("Which column will you move to? (1-7):", 1, NUM_COLS)
if move not in legals:
print("\nThat column is already full, nerdling. Choose another.\n")
print("Human moving to column", move)
return move #return the column number chosen by user
except NameError:
print ("Only numbers are allowed.")
except IndexError:
print ("You can only select colums from 1-7.")
def get_move_row(turn,move):
for m in (NUM_COLS):
place_piece(turn,move)
display_board()
def computer_move ():
move= random.choice(legal)
return move
def place_piece(turn,move):
if this_row[m[move]]==" ":
this_row.append[m[move]]=turn
def winner(board):
# Check rows for winner
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] == board[row][col + 3]) and (board[row][col] != " "):
return [row][col]
# Check columns for winner
for col in range(6):
for row in range(3):
if (board[row][col] == board[row + 1][col] == board[row + 2][col] ==board[row + 3][col]) and (board[row][col] != " "):
return [row][col]
# Check diagonal (top-left to bottom-right) for winner
for row in range(3):
for col in range (4):
if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] == board[row + 3][col + 3]) and (board[row][col] != " "):
return true
# Check diagonal (bottom-left to top-right) for winner
for row in range (5,2,-1):
for col in range (3):
if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] == board[row - 3][col + 3]) and (board[row][col] != " "):
return [row][col]
# No winner
return False
def main():
display_instruct()
computer,human = pieces()
turn = X
board = new_board()
while not winner(board) and (" " not in board):
display_board(board)
if turn == human:
human_move(board,human)
get_move_row()
place_piece()
else:
computer_move(board,computer)
place_piece()
display_board(board)
turn = next_turn()
the_winner = winner(board)
congrat_winner(the_winner, computer, human)
#start the program
main ()
input ("\nPress the enter key to quit.")
For fun, here's an object-oriented refactorization. It's a bit long, but well documented and should be easy to understand.
I started with your code and split it into Board, Player, and Game classes, then derived Computer and Human classes from Player.
Board knows the shape and size of the rack, what moves are legal, and recognizes when wins and ties occur
Player has a name and knows how to choose (or prompt for) a legal move
Game has a Board and two Players and controls turn-taking and output
I'm not 100% happy with it - Board has a .board that is a list of list of string, but Game has a .board that is a Board; a bit of judicious renaming would be a good idea - but for an hour's work it's pretty solid.
Hope you find this educational:
# Connect-4
from itertools import cycle, groupby
from random import choice
from textwrap import dedent
import sys
# version compatibility shims
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
def get_yn(prompt, default=None, truthy={"y", "yes"}, falsy={"n", "no"}):
"""
Prompt for yes-or-no input
Return default if answer is blank and default is set
Return True if answer is in truthy
Return False if answer is in falsy
"""
while True:
yn = inp(prompt).strip().lower()
if not yn and default is not None:
return default
elif yn in truthy:
return True
elif yn in falsy:
return False
def get_int(prompt, lo=None, hi=None):
"""
Prompt for integer input
If lo is set, result must be >= lo
If hi is set, result must be <= hi
"""
while True:
try:
value = int(inp(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return value
except ValueError:
pass
def four_in_a_row(tokens):
"""
If there are four identical tokens in a row, return True
"""
for val,iterable in groupby(tokens):
if sum(1 for i in iterable) >= 4:
return True
return False
class Board:
class BoardWon (BaseException): pass
class BoardTied(BaseException): pass
EMPTY = " . "
HOR = "---"
P1 = " X "
P2 = " O "
VER = "|"
def __init__(self, width=8, height=6):
self.width = width
self.height = height
self.board = [[Board.EMPTY] * width for h in rng(height)]
self.tokens = cycle([Board.P1, Board.P2])
self.rowfmt = Board.VER + Board.VER.join("{}" for col in rng(width)) + Board.VER
self.rule = Board.VER + Board.VER.join(Board.HOR for col in rng(width)) + Board.VER
def __str__(self):
lines = []
for row in self.board:
lines.append(self.rowfmt.format(*row))
lines.append(self.rule)
lines.append(self.rowfmt.format(*("{:^3d}".format(i) for i in rng(1, self.width+1))))
lines.append("")
return "\n".join(lines)
def is_board_full(self):
return not any(cell == Board.EMPTY for cell in self.board[0])
def is_win_through(self, row, col):
"""
Check for any winning sequences which pass through self.board[row][col]
(This is called every time a move is made;
thus any win must involve the last move,
and it is faster to check just a few cells
instead of the entire board each time)
"""
# check vertical
down = min(3, row)
up = min(3, self.height - row - 1)
tokens = [self.board[r][col] for r in rng(row - down, row + up + 1)]
if four_in_a_row(tokens):
return True
# check horizontal
left = min(3, col)
right = min(3, self.width - col - 1)
tokens = [self.board[row][c] for c in rng(col - left, col + right + 1)]
if four_in_a_row(tokens):
return True
# check upward diagonal
down = left = min(3, row, col)
up = right = min(3, self.height - row - 1, self.width - col - 1)
tokens = [self.board[r][c] for r,c in zip(rng(row - down, row + up + 1), rng(col - left, col + right + 1))]
if four_in_a_row(tokens):
return True
# check downward diagonal
down = right = min(3, row, self.width - col - 1)
up = left = min(3, self.height - row - 1, col)
tokens = [self.board[r][c] for r,c in zip(rng(row - down, row + up + 1), rng(col + right, col - left - 1, -1))]
if four_in_a_row(tokens):
return True
# none of the above
return False
def legal_moves(self):
"""
Return a list of columns which are not full
"""
return [col for col,val in enumerate(self.board[0], 1) if val == Board.EMPTY]
def do_move(self, column):
token = next(self.tokens)
col = column - 1
# column is full?
if self.board[0][col] != Board.EMPTY:
next(self.move) # reset player token
raise ValueError
# find lowest empty cell (guaranteed to find one)
for row in rng(self.height-1, -1, -1): # go from bottom to top
if self.board[row][col] == Board.EMPTY: # find first empty cell
# take cell
self.board[row][col] = token
# did that result in a win?
if self.is_win_through(row, col):
raise Board.BoardWon
# if not, did it result in a full board?
if self.is_board_full():
raise Board.BoardTied
# done
break
class Player:
def __init__(self, name):
self.name = name
def get_move(self, board):
"""
Given the current board state, return the row to which you want to add a token
"""
# you should derive from this class instead of using it directly
raise NotImplemented
class Computer(Player):
def get_move(self, board):
return choice(board.legal_moves())
class Human(Player):
def get_move(self, board):
legal_moves = board.legal_moves()
while True:
move = get_int("Which column? (1-{}) ".format(board.width), lo=1, hi=board.width)
if move in legal_moves:
return move
else:
print("Please pick a column that is not already full!")
class Game:
welcome = dedent("""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you!
""")
def __init__(self):
print(Game.welcome)
# set up new board
self.board = Board()
# set up players
self.players = cycle([Human("Dave"), Computer("HAL")])
# who moves first?
if get_yn("Do you want the first move? (Y/n) ", True):
print("You will need it...\n")
# default order is correct
else:
print("Your rashness will be your downfall...\n")
next(self.players)
def play(self):
for player in self.players:
print(self.board)
while True:
col = player.get_move(self.board) # get desired column
try:
print("{} picked Column {}".format(player.name, col))
self.board.do_move(col) # make the move
break
except ValueError:
print("Bad column choice - you can't move there")
# try again
except Board.BoardWon:
print("{} won the game!".format(player.name))
return
except Board.BoardTied:
print("The game ended in a stalemate")
return
def main():
while True:
Game().play()
if not get_yn("Do you want to play again? (Y/n) ", True):
break
if __name__=="__main__":
main()
Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description