Re: [Tutor] Select a string

2017-09-06 Thread Ben Southwell
May I suggest you use regular expressions?

You can check it out here (take note of the difference between search,
findall etc):
https://docs.python.org/3/library/re.html

Essentially it is a standard library built for matching patterns in
strings. It is a powerful tool that is kind of it's own language in itself
(but other languages have re libraries too so it's definitely worth
learning). The magic of re is learning how to construct your patterns.

re.findall()  will return all non-overlapping matches of a pattern in a
given string.  However, the pattern I've used below will match overlapping
bobs, this is because of the lookahead assertion (the "?=" part of the
pattern). I won't go into regex anymore, it's something I believe you learn
as you do otherwise its way too syntax to learn at once.

 DISCLAIMER: I have only just learnt regex myself lately so if anyone wants
to charm in with a better method please to do so!

Here is a snippet which solves your problem

#!/usr/bin/env python3

import re

pat = r'(?=(bob))'
s = 'azcbobobegghakl'

result = re.findall(pat, s)

print(result)
print(len(result))



On 6 September 2017 at 15:49, Cameron Simpson  wrote:

> On 05Sep2017 22:34, Pat Martin  wrote:
>
>> I am trying to write a program for a programming class that finds the
>> number of a specific string (bob) in a string of characters. I am using
>> one
>> of the sample strings they give me and it should find 2 instances of bob
>> but my script returns 0. Since they want it to find 2 from the bobob in
>> the
>> string using "bob in s" doesn't work (it only returns 1). My eyes are
>> crossing looking at the code, can someone give me a hint on what I am
>> missing that causes this to not give me the correct answer of 2.
>>
>> #!/usr/bin/env python3
>>
>> s = 'azcbobobegghakl'
>>
>> count = 0
>> theo = False
>> firstb = False
>>
>> for i in s:
>>if i == 'b':
>>firstb == True
>>
>
> This line is a boolean expression using "==", not an assignment using "=".
> As a consequence firstb is never set to True and the rest of the logic
> never fires.
>
> It is legal in Python to just put an expression on a line.
>
> It is usually worth putting in print() calls to debug things like this. I
> put:
>
>  print(i, firstb, theo, count)
>
> at the start of the loop and learned that firstb never becomes true. I
> also put the same print statement at the bottom.
>
> The advantage of hte above print statement is that it shows you the
> character from the string along with each set of values. That way you can
> scan down the output to the "bob" part and look for correct behaviour.
>
> I that hadn't helped I've have stuck print after each "if" until the
> problem became glaringly obvious.
>
> BTW, it isn't good to write tests like:
>
>  if theo == True:
>
> "theo" a Boolean anyway. Just say:
>
>  if theo:
>
> It reads more naturally as well.
>
> Cheers,
> Cameron Simpson  (formerly c...@zip.com.au)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Best Regards,

Ben Southwell
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help

2017-09-06 Thread edmundo pierre via Tutor
Hi Python,
I am trying to make a french to English dictionary. First of all, I made a 
dictionary with keys and values. Then I asked the user to enter a letter. If 
the letter correspond to the Keys, my print function should display the Key and 
value. But my code below, could not . Thank you!

List ={"le":"Determinant: The. Pronoun: Him, Her, It, Them .. Example: vive la 
politique, vive l'amour:long live politics, long live love","de": "Preposition: 
Of, From, Some, Any.. Example: Il ne rêve que d'argent et de plaisirs: he only 
dreams of money and pleasure","un":" Adjective,Noum, Pronoun: One..Article: 
A,An... Example: Je me suis cassé un ongle: I broke one of my fingernails","à": 
"Preposition: To,At,In. Example: Ils restent à l'école le plus longtemps 
possible:they remain at school as long as possible","être": "Verb: To be..Noum: 
Being..Example:Tout le monde veut être beau:everybody wants to be 
beautiful","et": "Conjunction: And.. Example: Et les larmes se remirent à 
couler:and the tears started flowing again","en": "Adverb:Thereof. Preposition: 
In, Into, Of, At..Example: Je suis retournée en Espagne en septembre:I returned 
to Spain in September","avoir": "Verb: To have. Noun: Asset, Credit..Example: 
On était six donc tu peux pas avoir une conversation:there were six of us so 
you can't have a conversation","que": "Conjunction: That,Than. 
Pronoun:Which,Who,Whom..Example: C'est un soldat,mais que fait? Il est ici?: 
it's a soldier. But what's he doing here?","pour": "Preposition: For, In order 
toExample: Elle jouait pour gagner:she played to win","dans": "Preposition: 
In, Into, From..Example: Je reviendrai dans dix minutes:I will return in 10 
minutes","ce": "Proposition,Adjective: This, that..Example: Je ne déteste pas 
cet homme: I do not detest this man","il": "Pronoun:He, ItExample: Allez 
voir s'il est blessé: go see if he is injured","qui": "Pronoun: Who, 
WhomExample: Je ne sais pas à qui m'adresser: I don't know who to talk 
to","ne": "Adverb: Not...Example: Nous ne faisons pas du très bon travail:we 
are not doing very good work","sur":"Preposition:On,Upon, Over,...Example: 
T'avais une chance sur un million:you had one chance in a million",  }

keys = List.keys()print(keys)
a = str(input(""))
if 'a' in keys:    print(a + ":"+ List['a'])else:    print("impossible")
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: I want to display Integral symbols

2017-09-06 Thread edmundo pierre via Tutor
So show us what you did. Its hard to figure out what's
gone wrong when we can't see your code:That is what I did:
from sympy import*from tkinter import*from sympy import init_printing
root = 
Tk()root.geometry("450x350+500+500")root.title("Factorisations/Simplifications")root.configure(background
 = "gray")#Difine variablevar1= StringVar()var2 =StringVar()#Create the 
function answer
def Answer():    x = symbols("x")    A = var1.get()    B = factor(A)    
Right_insert_top .insert(END,str(B))

    #A1 = var2.get()    #B1 = factor(A1)    #Right_insert_top 
.insert(END,str(B1))#Create the function simplification
def Simplification():    init_printing()    x= symbols("x")    D = var2.get()   
 E = expand(D)    Right_insert_top .insert(END,str((E))     #Create the 
Factorisation frameTops = Frame(root,relief= "sunken")Tops.pack(side = TOP)
#Create a Label of the TopTop_Label = Label(Tops,font=("arial",30,"bold"),text 
= "Factorisations/Simplifications",bd = 10)Top_Label.pack(side = "top",fill 
=BOTH )
#Create the left frameLeft = Frame(root,relief= "sunken")Left.pack(side = 
"left",fill =BOTH )
#Create the top left frameTop_left = Frame(Left,relief= 
"sunken")Top_left.pack(side ="top")
#Create the Labels top and bottomLeft_top = Label(Top_left ,text ="Factorise: 
",bd = 5)Left_top.pack(side= "left",fill =BOTH)
top_entry = Entry(Top_left,textvariable = var1,bd = 5)top_entry.pack(side= 
"right",fill =X)
#Create the bottom leftLeft_bottom = Frame(Left,relief= 
"sunken")Left_bottom.pack(side = "bottom",fill =BOTH )

Left_bottom_label = Label(Left_bottom,text ="Simplifie: ",bd = 
5)Left_bottom_label.pack(side= "left")
bottom_entry = Entry(Left_bottom ,textvariable = var2,bd = 
5)bottom_entry.pack(side= "right",fill =X)
#Create a Right side Frame
Right = Frame (root,relief= "sunken")Right.pack(side = "right",fill = BOTH)
#Create a Frame on the Top rightRight_top = Frame (Right,relief= 
"sunken")Right_top.pack(side = "top")
#Create the bottom frame on the rightRight_bottom = Frame (Right,relief= 
"sunken")Right_bottom.pack(side = "bottom")#Create a insert text on the screen 
on the rightRight_insert_top = Text( Right_top,font=("arial",10,"bold"),bd= 
5)Right_insert_top.pack()
#Create the exit bottom#Right_exit_buton = Button(Right_bottom1 , text = 
"Exit", font=("arial",20,"bold"),bd = 5)#Right_exit_buton.pack(side ="right")
#Create the Reset bottomRight_reset_buton = Button(Right_bottom , text = 
"Answer\nSimplifie ",command = Simplification,  font=("arial",20,"bold"),bd = 
5)Right_reset_buton.pack(side ="right")#Create the Answer 
buttonRight_answer_buton = Button(Right_bottom , text = 
"Answer\nFactorisasions",command= Answer, font=("arial",20,"bold"),bd = 
5)Right_answer_buton.pack(side ="left")
root.mainloop()



I am using Window 7. I have two  functions: Factorization and Simplification. I 
am using Tkinter (GUI). When I entered the polynomial :(x+3)**2 at the simplify 
box and when I clicked ANSWER SIMPLIFY, I got: x**2+6*x+9, which is Correct. 
But I do not like the syntax. I will like my syntax to be clear like this in my 
Tkinter:  (x−3)2      x-32x-32  and the answer to be like this: x2+6x+9I am 
trying to display the answer : 
x2−6x+9on the Tkinter screen I created. I am using Python 3.6.1. I used the 
Integral as an example of how my answer should look like. My code run 
perfectly, you can try. Thank you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Select a string

2017-09-06 Thread Alan Gauld via Tutor
On 06/09/17 06:34, Pat Martin wrote:

> but my script returns 0. Since they want it to find 2 from the bobob in the
> string using "bob in s" doesn't work (it only returns 1). 

Your code has bugs and Cameron has addressed those along
with general advice on how to debug your code in future.
However there are other string methods that could save
you some work.

At the >>> prompt use dir(str) to see a list of all
the methods available. Then use help(str.methodName)
to find out what each one does.
(Or just browse the string documentation on the web site!)

In this case you might find some of the following methods useful:

str.count
str.find
str.index
str.startswith

and of course you can use string slicing to access a
substring. Combining slicing with the parameters of
find or index should make your task easier.

Finally, if you want to carry on with your loop approach
you might find that enumerate is useful here since it
gives you the index as well as the character. That
will allow you to look-ahead to see if the next two
characters are 'ob'... That should simplify things.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2017-09-06 Thread Chris Warrick
On 6 September 2017 at 08:39, edmundo pierre via Tutor  wrote:
> Hi Python,
> I am trying to make a french to English dictionary. First of all, I made a 
> dictionary with keys and values. Then I asked the user to enter a letter. If 
> the letter correspond to the Keys, my print function should display the Key 
> and value. But my code below, could not . Thank you!
>
> List ={"le":"…"}
(it”s called dict, or dictionary, and “List”/“dict” are not good variable names)

> keys = List.keys()print(keys)
> a = str(input(""))
> if 'a' in keys:print(a + ":"+ List['a'])else:print("impossible")

You’re trying to find the letter 'a' and print it, you aren’t using
the variable a. Don’t put it in quotes. So, do it like this:

data = {"le": "…"}
print(data.keys())
search_key = str(input("> "))
if search_key in data:
print(search_key, ":", data[search_key])
else:
print("Not in dictionary.")

(I also cleaned it up a little)

-- 
Chris Warrick 
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fw: I want to display Integral symbols

2017-09-06 Thread Alan Gauld via Tutor
On 06/09/17 08:09, edmundo pierre via Tutor wrote:
> So show us what you did. Its hard to figure out what's
> gone wrong when we can't see your code:That is what I did:

> from sympy import*from tkinter import*from sympy import init_printing
> root = 
> Tk()root.geometry("450x350+500+500")root.title("Factorisations/Simplifications")root.configure(background
>  = "gray")#Difine variablevar1= StringVar()var2 =StringVar()#Create the 
> function answer
> def Answer():x = symbols("x")A = var1.get()B = factor(A)
> Right_insert_top .insert(END,str(B))

As you can see your code is a mess. you need to send in plain text
format not HTML, otherwise the mail system mangles everything
into an unreadable mess.

I'll try to unscramble it as best I can but it would help a lot
if in future you can switch to plain text for mails with code.
(This is true of most programming mailing lists not just Python)

from sympy import*
from tkinter import*
from sympy import init_printing

root =Tk()
root.geometry("450x350+500+500")
root.title("Factorisations/Simplifications")
root.configure(background = "gray")
#Difine variable
var1= StringVar()
var2 =StringVar()

#Create the function answer
def Answer():
x = symbols("x")
A = var1.get()
B = factor(A)
Right_insert_top .insert(END,str(B))

#Create the function simplification
def Simplification():
init_printing()
x= symbols("x")
D = var2.get()
E = expand(D)
Right_insert_top .insert(END,str((E))

#Create the Factorisation frame
Tops = Frame(root,relief= "sunken")Tops.pack(side = TOP)

#Create a Label of the Top
Top_Label = Label(Tops,font=("arial",30,"bold"),text =
"Factorisations/Simplifications",bd = 10)
Top_Label.pack(side = "top",fill =BOTH )

> #Create the left frame


#Create a Right side Frame
Right = Frame (root,relief= "sunken")
Right.pack(side = "right",fill = BOTH)

#Create a Frame on the Top right
Right_top = Frame (Right,relief= "sunken")
Right_top.pack(side = "top")
...
#Create a insert text on the screen on the right

Right_insert_top = Text( Right_top,font=("arial",10,"bold"),bd= 5)
Right_insert_top.pack()

Ok, I got bored after this, and we have the basic info we need...

We can now see that you are using a Text widget with the Arial font.

> I am using Window 7. 

> I got: x**2+6*x+9, which is Correct. But I do not like the syntax.

OK, So all you need to do is write a string formatting function
that takes your current output and returns the output you want.
You can write and test that in a command line tool which will
avoid all the complexity of a GUI. Then plug that into your GUI
and insert the output into your Text widget.

I don't know sympy but it may have some string formatting
functions that you can use. If not you will need to
interpret the input string yourself. There are some
math expression parsers around on the internet if you
search for the,m. You could adapt one of them I'm sure.

>  I used the Integral as an example of how my answer should look

All the mathematical symbols have their own characters.
Here is a link to the characters that Arial font supports:

http://www.fileformat.info/info/unicode/font/arial_unicode_ms/list.htm

You will see the integral variations at U222B-U2233
Use your browser string find tool to find the other
operators/symbols.

Your formatting function will need to insert the
appropriate unicode characters into your output string.

> My code run perfectly, you can try.

Your code does not run perfectly since it doesn't
do what you want! I assume you mean your code doesn't
generate any errors. That's a different thing :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Select a string

2017-09-06 Thread Pat Martin
I knew it was an assignment I just couldn't see it no matter how hard I
looked at the code. Thanks for the tips on printing the variables, I was
printing them right after the if statements not at the beginning and ending
of the loop. I will remember that about True/False and comparisons thanks
for that as well.

The reason I haven't used regex/methods/etc is it hasn't been covered yet,
we have only covered basic types, for, while and if statements.

On Wed, Sep 6, 2017 at 1:54 AM, Alan Gauld via Tutor 
wrote:

> On 06/09/17 06:34, Pat Martin wrote:
>
> > but my script returns 0. Since they want it to find 2 from the bobob in
> the
> > string using "bob in s" doesn't work (it only returns 1).
>
> Your code has bugs and Cameron has addressed those along
> with general advice on how to debug your code in future.
> However there are other string methods that could save
> you some work.
>
> At the >>> prompt use dir(str) to see a list of all
> the methods available. Then use help(str.methodName)
> to find out what each one does.
> (Or just browse the string documentation on the web site!)
>
> In this case you might find some of the following methods useful:
>
> str.count
> str.find
> str.index
> str.startswith
>
> and of course you can use string slicing to access a
> substring. Combining slicing with the parameters of
> find or index should make your task easier.
>
> Finally, if you want to carry on with your loop approach
> you might find that enumerate is useful here since it
> gives you the index as well as the character. That
> will allow you to look-ahead to see if the next two
> characters are 'ob'... That should simplify things.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Select a string

2017-09-06 Thread Pat Martin
I got it working for all the tests, but the code is ugly. I think regex or
using string methods would have been easier and neater but like I said we
hadn't covered it in the class yet so didn't think I should use it. I am
embarrassed by how bad the code looks to me.

I am self taught and have written a couple useful scripts but still very
much a beginner and there are definite holes in my knowledge. Hoping this
class fills in some of the holes.

Thanks again all for the suggestions and the tips.

On Wed, Sep 6, 2017 at 8:01 AM, Pat Martin  wrote:

> I knew it was an assignment I just couldn't see it no matter how hard I
> looked at the code. Thanks for the tips on printing the variables, I was
> printing them right after the if statements not at the beginning and ending
> of the loop. I will remember that about True/False and comparisons thanks
> for that as well.
>
> The reason I haven't used regex/methods/etc is it hasn't been covered yet,
> we have only covered basic types, for, while and if statements.
>
> On Wed, Sep 6, 2017 at 1:54 AM, Alan Gauld via Tutor 
> wrote:
>
>> On 06/09/17 06:34, Pat Martin wrote:
>>
>> > but my script returns 0. Since they want it to find 2 from the bobob in
>> the
>> > string using "bob in s" doesn't work (it only returns 1).
>>
>> Your code has bugs and Cameron has addressed those along
>> with general advice on how to debug your code in future.
>> However there are other string methods that could save
>> you some work.
>>
>> At the >>> prompt use dir(str) to see a list of all
>> the methods available. Then use help(str.methodName)
>> to find out what each one does.
>> (Or just browse the string documentation on the web site!)
>>
>> In this case you might find some of the following methods useful:
>>
>> str.count
>> str.find
>> str.index
>> str.startswith
>>
>> and of course you can use string slicing to access a
>> substring. Combining slicing with the parameters of
>> find or index should make your task easier.
>>
>> Finally, if you want to carry on with your loop approach
>> you might find that enumerate is useful here since it
>> gives you the index as well as the character. That
>> will allow you to look-ahead to see if the next two
>> characters are 'ob'... That should simplify things.
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.amazon.com/author/alan_gauld
>> Follow my photo-blog on Flickr at:
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Select a string

2017-09-06 Thread Cameron Simpson

On 06Sep2017 09:12, Pat Martin  wrote:

I got it working for all the tests, but the code is ugly. I think regex or
using string methods would have been easier and neater but like I said we


Always go for string methods first. Regexps are cryptic and easy to get wrong, 
and relatively hard to debug when they are wrong. And they're more expensive to 
create and to run.


The flip side is that there are things which can be said easily and concisely 
with regexps. But you should generally consider string methods first.



hadn't covered it in the class yet so didn't think I should use it. I am
embarrassed by how bad the code looks to me.


That comes with practice: getting intuition about what reads well, and what 
tends to be error prone or fragile.


For the exercise, have a relook at the code you have. What would make it easier 
to read? Easier to debug? Better variable names? Even trivial changes like 
changing "firstb" to "first_b" and "theo" to "the_o" can help. Would things be 
clearer with a leading comment explaining the purposes of the state variables:


 # Scan a string for instances of "bob", including overlaps like "bobob".
 # State variables:
 #  first_b: set on encountering the first "b" of a potential "bob"
 #  the_o: set on encountering the :o"  of a potential "bob"; only set if the
 #preceeding character was the "b" (first_b).

Partiularly for little state machines like yours I often find such descriptions 
useful.  They help get the logic clear in my own mind _before_ writing the 
loop, and help you and others understand the code later when you come back to 
debug.


It can also help to comment the individual if-statements. Eg:

 # recognise the "o" of "bob" if the preceeding character was "b"

Cheers,
Cameron Simpson  (formerly c...@zip.com.au)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor