What is wrong with my areas problems code in python? - python-2.7

j = True
while j == True:
area = raw_input("Elije la figura geometrica para calcular su area
\nCuadrado=1 \nTriangulo=2 \nCirculo=3\n")
if area == 1 :
acuadrado()
the problem is in the area.It is something in the syntax?

raw_input in python2.x returns a "string" representation of the users input. Your wanting to do numerical comparison on the input, so you'll want to cast the area variable to an integer (int) before performing the comparison. Something like the following:
area = int(raw_input("Elije la figura geometrica..")
or
area = raw_input("Elije ...")
area = int(area)
then you can compare int values:
if area == 1 :
acuadrado()
etc...
altogether something like this might help you get along:
def acuadrado():
print 'acuadrado'
def atriangulo():
print 'atriangulo'
def acirculo():
print 'acirculo'
j = True
while j == True:
area = raw_input("Elije la figura geometrica para calcular su area \nCuadrado=1 \nTriangulo=2 \nCirculo=3\n")
area = int(area)
if area == 1 :
acuadrado()
elif area == 2:
atriangulo()
elif area == 3:
acirculo()
else:
print 'nada'
j = False
Also see How can I convert a string to an int in Python?
Hope that helps.

Related

Trying to create a new list of Odd numbers from a user inputted list?

This is my code. I have looked at many similar codes and have mine set up exactly how I should. I do not receive an error!
The problem is the output I receive is [11]. When the user inputs [1,2,3,4,5,6,7,8,9,11]. Why is it only pulling one odd number??
totlist = []
max_int = 10
oddlist = []
while len(totlist) < max_int:
nums = int(input('Enter a number: '))
totlist.append(nums)
def find_odds(totlist, oddlist):
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
find_odds(totlist,oddlist)
print(oddlist)
You have forgoot the loop boucle inside the function
def find_odds(totlist, oddlist):
for item in range(len(totlist)) : # here
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)

Image segmentation using k-means

I 'm trying to use k-means algorithm for an image segmentation task . The problem is that my program does not segment the image.
Would you please help me to find the error in my code ?
In fact , I have fixed the number of clusters to 32.
I have used the following data structures:
3 arrays bleu,vert,rouge to store RGB values for each pixel
3 arrays cluster_bleu,cluster_rouge,cluster_vert to store RGB value for each cluster
groupe[i,0]=k maps each pixel i to cluster k
import cv2
import numpy
import random
def main():
MAX_LARGEUR = 400
MAX_HAUTEUR = 400
K = 32 #Le fameux parametre K de l'algorithme
imagecolor = cv2.imread('perr.jpg')
if imagecolor.shape[0] > MAX_LARGEUR or imagecolor.shape[1] > MAX_HAUTEUR:
factor1 = float(MAX_LARGEUR) / imagecolor.shape[0]
factor2 = float(MAX_HAUTEUR) / imagecolor.shape[1]
factor = min(factor1, factor2)
imagecolor = cv2.resize(imagecolor, None, fx=factor, fy=factor, interpolation=cv2.INTER_AREA)
nb_pixels = imagecolor.shape[0] * imagecolor.shape[1]
bleu = imagecolor[:, :, 0].reshape(nb_pixels, 1)
vert = imagecolor[:, :, 1].reshape(nb_pixels, 1)
rouge = imagecolor[:, :, 2].reshape(nb_pixels, 1)
cluster_bleu = numpy.zeros(K)
cluster_vert = numpy.zeros(K)
cluster_rouge = numpy.zeros(K)
groupe = numpy.zeros((nb_pixels, 1))
for i in range(0,K):
groupe[i,0]=i
for i in range(K,nb_pixels):
groupe[i,0]=random.randint(0, K-1)
condition =False
def etape1(indices,i):
s=indices.size
rouge_s=0
vert_s=0
bleu_s=0
#calcul de barycentre des points
if s==0:
cluster_rouge[i]=0
cluster_vert[i]=0
cluster_bleu[i]=0
if s >=1:
for j in range(0,s):
rouge_s=rouge_s+rouge[indices[j]]
vert_s=vert_s+vert[indices[j]]
bleu_s=bleu_s+bleu[indices[j]]
#mise jour des clusters
cluster_rouge[i]=rouge_s/s
cluster_vert[i]=vert_s/s
cluster_bleu[i]=bleu_s/s
iteration=0
oldGroupe = numpy.copy(groupe)
while(condition==False) :
for i in range(0,K):
indices=numpy.where(groupe==i)[0]
etape1(indices,i)
for i in range(0,nb_pixels):
minimum=10000;
dist=0;
index=-1;
for j in range(0,K):
dist=(cluster_rouge[j]-rouge[i])**2+(cluster_vert[j]-vert[i])**2+(cluster_bleu[j]-bleu[i])**2;
if(dist<=minimum):
minimum=dist;
index=j;
groupe[i,0]=index;
condition=numpy.all(groupe==oldGroupe)
oldGroupe = numpy.copy(groupe)
groupe=numpy.reshape(groupe, (imagecolor.shape[0], imagecolor.shape[1]))
for i in range(0, imagecolor.shape[0]):
for j in range(0, imagecolor.shape[1]):
imagecolor[i,j,0] = (cluster_bleu[groupe[i,j]])
imagecolor[i,j,1] = (cluster_vert[groupe[i,j]])
imagecolor[i,j,2] = (cluster_rouge[groupe[i,j]])
cv2.namedWindow("sortie")
cv2.imshow("sortie", imagecolor)
key = cv2.waitKey(0)
if __name__ == "__main__":
main()
The problem is assignment oldGroupe=groupe; which doesn't copy an array, but creates reference with different name (oldGroupe), that points to the same data as groupe. Thus, when you change groupe you also change oldGroupe, and condition is always True.
What you want is to create a copy of data in groupe with oldGroupe = numpy.copy(groupe).

[Code is working]How to shorten my code? Rock =/= rock?

I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read
For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )

Python ignoring while loop with True condition

I'm writing a menu for a simple game, so I thought to use a while loop to let the user choose his wanted option by clicking on it. While my program works properly until this loop, it does not continue when reaching the line of the following loop:
pygame.mouse.set_visible(True) # This is the last line processed.
while True: # This line ist not processed.
(curx,cury)= pygame.mouse.get_pos()
screen.blit(cursor,(curx-17,cury-21))
pygame.display.flip()
# rating values of the cursor position and pressed mouse button below:
(b1,b2,b3) = pygame.mouse.get_pressed() #getting states of mouse buttons
if (b1 == True or b2 == True or b3 == True): # "if one mouse button is pressed"
(cx,cy) = pygame.mouse.get_pos()
if (px <= curx <= px+spx and py <= cury <= py+spy):
return (screen,0)
elif (ox <= curx <= ox+sox and oy <= cury <= oy+soy):
return (screen,1)
elif (cx <= curx <= cx+scx and cy <= cury <= cy+scy):
return (screen,2)
else:
return (screen,3)
time.sleep(0.05)
I have already checked such things like wrong indentation.
BTW my interpreter (python.exe, Python 2.7.11) always does not respond after reaching this line of the
while True:
Because the question was asked in a deleted answer:
I had a print("") between every above shown line to find the problematic line.
As I wrote 4 lines above: The interpreter (and with it the debugger and bug report) has crashed without any further response.
The whole code of this function is:
# MAIN MENU
def smenu (screen,res,menuimg,cursor):
#preset:
x,y = res
click = False
print("preset") # TEST PART
# Fontimports, needed because of non-standard font in use
menu = pygame.image.load("menu.png")
playGame = pygame.image.load("play.png")
options = pygame.image.load("options.png")
crdts = pygame.image.load("credits.png")
print("Fontimport") # TEST PART
#SIZETRANSFORMATIONS
# setting of sizes
smx,smy = int((y/7)*2.889),int(y/7)
spx,spy = int((y/11)*6.5),int(y/11)
sox,soy = int((y/11)*5.056),int(y/11)
scx,scy = int((y/11)*5.056),int(y/11)
print("setting of sizes") # TEST PART
# setting real size of text 'n' stuff
menu = pygame.transform.scale(menu,(smx,smy))
playGame = pygame.transform.scale(playGame,(spx,spy))
options = pygame.transform.scale(options, (sox,soy))
crdts = pygame.transform.scale(crdts, (scx,scy))
cursor = pygame.transform.scale(cursor,(41,33))
print("actual size transformation") # TEST PART
#DISPLAY OF MENU
# fixing positions
mx, my = int((x/2)-((y/7)/2)*2.889),10 # position: 1. centered (x) 2. moved to the left for half of the text's length 3. positioned to the top(y), 10 pixels from edge
px, py = int((x/2)-((y/11)/2)*6.5),int(y/7+10+y/10) # position: x like above, y: upper edge -"menu"'s height, -10, - height/10
ox, oy = int((x/2)-((y/11)/2)*5.056),int(y/7+10+2*y/10+y/11)
cx, cy = int((x/2)-((y/11)/2)*5.056),int(y/7+10+3*y/10+2*y/11)
print("fixing positions") # TEST PART
# set to display
#screen.fill(0,0,0)
screen.blit(menuimg,(0,0))
screen.blit(menu,(mx,my))
screen.blit(playGame,(px,py))
screen.blit(options,(ox,oy))
screen.blit(crdts,(cx,cy))
pygame.display.flip()
print("set to display") # TEST PART
# request for input (choice of menu options)
pygame.mouse.set_visible(True)
print("mouse visible") # TEST PART last processed line
while (True):
print("While-loop") # TEST PART
curx,cury = pygame.mouse.get_pos()
screen.blit(cursor,(curx-17,cury-21))
pygame.display.flip()
# decision value below
(b1,b2,b3) = pygame.mouse.get_pressed() # getting mouse button's state
if (b1 == True or b2 == True or b3 == True): # condition true if a buton is pressed
(cx,cy) = pygame.mouse.get_pos()
if (px <= curx <= px+spx and py <= cury <= py+spy):
return (screen,0)
elif (ox <= curx <= ox+sox and oy <= cury <= oy+soy):
return (screen,1)
elif (cx <= curx <= cx+scx and cy <= cury <= cy+scy):
return (screen,2)
else:
return (screen,3)
time.sleep(0.05)
print("directly skipped")
Would comment but can't because of low rep.
The problem might be, that you're returning a value to a while loop outside a function.
Although it's a bit weird that your interpreter/IDE isn't giving you the correct Error message for it.
I think that the problem is in the following line of your code:
if (b1 == True or b2 == True or b3 == True):
This condition never becomes true so you are stuck into the while loop without your function returning anything.

I need help making a GUI with python, Glade,and GTK

i have a program that encodes and decodes messages with a key but i want to make it look nicer and more professional. My code is as follows:
from random import seed, shuffle
#Encoder Function
def Encoder(user_input,SEED):
user_input = user_input.lower()
letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
n = []
seed(SEED)
shuffle(code)
for letter in user_input:
for let in letter:
if letter != " ":
if letter == let:
first = Letter_code[let]
n.append(code[first])
else:
n.append("~")
return ''.join(n)
#Decoder Function
def Decoder(user_input,SEED):
user_input = user_input.lower
key_list = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
final = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
seed(SEED)
shuffle(key_list)
key_code = {}
z = 0
n = []
for key in key_list:
key_code[key] = z
z += 1
for let in user_input:
if let != "~":
for Ke in key_list:
if let == Ke:
a = key_code[Ke]
n.append(final[a])
else:
n.append(" ")
return ''.join(n)
i wanted a gui that would have two entry boxes,one for the message and the other for the key, and i wanted it to have two buttons, one would say encode and the other decode. and also a place in the gui where the final message would be printed and be copy-able by the user. would greatly appreciate it if someone could help me with this
Following glade tutorials may help you.
http://www.overclock.net/t/342279/tutorial-using-python-glade-to-create-a-simple-gui-application
https://wiki.gnome.org/Glade/Tutorials
http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm
As for converting the .py to an exe, you can use py2exe, please take a look at this answer - https://stackoverflow.com/a/14165470/2689986