Getting infinite "wrong answer" as output on ideone - exception

import sys
def carton(x):
bottle=x/10
rem=x%10
if rem > 7:
bottle = bottle + rem + 1
elif rem == 7:
bottle = bottle + 1
elif 5<rem<7:
bottle = bottle + 2
elif rem == 5:
bottle = bottle + 1
elif rem<5:
bottle = bottle + rem
print (bottle)
def carton_small(x):
bottle = 0
if x > 7:
bottle = bottle + x%7 + 1
elif x == 7:
bottle = bottle + 1
elif 5<x<7:
bottle = bottle + 2
elif x == 5:
bottle = bottle + 1
elif x<5:
bottle = x
print(bottle)
while True:
test = sys.stdin.read()
try:
test = int(test)
except ValueError:
print ("no, wrong data")
continue
except EOFError:
print ("no,EOF")
continue
if not test: break
break
for x in range(test):
while True:
bottle = sys.stdin.read()
try:
bottle = int(bottle)
except ValueError:
print ("no, wrong data")
continue
except EOFError:
print ("no, EOF1")
continue
if not test: break
break
if(bottle>10):
carton(bottle)
elif(bottle<10):
carton_small(bottle)
else:
bottle = 1
print (bottle)
I wrote the code to check the minimum number of bottles requrired by the milkman to carry x litre of milk. The bottles are of size {1,5,7,10} litres only. Things are working fine on my system but on Ideone, I am getting the error defined in my valueError exception infinitely.Anyhelp possible please?
I am sure the problem is because of sys.stdin.readline() here as input was doing just fine but ideone doesn't accept input() i guess.

Related

I want writerow to export the data to THREE columns, not One as it is doing

My data is exporting to CSV but it is going to just one column. I want it to go to the three columns that I named in the header
for i in range (len(tieList)):
db.writerow([myList[0][i]])
for i in range (len(youWinList)):
db.writerow([myList[1][i]])
for i in range (len(computerWinsList)):
db.writerow([myList[2][i]])
# Single Player
import random
import csv
header = ['tieList','youWinList', 'computerWinsList']
file = open("rps.csv", "w", newline = "")
# Print an introduction
print("Welcome to Rock, Paper, Scissors!")
# Create a list of choices
choices = ["rock", "paper", "scissors"]
#mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()
def single_player():
# Ask the player for their choice
player_choice = input("Enter your choice (rock/paper/scissors): ").lower()
# Check if the player's choice is valid
if player_choice not in choices:
print("Invalid choice. Please try again.")
player_choice = input("Enter your choice (rock/paper/scissors): ").lower()
# Choose a random option for the computer
computer_choice = random.choice(choices)
# Print the choices
print(f"You chose {player_choice} and the computer chose {computer_choice}.")
# Determine the winner
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
else:
print("You lose :(")
def multiple_players():
# Ask the players for their choices
player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()
# Check if the players' choices are valid
if player1_choice not in choices:
print("Player 1, invalid choice. Please try again.")
player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
if player2_choice not in choices:
print("Player 2, invalid choice. Please try again.")
player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()
# Print the choices
print(f"Player 1 chose {player1_choice} and player 2 chose {player2_choice}.")
# Determine the winner
if player1_choice == player2_choice:
print("It's a tie!")
elif player1_choice == "rock" and player2_choice == "scissors":
print("Player 1 wins!")
elif player1_choice == "paper" and player2_choice == "rock":
print("Player 1 wins!")
elif player1_choice == "scissors" and player2_choice == "paper":
print("Player 1 wins!")
else:
print("Player 2 wins!")
tieList = []
youWinList = []
computerWinsList = []
myList = [tieList, youWinList, computerWinsList]
def simulation():
tie = 0
youWin = 0
computerWins = 0
for i in range(1000):
choices = ['rock', 'paper', 'scissors']
player_choice = random.choice(choices)
computer_choice = random.choice(choices)
print(f"You chose {player_choice} and the computer chose {computer_choice}.")
if player_choice == computer_choice:
tie =tie + 1
tieList.append(1)
print("It's a tie!")
elif player_choice == 'rock' and computer_choice == 'scissors':
print("You win!")
youWin +=1
youWinList.append(1)
elif player_choice == 'paper' and computer_choice == 'rock':
print("You win!")
youWin +=1
youWinList.append(1)
elif player_choice == 'scissors' and computer_choice == 'paper':
print("You win!")
youWin +=1
youWinList.append(1)
else:
print("The computer wins!")
computerWins +=1
computerWinsList.append(1)
print(f'You Win: {youWin} Computer Wins: {computerWins} Tie: {tie}')
print(f'TieList.................................:{tieList}')
db = csv.writer(file)
db.writerow(header)
for i in range (len(tieList)):
db.writerow([myList[0][i]])
for i in range (len(youWinList)):
db.writerow([myList[1][i]])
for i in range (len(computerWinsList)):
db.writerow([myList[2][i]])
file.close()
while True:
again = input("Do you want to play a game: (yes/no)? ")
if again.lower() == 'yes':
mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()
if mode == 'single':
single_player()
if mode == 'multiple':
multiple_players()
if mode == 'simulation':
simulation()
def play_Game():
print("Welcome to Rock, Paper, Scissors!")
player_score = 0
computer_score = 0
while True:
simulation()
again = input("Do you want to play again (yes/no)? ")
if again.lower() != 'yes':
break
play_Game()

reinforcement learning improvement suggestions equating float numbers with open ai gym

I'm working on a reinforcement model at university. The aim is to equate three decimal numbers (X,Y,Z) to other decimal numbers (X2,Y2,Z2).
I already have a working model and would like to ask you for suggestions for improvement. I use the open ai gym library
with each reset the agent gets new numbers
X=(random.uniform(-1, 1))
Y=(random.uniform(-1, 1))
Z=(random.uniform(-1, 1))
X = round(X, 5)
Y = round(Y, 5)
Z = round(Z, 5)
choice = random.choices([True,False])
if choice[0]:
X2=X + random.uniform(0,0.5)
Y2=Y + random.uniform(0,0.5)
Z2=Z + random.uniform(0,0.5)
else:
X2=X - random.uniform(0,0.5)
Y2=Y - random.uniform(0,0.5)
Z2=Z - random.uniform(0,0.5)
X2 = round(X2, 5)
Y2 = round(Y2, 5)
Z2 = round(Z2, 5)
Here are my 7 discrete actions:
if action == 0:
self.state[0] -= 0.00001
elif action == 1:
self.state[1] -= 0.00001
elif action == 2:
self.state[2] -= 0.00001
elif action == 3:
self.state[0] += 0.00001
elif action == 4:
self.state[1] += 0.00001
elif action == 5:
self.state[2] += 0.00001
elif action == 6:
self.state[0] += 0
self.state[1] += 0
self.state[2] += 0
My rewardsystem:
direction = np.array(self.state[3:6] - self.state[0:3])
length = np.sqrt(direction.dot(direction))
reward = length *-100
my model:
def build_model(states, actions):
model = Sequential()
model.add(Flatten(input_shape=(1,states)))
model.add(Dense(256, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(actions, activation="sigmoid"))
and my agent:
def build_agent(model, actions):
policy = BoltzmannQPolicy()
memory = SequentialMemory(limit=50000, window_length=1)
dqn = DQNAgent(model=model, memory=memory, policy=policy,
nb_actions=actions, nb_steps_warmup=10, target_model_update=1e-2)
i've tried a lot with the step length but i don't really get a feeling for it.
is there perhaps a better agent, a better policy or better actions?
I am thankful for every hint :)

Tkinter Not Opening Window

I am creating a program that allows a user to make a custom dice, but when I open a GUI window with a button that calls the backend dice roll logic, it breaks. In other words, the window doesn't open, and the code just runs in the terminal. It doesn't happen when the button is clicked like I want it to, instead when I run the code, it doesn't open any GUI window and the code executes in the terminal. The code works without the GUI, and if i take out the dice button callback, the GUI works but together it doesn't.
Any help is appreciated!
import random
import tkinter as tk
def dice_roll():
dice = []
x = 0
# used to check if the input is a whole number, if it isn't, you get a message
while True:
while x == 0:
try:
SIDE_AMT = int(input("How many sides would you like? (min is 2, max is infinite): ")) # amt is amount
x = 1
except ValueError:
print("Sorry it has to be a whole number.")
if SIDE_AMT > 1:
for side in range(SIDE_AMT):
print(f"What would you like side {side + 1} to be?:")
dice.append(str(input()))
break
else:
print("You can't have a dice with one side!")
x = 0
# roll function
def roll():
dice_side = random.choice(dice)
print(f"I choose {dice_side}!")
roll_num = 0
while True:
if roll_num == 0:
spin_it = str(input("Type 'roll' if you would like to roll the dice: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
roll_num += 1
elif roll_num == 1:
while True:
spin_it = str(input("Type 'roll' if you would like to roll the dice again!: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
if __name__ == '__main__':
gui = tk.Tk()
gui.title("Dice Roll")
gui.geometry("1912x1090")
gui.configure(bg='#a2a2a1', borderwidth=5,
relief="raised")
# title
title = tk.Label(gui, text='Unique Dice', font=("Times
New Roman", 52))
title.configure(bg='#a2a2a1', fg='#195190',
borderwidth=3, relief='raised')
# make a dice?
dice = tk.Button(gui,
text="Yes!",
fg="red",
command=dice_roll())
no_dice = tk.Button(gui,
text="No",
fg="red",
command=quit)
# frame = tk.Frame(gui, height=200, width=200)
# frame['borderwidth'] = 10
# frame['relief'] = 'sunken'
# frame.pack()
dice.pack()
no_dice.pack()
title.pack()
gui.mainloop()
you may want to do something like this:
import tkinter as tk
from random import choice
root = tk.Tk()
root.geometry('400x600')
root.resizable(False, False)
root.config(bg='light blue')
dice_numbers = [1, 2, 3, 4, 5, 6]
rolled_nums = []
def roll():
if len(rolled_nums):
rolled_nums[0].pack_forget()
rolled_nums.pop(0)
chosen_number = choice(dice_numbers)
text = tk.Label(root, text=f'{chosen_number}',
font='arial 500 bold', bg='light blue')
text.pack()
rolled_nums.append(text)
button = tk.Button(root, text='Roll Dice!', font='arial 20 bold', relief='raised', width='300',
bg='dark red', fg='black', command=lambda: roll())
button.pack()
root.mainloop()
fell free to adjust this code and if you have questions -> ask

Python 3 random.randint() only returning 1's and 2's

I thought I'd finally worked out all the kinks in the dice rolling code I wrote for practice, but then apparently I forgot to save my work last night, and when I rewrote it this afternoon, the random.randint function didn't seem to be returning any numbers other than 1's and 2's, where before I remember it returning much higher numbers when given larger sizes of dice. I ran the rolling function by itself in the shell and it seemed to be working fine, but I think there must be something wrong with my overall code that's causing it to treat every roll as a 1d2.
import random
die = 0
num = 0
def Opening():
print ("Welcome to the Super Deluxe Diceroller mk. 3!")
print ("What sort of Dice would you like to roll")
choice()
def choice():
print ("A. d2")
print ("B. d4")
print ("C. d6")
print ("D. d8")
print ("E. d10")
print ("F. d12")
print ("G. d20")
print ("H. d100")
global sides
die = input()
if die == 'a' or 'A':
sides = 2
nombre()
elif die == 'b' or 'B':
sides = 4
nombre()
elif die == 'c' or 'C':
sides = 6
nombre()
elif die == 'd' or 'D':
sides = 8
nombre()
elif die == 'e' or 'E':
sides = 10
nombre()
elif die == 'f' or 'F':
sides = 12
nombre()
elif die == 'g' or 'G':
sides = 20
nombre()
elif die == 'h' or 'H':
sides = 100
nombre()
else:
return 'Invalid'
choice()
def nombre():
print ("How many dice would you like to roll?")
global num
num = input()
if num.isnumeric():
roll()
else:
return 'Invalid'
nombre()
def roll():
global num
global fortuna
global sides
if int(num) > 0:
fortuna = random.randint(1,sides)
num = int(num)
num = num - 1
print(fortuna)
roll()
else:
retry()
def retry():
print("Would you like to roll again? (y/n)")
ans = input()
if ans == 'y':
Opening()
elif ans == 'n':
exit
else:
return 'Invalid'
retry()
Opening()
this line if die == 'a' or 'A': will always return True. That is because the way the items are grouped, it is the same as if (die == 'a') or ('A'): and 'A' (along with any string except "") is always True.
Try changing all those lines to if die == 'a' or die == 'A": and it should solve your problem. Also see Truth Value Testing for more info about why this is True.

Picture doesn't load in pygame

# 1 - Import library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.mixer.init()
# 3 - Load image
player = pygame.image.load("C:\python27\PyGame\resources\images\dude.png")
grass = pygame.image.load("C:\python27\PyGame\resources\images\grass.png")
castle = pygame.image.load("C:\python27\PyGame\resources\images\castle.png")
arrow = pygame.image.load("C:\python27\PyGame\resources\images\bullet.png")
badguyimg1 = pygame.image.load("C:\python27\PyGame\resources\image\badguy.png")
badguyimg=badguyimg1
healthbar = pygame.image.load("C:\python27\PyGame\resources\images\healthbar.png")
health = pygame.image.load("C:\python27\PyGame\resources\images\health.png")
gameover = pygame.image.load("C:\python27\PyGame\resources\images\gameover.png")
youwin = pygame.image.load("C:\python27\PyGame\resources\images\youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\explode.wav")
enemy = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\enemy.wav")
shoot = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('C:\python27\PyGame\resources\audio\moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
running = 1
exitcode = 0
while running:
badtimer-=1
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the player on the screen at X:100, Y:100
for x in range(width/grass.get_width()+1):
for y in range(height/grass.get_height()+1):
screen.blit(grass,(x*100,y*100))
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345 ))
# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index=0
velx=math.cos(bullet[0])*10
vely=math.sin(bullet[0])*10
bullet[1]+=velx
bullet[2]+=vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
index+=1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer==0:
badguys.append([640, random.randint(50,430)])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
# 6.3.1 - Attack castle
badrect=pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64:
hit.play()
healthvalue -= random.randint(5,20)
badguys.pop(index)
#6.3.2 - Check for collisions
index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
enemy.play()
acc[0]+=1
badguys.pop(index)
arrows.pop(index1)
index1+=1
# 6.3.3 - Next bad guy
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
position=pygame.mouse.get_pos()
acc[1]+=1
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
here is the error message
Traceback (most recent call last):
File "C:\Python27\game2.py", line 22, in
player = pygame.image.load("C:\python27\PyGame\resources\images\dude.png")
error: Couldn't open C:\python27\PyGame\resources\images\dude.png
What should I do?
First, make sure the file exists.
Next, using single backslashes, \, may lead to problems. For example, \r is the carriage return sequence (\n is the more widely known newline sequence). Your file path, happens to contain a \r, which could be causing your issue.
Try one of these instead:
# Use forward slashes
pygame.image.load("C:/python27/PyGame/resources/images/dude.png")
# Use double back-slashes. For file path specification, \\ indicates '\' (depending
# on the platform)
pygame.image.load("C:\\python27\\PyGame\\resources\\images\\dude.png")
# Use the os module
# Note that this assembles a path relative to your .py file.
# Absolute path can still be done here, it's just more verbose.
pygame.image.load(os.path.join("Pygame", "resources", "images", "dude.png"))
The last option is probably the best practice.