Re: count consecutive elements
I'd wish to have this challenge posted on my blog but because I suck in IT english, could you guys help me with decribing the task of what the code supposed to do? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Python for Android
Will Python delevopment apps for Android OS getting easier? So far best option is Kivy which is not liked by many developers, another option is PyQT5, which finally gets some support but there still are some buts.. Tkinter, some tried but it's still a NO for Android support. -- https://mail.python.org/mailman/listinfo/python-list
Re: If you have Python Cookbook, 3rd ed.
On 2021-05-19, Terry Reedy wrote: > can you verify that the Algorithm chapter (near end in 2nd ed.) does > *NOT* have an introduction by Tim Peters? > (Info needed to verify timeit doc correction > https://github.com/python/cpython/pull/21744) Preface .. xi 1.Data Structure adn Algorithms.1 1.1 Unpacking a Sequence into Separate Variables1 1.2 Unpacking Elements from Iterables of Arbitrary Lenght 3 1.2 Keeping the Last N items5 1.3 Finding the Largest or Smallest N itemst7 Third Edition. -- https://mail.python.org/mailman/listinfo/python-list
Re: do ya still use python?
On 2021-04-19, Unbreakable Disease wrote: >> do ya still use python? That's why we're all here. > almost no useful posts here for almost a year. is python dying? It's not a Python thing, it's Usenet that's not used as much today as decade ago. There's a lot of places in a Internet to talk Python: Discord,FB, Forums. Feel free to write some useful posts :-) -- https://mail.python.org/mailman/listinfo/python-list
Yield after the return in Python function.
The return suspends the function execution so how is it that in below example I got output: def doit(): return 0 yield 0 print(doit()) -- https://mail.python.org/mailman/listinfo/python-list
Re: Button placement
On 2021-03-09, Terry Reedy wrote: > > Say more clearly what you want/expect and what you are getting and why > you are unhappy. > It solved Terry, I wanted center the button on top, had only 3 columns (0,1,2) and was unaware that I could use "columnspan=3" as it ends on 2, I was using columnspan=2 :-) Thanks, anyway. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Button placement
On 2021-03-09, Richard Damon wrote: > > One thing to remember is that span is sort of like range, range(3) is > [0, 1, 2] > Right, ends on 2. Thanks again, that ended mine frustration lol. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Button placement
On 2021-03-09, Peter Otten <__pete...@web.de> wrote: > On 09/03/2021 03:08, Bischoop wrote: >> >> I try for a while place the top button in a a middle of column=0 with >> span to column2 below so the button being centered to those, > > I'm not sure what you mean, do you perhaps need columnspan=3? > > You were sure :-) columnspan=3 helped, I didn't know that I can apply it to 3 when not having column=3, was trying just with columnspan=2 but as you know it didn't do the job. I was swearing when fighting with it with padding lol. -- Thanks > -- https://mail.python.org/mailman/listinfo/python-list
Button placement
I try for a while place the top button in a a middle of column=0 with span to column2 below so the button being centered to those, tried with canvas as well but with no success. Is someone with Tkinter experience able to advice what I could do? from tkinter import * from tkinter import ttk root = Tk() root.title('Password Generator') root.config(padx=10, pady=10) backg = '#06090f' canvas = Canvas(root, width=80, height=40).grid(column=0, row=0, columnspan=2,sticky=E) bgs = Button(canvas, text="Password Manager & Generator", background='#0f2a52', foreground="orange", font=("Times New Roman", 15, 'bold')).grid(column=0, row=0, pady=10, columnspan=2) long_t = Label(text='Password Length:') long_t.grid(column=0, row=1) choice_n = IntVar() choice = ttk.Combobox(width=10) w = [x for x in range(8, 16)] choice['values'] = w choice.grid(row=1, column=1) choice.current() choice.bind("<>") password_text = Label(text='Password: ') password_text.grid(row=2, column=0) password_entry = Entry(width=20) password_entry.grid(row=2, column=1) gen = Button(text='Generate Password') gen.grid(row=1, column=2, sticky=W) -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter new window contentent when button is clicked.
On 2021-02-25, MRAB wrote: >> > The trick is to put the "pages" on top of each other and then show the > appropriate one, something like this: > import tkinter as tk > > def on_next_page(): > # Brings page 2 to the top. > frame_2.tkraise() > > def on_previous_page(): > # Brings page 1 to the top. > frame_1.tkraise() > > def on_finish(): > # Closes the dialog. > root.destroy() > > root = tk.Tk() > > # Page 1. > frame_1 = tk.Frame(root) > tk.Label(frame_1, text='Page 1').pack() > tk.Button(frame_1, text='Next', command=on_next_page).pack() > > # Page 2. > frame_2 = tk.Frame() > tk.Label(frame_2, text='Page 2').pack() > tk.Button(frame_2, text='Previous', command=on_previous_page).pack() > tk.Button(frame_2, text='Finish', command=on_finish).pack() > > # Put the pages on top of each other. > frame_1.grid(row=0, column=0, sticky='news') > frame_2.grid(row=0, column=0, sticky='news') > > # Bring page 1 to the top. > frame_1.tkraise() > > tk.mainloop() Great, thanks for reply, I'll look into that. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter new window contentent when button is clicked.
On 2021-02-24, Bischoop wrote: > Just came to solution, I learnt that the combobox can be bind and call function when combobox value changes. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Tkinter new window contentent when button is clicked.
I'm learning Tkinter now and have upgraded few programs I've made in CLI in the past. What is bothering me now is what I should look at when I want new content in a window when button is 'Next' is clicked. In some programs we're clicking button next and new content appears in same window. I've used so far Toplevel(root) and new window was appearing on top the main one but I'd like to find out about solution without creating new windows. Is it a Canvas used for it? I'd be glad if you could direct me because I don't know even what to look for. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Deleting Python 3.8.5
On 2021-02-22, Vinicius Costa Marques wrote: > Hello there Python team, I’m having this problem were I installed >Python 3.9.2 and then went to unistall 3.8.5 but here is the problem >the version 3.8.5 dosen’t get deleted properly. >The uninstall program says that everything worked but the files >for 3.8.5 still exist algong with 3.9.2 can someone help me? I wouldn't do that, you can meet missing libraries for Py3.9.2 and then need to install Py3.8 again. Just wait with uninstalling Py3.8 for a while. -- https://mail.python.org/mailman/listinfo/python-list
Problem when scraping the 100 Movie titles.
I'm learning Scraping actually and would like to scrape the movie titles from https://www.empireonline.com/movies/features/best-movies-2 . In the course I was learning I was supposed to do it with bs4: titles = soup.find_all(name = 'h3', class_ = 'title') but after after a while I guess the site has changed and now the class is: jsx-2692754980 100) Stand By Me but anyway if I do try get those titles by name and class, my list is empty: titles = soup.find_all(name = 'h3', class_ = 'jsx-2692754980') I tried also selenium and manage get those titles with: driver.get('https://www.empireonline.com/movies/features/best-movies-2') #driver.find_element_by_xpath('/html/body/div/div[3]/div[5]/button[2]').click() titles = driver.find_elements_by_css_selector("h3.jsx-2692754980") tit=[] for e in titles: tit.append(e.text) print(tit) But in Chrome I get a popup asking to accept cookies and I need to click to accept them. Is someone here who knows how can I get those titles with BeautifulSoup and how to deal with cookies if using Selenium? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Response for PING in ircbot.
Got problem with responding for Ping, tried so many ways to response and always end up with time out or other error. This time: ERROR :(Ping timeout: 264 seconds) Traceback (most recent call last): s.send(bytes('PONG ' + data.split()[1], 'UTF-8')) BrokenPipeError: [Errno 32] Broken pipe while True: time.sleep(2) data=s.recv(2040).decode('utf8') data = data.strip("\n\r") print(data) if data.find ("PING :"): s.send(bytes('PONG ' + data.split()[1], 'UTF-8')) -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: imalib cant get From: adresses
On 2021-01-27, Bischoop wrote: Solved using IMAP4.uid. -- https://mail.python.org/mailman/listinfo/python-list
imalib cant get From: adresses
I don't have much experience with imaplib and for a few days can't manage to get properly, I followed also some tutorial but also met few problems. What I want is to get email addresses from emails I do have in gmail inbox. The code below gets them but then pops an error. When I change the part "for i in range()" as in commented line it gets just the last email. Anybody familiar here with imaplib? import getpass, imaplib import email from email.header import decode_header M = imaplib.IMAP4_SSL('imap.gmail.com') M.login(u, p) M.select() status, messages = M.select("INBOX") di={} # number of top emails to fetch N = 100 # total number of emails messages = int(messages[0]) for i in range(messages, messages-N,-1): #for i in range(messages, N): # fetch the email message by ID res, msg = M.fetch(str(i), "(RFC822)") for response in msg: if isinstance(response, tuple): # parse a bytes email into a message object msg = email.message_from_bytes(response[1]) From, encoding = decode_header(msg.get("From"))[0] if isinstance(From, bytes): From = From.decode(encoding) print("From:", From) print(type(From)) print("="*100) if '<'in From: s = From.index('<') d = From.index('>') q = From[s + 1:d] w = From[0:s - 1] if q in di.values(): pass else: di[w] = q else: if q not in di.values(): b = sum(1 for key in di if key.startswith('Friend')) di[f'Friend{b+1}']=From # close the connection and logout M.close() M.logout() print(di) for i in di.keys(): if 'Friend' in i: print(From,'\n',i,di[i]) b = sum(1 for key in di if key.startswith('Friend')) print(b) raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: FETCH command error: BAD [b'Could not parse command'] Process finished with exit code 1 -- https://mail.python.org/mailman/listinfo/python-list
Re: count consecutive elements
On 2021-01-19, Peter Otten <__pete...@web.de> wrote: > On 19/01/2021 04:45, Bischoop wrote: > >> I sat to it again and solved it. > > Congratulations! > > > lil = tuple(set(s)) # list of characters in s > > > > li=[0,0,0,0,0,0] # list for counted repeats > > I see a minor problem here. What happens if s contains more than len(li) > characters? > Thanks, I've created it when came to idea how to solve the problem and then forgot that part, will have to update it with two additional line of code. >> import timeit > > Since you seem interested in performance: imagine that the input is a > very long string. Let's call the length N. > > How often do you iterate over its characters? > Does it take time :-) I actually left it because seen guy in thread were comparing their time results, I'm pretty much aware that mine solution is time consuming and there are better ways to do it but I wanted to finish what I started without any additional libraries like itertools etc in the way that my knowledge allows. The idea with for this tuple just came up in a first seconds when I look at that and was not bothering about time or performance especially that later on as you seen I had different problem to solve and which took me quite a time and when I look at it today I think how couldn't I came with it earlier and let myself stuck on it. I'm happy that despite I've asked here I've finish it practically wthout additional help and yeah ( Thanks to Stefan who just pointed me to look at it from different prespective instead pointing what was wrong), I'll iterate here n = x [x for x in lil], with big string it can make difference. Now, when you asked me that question I came indeed for better idea to do this. One loop during which I can append character if not in lil. > How often does Tim's solution? oh here Im stuck and dont understand what you mean? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: count consecutive elements
On 2021-01-14, Stefan Ram wrote: > > If you want to know why, maybe you should insert print > statements to see the values of critical variables and > expression, especially in loops. > > Then compare the printed values with your expectations. > > Also, decompose into meaningful functions and test each > function separately. > > I sat to it again and solved it. import timeit run1 = ''' s = 'aabskbad' lil = tuple(set(s)) # list of characters in s li=[0,0,0,0,0,0] # list for counted repeats for i in lil: c = 0 h= lil.index(i) for letter in s: if letter == i: c += 1 if c > li[lil.index(letter)]: li[lil.index(letter)] = c else: c=0 continue m = max(li) for index, j in enumerate(li): if li[index] == m: print(f'{lil[index]} appears {m} consecutive times') ''' print(timeit.timeit(stmt=run1, number=1)) output: c appears 4 consecutive times a appears 4 consecutive times 0.00013008200039621443 -- https://mail.python.org/mailman/listinfo/python-list
Re: binascii.b2a vs ord()
On 2021-01-10, Chris Angelico wrote: > > Hope that helps! > Yep, now it seems more understandable what is going on. Thanks for you time. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: count consecutive elements
On 2021-01-14, Tim Chase wrote: > > seems to only return one value so seems to get odd results if I > specify something like > > get_longest("aaabcccbbb") > > which at least here tells me that "c" is the longest run, even though > aaa, bbb, and ccc are all runs of length 3. The OP didn't specify > what should happen in that case, so it would need some clarification. > > In that case maybe good solution would be to return three of them? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: count consecutive elements
On 2021-01-13, Bischoop wrote: I know what was wrong: > m = s.index(i) I forgot that m will return first index of i. So tried that way but still getting out of index although I that that I'm making sure not to get out of index. s = 'aabskaaabadh' c = 0 t = list(set(s)) # list of characters in s li=[0,0,0,0,0,0] # list for counted repeats print(t) for x in t: h = t.index(x) for index, i in enumerate(s): maximus = len(s) if i == x: c += 1 if index < maximus: if s[index +1] != x: # if next element is not x if c > li[h]: #update c if bigger than existing li[h] = c c = 0 else: if c > li[h]: li[h] = c for i in t: n = t.index(i) print(i,li[n]) print(f'{s[li.index(max(li))]} appears {max(li)} consecutive times') -- https://mail.python.org/mailman/listinfo/python-list
Re: count consecutive elements
On 2021-01-13, Bischoop wrote: > t = set(s) # set of characters in s I have this one changed to: t= list(set(s)) -- https://mail.python.org/mailman/listinfo/python-list
count consecutive elements
I want to to display a number or an alphabet which appears mostly consecutive in a given string or numbers or both Examples s= ' aabskaaabad' output: c # c appears 4 consecutive times 8bbakebaoa output: b #b appears 2 consecutive times I thought about set the string then and for each element loop the string to check if equal with element set element if so count =+1 and check if next to it is not equal add counter value to list with same index as in set. However I'm fighting to code it and the counting numbers are not right: s = 'aabskaaabad' c = 0 t = set(s) # set of characters in s li=[0,0,0,0,0,0] # list for counted repeats for x in t: h = t.index(x) for i in s: if i == x: m = s.index(i) c +=1 if s[m+1] != x: # if next element is not x if c > li[h]: li[h]= c c = 0 for i in t: n = t.index(i) print(i,li[n]) -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: binascii.b2a vs ord()
On 2021-01-10, Chris Angelico wrote: > > Trace it through, step by step. You have a series of ASCII values, > represented in binary, and then you call int() on each of them. What > sort of numbers will you get? > I'm kinda lost here about what sort of numbers I get, its class 'int'. > Then look at what chr() does when given those sorts of numbers. > > BTW, it may be helpful to look at the repr of the final string, rather > than simply printing it out. (It also may be unhelpful. If so, don't > worry about it.) > That was quite interesting text = b'This is a string' text2 = 'This is a string' res = ' '.join(format(ord(i), 'b') for i in text2) k= res.split(' ') for i in k: w= k.index(i) k[w]= int(i) s = k[0] print(type(s)) print(f'{s!r}') l = text[0] print(f'{l!r}') # output I've got: 1010100 84 -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-08, Stefan Ram wrote: > Bischoop writes: >>What I want to learn is if I need get for example four combinations, so >>how to get in a loop first letter 'a',then another step'a' and again 'a' >>and 'a', to have '' later on'abaa' etc. > > I can only guess what you want, maybe something like > > word = [] > p = 0 > > def inc_at( position ): > word[ position ]= chr( ord( word[ position ])+ 1 ) > > while True: > if len( word )< p + 1: > word =[ "a" ]+ word > print( "".join( word )) > p = 0 > o = len( word )- 1 - p > inc_at( o ) > while p < len( word ) and word[ o ]== '{': > word[ o ]= "a" > p += 1 > o -= 1 > if p < len( word ): inc_at( o ) > > ? > > Yes, it must generate 4 characters long all combination of alphabet, equivalent to: s = list(''.join(seq) for seq initertools.product(string.ascii_lowercase, repeat=4)). I must say that's quite coding you've done. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
binascii.b2a vs ord()
I wanted to learn about conversion string to Ascii. So I learn about binascii.b2a but because the output wasn't what I wanted got deeper and found out about ord(c) and actually that's what I'expected. So what's that binascii and why I cant convert ascii that I got from ord to string by using char, instead I'm getting some strings in weird coding. import binascii Ttext = b'This is a string' text2 = 'This is a string' data = binascii.b2a_uu(text) print(f' Conversion byte string to ascii by binascii:\n {data}') res = ' '.join(format(ord(i), 'b') for i in text2) print(f'Conversion string to Ascii by ord:\n {res}') b = binascii.a2b_uu(data) print(f' Conversion ascii to String by binascii:\n {b}') k= res.split(' ') for i in k: w= k.index(i) k[w]= int(i) c = ' '.join(chr(int(val)) for val in res.split(' ')) print(f'Conversion Ascii to string by chr: \n {c}') #output: Conversion byte string to ascii by binascii: b"05https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-07, Bischoop wrote: > On 2021-01-07, Chris Angelico wrote: >> >> True. Unfortunately, it doesn't work, so what you'd have is something >> that can be easily parameterized to not work on other numbers of >> characters too. :) >> > > My bad is I'm kinda maniac and have to know how to, I know best solution > itertool but... I just must know, was thinking that studing the itertool > code would give me an answer but found it's in C. > Now I try list comprehension for it, so it's another day on it for me. > > So after checking itertools doc I found what itertools.product is quivalent for on: https://docs.python.org/3/library/itertools.html#itertools.product Now I'll sleep. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-07, David Raymond wrote: > I think you might want to check out itertools.product() > https://docs.python.org/3.9/library/itertools.html#itertools.product Thanks David for contribution I find it very convenient but not knowing how to solve solution without itertools for: for a i : for b in : for c in : for d in : doesn't give me a peace. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-07, Chris Angelico wrote: > > True. Unfortunately, it doesn't work, so what you'd have is something > that can be easily parameterized to not work on other numbers of > characters too. :) > My bad is I'm kinda maniac and have to know how to, I know best solution itertool but... I just must know, was thinking that studing the itertool code would give me an answer but found it's in C. Now I try list comprehension for it, so it's another day on it for me. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Some problem in code execution in python
On 2021-01-07, Dario Dario wrote: > Sir, I am one of the user of your python program, that is after completion > of installation I got some statement like "you got code execution problem > ". I don't know how to rectify this problem.so please help me to rectify > this problem . > You send me the solution in this email ID itself . I'm not Window OS user but doesn't running program in Windows Command Shell tells also what's wrong? -- https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-07, Chris Angelico wrote: This could allow easy to change the number of characters in combination, just pass n argument to range where n is how many characters. -- https://mail.python.org/mailman/listinfo/python-list
Re: primitive password cracker
On 2021-01-07, Chris Angelico wrote: > > I'd recommend having just a string, rather than a list; it'll behave > identically for what you're doing, and it'll be a lot easier to see > when you have all the right letters. > Yes that's definitely better, I've done so. >> mineset= set() >> for a in letters: >> for b in letters: >> for c in letters: >> for d in letters: >> s = a + b + c + b > > Why is b at the end? :) That's why "zulu" could be found, but "pass" couldn't. > ha, that's typo I was working so long on it that got mixed up. and yes with 'd' it works :-) >> k = sorted(mineset) >> print(k) >> for i in k: >> if i == passe: >> print('got it: ', i ) >> print(passe in k) >> -- >> It works in someway but the problems are: >> Not all combination are made, I change password to: 'pass' and that >> combination is not in results. >> Another thing is, I had to made a set from list because combinations >> were repeated. > > Yep. I'd recommend looking at the original list rather than setting > and sorting, and you might notice patterns that hint at problems. > The problem was with that 'b' at the end, now it solved. >> for x in range(4): >> for y in letters: >> combin +=y >> lista.append(combin) >> combin='' > > Not entirely sure what your intended logic is here, but I'd advise > planning things out in pseudocode and knowing what you're actually > building. > Well :-) I tried to do shorter version of the previous code to do not do for loop for every character, range supposed to be for how long the password is, in this case four characters, once the 4character combination is made add it to the list, similarly to the previous code but my logic is wrong here. I don't have clue hot to tell: get a letter for 1 get for 2 get for 3 and get for 4. > Debugging code can be very hard, especially if you don't know what > it's doing. Fortunately, Python comes with a number of tools to help > you figure out your code; the simplest is the print function - just > add a few useful print calls to your code and trace through things > that way. You can also look at the pdb module, and various other > techniques. Explore your code, get to know how it works at each point, > and you should be able to figure things out. > > Good luck, have fun! And remember IIDPIO: If In Doubt, Print It Out! > For me is even not debbuging code is important but to do what I want and in that case is that what I mention earlier four letters picked and add them to the list, and today again I seat on it and just nothing lol. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
primitive password cracker
I was practising for educational purpose with simply password cracker. I know that I could use itertool but in my case when I'm learning I would miss facing problems and learning on them and indeed I've met one which is not giving me a peace. What I want to learn is if I need get for example four combinations, so how to get in a loop first letter 'a',then another step'a' and again 'a' and 'a', to have '' later on'abaa' etc. So I wrote that: -- import string passe = 'zulu' mylist = [] #letters = string.ascii_lowercase letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'q', 'y', 'z'] mineset= set() for a in letters: for b in letters: for c in letters: for d in letters: s = a + b + c + b mylist.append(s) mineset=set(mylist) k = sorted(mineset) print(k) for i in k: if i == passe: print('got it: ', i ) print(passe in k) -- It works in someway but the problems are: Not all combination are made, I change password to: 'pass' and that combination is not in results. Another thing is, I had to made a set from list because combinations were repeated. And finally, I was struglling with making it in without creating four loops for four letters, something like that: To try to solve those I went with that approach: - letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'q', 'y', 'z'] password = 'pass' combin = '' lista=[] for x in range(4): for y in letters: combin +=y lista.append(combin) combin='' mineset=set(lista) print(mineset) for i in lista: if i == password: print('pass:', i) --- But the results are disspainting: {'abc', 'a', 'ab', 'abcd', 'abcde'} I was seating on it for a long day but can't even closely achieve similar effect to 4 loops in previous code. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: A random word from one of two lists
On 2021-01-02, Stefan Ram wrote: > Bischoop writes: >>On 2021-01-02, Stefan Ram wrote: >>>Otherweise, I'd go this way without a dictionary. >>>import random >>>animal = ['koala', 'kangaroo'] >>>fruit = ['banana', 'apple'] >>>kinds = [animal,fruit] >>>kind = random.choice( kinds ) >>>result = random.choice( kind ) >>>print( result ) >>I had that solution in mind but I thought that one is not good >>programming style or not Pythonin :-) > > I do not see any stylistic problem when you use this approach > with "nested lists". List indexing by a number should even be > faster than indexing a dictionary. > > Now I know that's ok, seems I was ovethingking while solution was so simply. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: A random word from one of two lists
On 2021-01-02, Stefan Ram wrote: > > The following might /not/ be good programming style, > but addresses the idea to choose a "variable". > I kinda like the below one. > import random > animal = ['koala', 'kangaroo'] > fruit = ['banana', 'apple'] > kinds = ['animal','fruit'] > variable = random.choice( kinds ) > result = random.choice( globals()[ variable ]) > print( result ) > > Otherweise, I'd go this way without a dictionary. > import random > animal = ['koala', 'kangaroo'] > fruit = ['banana', 'apple'] > kinds = [animal,fruit] > kind = random.choice( kinds ) > result = random.choice( kind ) > print( result ) > I had that solution in mind but I thought that one is not good programming style or not Pythonin :-) -- Thanks > -- https://mail.python.org/mailman/listinfo/python-list
Re: A random word from one of two lists
On 2021-01-02, Python wrote: > > >>> from random import choice > >>> choice(words[choice(list(words.keys()))]) > 'apple' > >>> choice(words[choice(list(words.keys()))]) > 'kangaroo' > >>> choice(words[choice(list(words.keys()))]) > 'koala' > >>> choice(words[choice(list(words.keys()))]) > 'apple' > >>> choice(words[choice(list(words.keys()))]) > 'kangaroo' > > or this? > > >>> randstuff = lambda: choice(words[choice(list(words.keys()))]) > >>> randstuff() > 'kangaroo' > >>> randstuff() > 'kangaroo' > >>> randstuff() > 'apple' > >>> randstuff() > 'kangaroo' > >>> randstuff() > 'koala' > >>> randstuff() > 'banana' that lambada method is good. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: A random word from one of two lists
On 2021-01-01, Cameron Simpson wrote: > > kinds = list(words.keys()) > Yes, solved it with that exeactly. -- thanks -- https://mail.python.org/mailman/listinfo/python-list
A random word from one of two lists
I have two lists *animal* and *fruit* and I try to get a random variable animal or fruit and then random word from that list. I thought that dictionary(*words*) could help me but no succes, the only way I've done partially what was with list *kinds* and by using two times random.choice. However print(kind) return me a list not a variable: animal or fruit so now I'm kinda confuse if I can achieve that. import random animal = ['koala', 'kangaroo'] fruit = ['banana', 'apple'] kinds = [animal,fruit] words = {'animals': animal, 'fruits': fruit} kind = random.choice(kinds) print(kind) word = random.choice(kind) print(word) #output: ['kolala', 'kangaroo'] kangaroo -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Which method to check if string index is queal to character.
On 2020-12-29, jak wrote: > > you could try this way: > > # --- > from dns import resolver as dns > > emails=['john@fakeserver.bah', > 'john@gmail.com'] > > for ue in emails: > try: > mxl = dns.resolve(ue.split('@')[1], 'MX') > except: > print(f'{ue}: bad mail server') > else: > if len(mxl) > 0: > print(f'{ue}: valid mail server') > # --- > > ... so, having verified the sever, you should only worry about the name. I actually have tried, that's good idea. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Which method to check if string index is queal to character.
On 2020-12-28, Michael Torrie wrote: > On 12/28/20 10:46 AM, Marco Sulla wrote: >> On Mon, 28 Dec 2020 at 17:37, Bischoop wrote: >>> >>> I'd like to check if there's "@" in a string and wondering if any method >>> is better/safer than others. I was told on one occasion that I should >>> use is than ==, so how would be on this example. >>> >>> s = 't...@mail.is' >> >> You could do simply >> >> if "@" in s: >> >> but probably what you really want is a regular expression. > > https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/ > Interested article. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Which method to check if string index is queal to character.
On 2020-12-28, Mats Wichmann wrote: > On 12/28/20 10:46 AM, Marco Sulla wrote: >> On Mon, 28 Dec 2020 at 17:37, Bischoop wrote: >>> >>> I'd like to check if there's "@" in a string and wondering if any method >>> is better/safer than others. I was told on one occasion that I should >>> use is than ==, so how would be on this example. >>> >>> s = 't...@mail.is' >> >> You could do simply >> >> if "@" in s: >> >> but probably what you really want is a regular expression. >> > > Will add that Yes, you should always validate your inputs, but No, the > presence of an @ sign in a text string is not sufficient to know it's a > valid email address. Unfortunately validating that is hard. > Nah, by saying if is valid I meant exeactly if there's "@", I could add yet if endswith() but at this point @ is enough. Yes the only possible way for full validation would be just sending email and waiting for reply. -- https://mail.python.org/mailman/listinfo/python-list
Re: Which method to check if string index is queal to character.
On 2020-12-28, Stefan Ram wrote: > > "@" in s > That's what I thought. >>I want check if string is a valid email address. > > I suggest to first try and define "valid email address" in English. > > A valid email address consists of an email prefix and an email domain, both in acceptable formats. The prefix appears to the left of the @ symbol. The domain appears to the right of the @ symbol. For example, in the address exam...@mail.com, "example" is the email prefix, and "mail.com" is the email domain. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Which method to check if string index is queal to character.
I'd like to check if there's "@" in a string and wondering if any method is better/safer than others. I was told on one occasion that I should use is than ==, so how would be on this example. s = 't...@mail.is' I want check if string is a valid email address. code ''' import time email = "t...@mail.tu" start_time = time.time() for i in range(len(email)): print('@' in email[i]) print ("My program took", time.time() - start_time, "to run") print('--') start_time = time.time() for i in range(len(email)): print(email[i] == '@') print ("My program took", time.time() - start_time, "to run") print('--') start_time = time.time() if '@' in email: print('True') print ("My program took", time.time() - start_time, "to run") ''' -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Bischoop wrote: > On 2020-12-17, Dennis Lee Bieber wrote: >>> >> >> The main concern is that you are using a RECURSIVE call. It is much >> better for such input checking to use an ITERATIVE (loop) scheme. >> >> def marriage(): >> #loop forever >> while True: >> #get response from user >> maritals = input("Married: Yes/No ?").title() >> #if response is good, exit (break) the loop >> if maritals in ["Yes", "No"]: break >> #otherwise display error message and repeat loop >> print("Try again. Please respond with Yes or No") >> #return valid response >> return maritals >> >> > It makes sense for me now, better logic used here than mine. > I've never met that way used in * if maritals in ['Yes', No']: * , > it makes code elegant. > So it's not good to use calling function itself (recursive call), I get it > now. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Dennis Lee Bieber wrote: >> > > The main concern is that you are using a RECURSIVE call. It is much > better for such input checking to use an ITERATIVE (loop) scheme. > > def marriage(): > #loop forever > while True: > #get response from user > maritals = input("Married: Yes/No ?").title() > #if response is good, exit (break) the loop > if maritals in ["Yes", "No"]: break > #otherwise display error message and repeat loop > print("Try again. Please respond with Yes or No") > #return valid response > return maritals > > It makes sense for me now, better logic used here than mine. I've never met that way used in * if maritals in ['Yes', No']: * , it makes code elegant. So it's not good to use calling function itself (recursive call), I get it now. -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-17, Peter J. Holzer wrote: > > --EVF5PPMfhYS0aIcm > Content-Type: text/plain; charset=us-ascii > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On 2020-12-17 03:06:32 -, Bischoop wrote: >> pasting from my IDE to vim/slrn was messing syntax, > > You can=20 > >:set paste Indeed, thanks I just didn't come to conclusion that it has to be special paste mode to paste without breaking the lines. Also adding in * set pastetoggle= * in vimrc activates paste mode when pressing F2, I find it more convenient. > -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-17, dn wrote: >> After expiry, any posts 'here' with links to 'there', will be useless. >> >> I do mind that however I thoght it better if paste a whole code to see >> and pasting from my IDE to vim/slrn was messing syntax, I'll do better >> next time. > > > Yes, it can be difficult to know how much code to include and how much > can be left-out. Don't worry about that - replies can always trim any > excess. > I solved the pasting problem but about triming the excess, well some people don't give a fuck and don't cut unecessary lines. I'm pretty sure that if I post a 100 line code, some will reply without cutting it just to point what's wrong in line 50 lol. > Also, don't be concerned about such comments. Rather than complaints, > please regard them as advice from folk who have been 'here' and/or using > Python for some time. I'm not concerned at all :-) I'm using newsgroups,irc for good over 20 years so I don't bother. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Michał Jaworski wrote: > > Exactly. I would go even further and make it a reusable function. Eg. > > def prompt_choices(prompt, choices): > choices = set(c.lower() for c in choices) > while value := input(f"{prompt} {choices}:").lower() not in choices: > pass > return value > > Or without := operator: > > def prompt_choices(prompt, choices): > value = None > choices = set(c.lower() for c in choices) > while value not in choices: > input(f"{prompt} {choices}:").lower() > return value > > That way you can use it as follows: > > marital = prompt_choices("Married", ["yes", "no"]) > Oh man that really not like they teach in tutorials. These are the examples at which you look and think: moment, I need a few sec to follow :-) >> So in other words I shoudn't nest functions like in >> changes(), add_people() etc but keep >> everything in one functions. > > Simply move those functions outside of their "hosting" functions and > call them as they are. Also, many of them won't be needed anymore as you > introduce some generic helper functions (e.g. prompt_choices). > Honestly I've done it like that because I thought that would be more elegant way to have how_old(), marriage() etc hosted in add_people() but I'm glad I've done this time because learn a bit, I had quite a problem to keep people argument storing and returning in every function, I see it was unecessary as I know now but another experience. >> Now I'll learn OOP as you said and then try to made this program again >> with OOP from scratch. > > Recommend polishing the procedural approach a bit more too, though. Like > reducing code repetition. Looking into how data is stored, eg. can fields > be stored in CSV columns instead of JSON? OOP can be overwhelming at the > very beginning. For instance it can take some time learning what should be > an object and what shouldn't. You definitely can start adding e.g. > dataclasses because they are more like structures (e.g. struct in C > mentioned earlier). > Right I keep it in mind. Yes, the storing you mention I'll have to improve, even the json I've done sucks because I've noticed it storing everything in one column lol I thought that json library handles it itself but apparently I have to tell him about it to insert key,values into different columns. -- Dzieki -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Michael Torrie wrote: > On 12/17/20 9:10 AM, Bischoop wrote: >> Could you expand here, I rather don't know how I could do it different >> way apart from if maritals == 'Yes' or maritals == 'No' or is it what >> you meant? > > I think he's hinting at using a loop instead. > > while maritals != 'Yes' and maritals != 'No': > maritals = input('Married: Yes/No ?: ').title() > > I think I got the logical condition right. Sometimes those are tricky! I think you're right. Yes those are tricky sometimes :-) Look how I had it previously: def marriage(): maritals = input('Married: Yes/No ?: ').title() while maritals != 'Yes' and maritals != 'No': return marriage() return maritals marital = marriage() When looking at it now I couldn't find the dumbest way for it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Messed up syntax in Vim when pasting python code to post to the groups.
On 2020-12-17, 2qdxy4rzwzuui...@potatochowder.com <2qdxy4rzwzuui...@potatochowder.com> wrote: > > I'm not a vim user, but it just came up to look into the paste and > nopaste commands. I've googled the matter and found pressing F2 toogles 'paste' mode and then after pasting F2 again to switch off paste mode or manually :set paste :set nopaste https://vim.fandom.com/wiki/Toggle_auto-indenting_for_code_paste -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Messed up syntax in Vim when pasting python code to post to the groups.
On 2020-12-17, Bischoop wrote: > > I've being asked not to use external links for code sharing to the > groups but when I paste the code in to my vim editor I do use with slrn > client the code is just messed up. > How dear people people using vim solved this? Solved, partialy. Paste mode F2, however after pasting clicking F2 again supposed to go to paste option OFF but in my case it's still pasting without messing syntax, but yes I can paste with correct syntax. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Messed up syntax in Vim when pasting python code to post to the groups.
I've being asked not to use external links for code sharing to the groups but when I paste the code in to my vim editor I do use with slrn client the code is just messed up. How dear people people using vim solved this? -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Michał Jaworski wrote: Thanks for feedback and useful tips. I couldn't use any OOP here because have not a clue about it, just going to go toward it. > I've made a quick look at the code and even executed it. It looks pretty > clear and is easy to understand, although it has some structural problems. > I won't do a thorough review but highlight the most important problems. > > First, the recursive user input pattern you use: > def marriage(): > maritals = input('Married: Yes/No ?: ').title() > while maritals != 'Yes' and maritals != 'No': > return marriage() > return maritals > > > def marriage(): > ... > Could you expand here, I rather don't know how I could do it different way apart from if maritals == 'Yes' or maritals == 'No' or is it what you meant? > You shouldn't be doing that unless you need a closure with nonlocal > variables to read from. Otherwise it really harms the readability. I > understand the urge to keep relevant code close to the usage but you would > have better results with modules. If you really want to keep everything in > a single module, keep functions close together in the file but don't nest > them. Use relevant naming conventions instead. Simply think of how you > would write that in C. You could use some object-oriented approach too, but > I would recommend polishing structural programming first. > Well I don't know C, the only other language I was learning it was basic for Atari :-) So in other words I shoudn't nest functions like in changes(), add_people() etc but keep everything in one functions. > There are also other issues like not always closing files, and not > validating the user input in specific places. Still, these will be more > evident as you improve the structure of application and do thorough > testing. Anyway, the code doesn't look bad. It of course needs improvement > but I've also seen worse specimens from people being actually paid for > writing the code. > > Remember that "how to make things better" is a function of few parameters: > - what you want to achieve > - what are you able to do > - how much time do you have > > If your sole goal is to learn and improve skills, I would recommend > polishing this in current procedural fashion to some extent, but not trying > to make it perfect. Then I would start from scratch and experiment with > different paradigms (OOP for instance). Then I would try to make a smaller > project that has some actual utility. > Yes, I was pretty much interested in Python at the end 90s however life made me putting this hobby away and now life changed again so I've more free time and I'm happy be back with Python so after couple months learning it again and writing few liners this is first thing that got me to use what I've learnt so far and gave opportunity to solve moany problems I had to deal with (had few nights without sleep ) :-) Now I'll learn OOP as you said and then try to made this program again with OOP from scratch. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Review, suggestion etc?
On 2020-12-17, Bischoop wrote: Accidently removed the paste, https://bpa.st/E3FQ -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-17, dn wrote: > Remember that posts to the list are archived, and thus may be searched. > People experiencing similar problems in-future will be able to 'mine' > the archives for help and advice. > > Using a/any pastebin is great for immediate sharing. Remember that in > this case their links expire/the bin 'disappears'. > > After expiry, any posts 'here' with links to 'there', will be useless. I do mind that however I thoght it better if paste a whole code to see and pasting from my IDE to vim/slrn was messing syntax, I'll do better next time. -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-12, Terry Reedy wrote: > > Don't post links to unknown sites. Reduce it to the minimum needed to > exhibit the questionable behavior and include inline with the question. > >> How this functions should look properly? > > I've solved the problem. BTW bpa.st/+python is well known for code sharing among Python communities it's alternative to pastebin.com. -- https://mail.python.org/mailman/listinfo/python-list
Review, suggestion etc?
I've done my biggest project that allowed me to learn a lot. It's basically simply Database with basic options >> https://bpa.st/FU4A . What sucks here is basically the find_people() I'll have to work on it yet to make it more useful. . If anyone was bored and wished to point me some wrong way or suggest a better one I'd appreciate. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12, Tim Chase wrote: > > Hopefully this gives you the hints that you need to troubleshoot. > > -tkc > > > > Yes it explains a lot. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Unable to pass dict from json.
Here https://bpa.st/YBVA I've working code with dictionary only if used dict from the code (it's commented now) but when I load it I can print it from load function (line 14) but at all have not a clue how to pass the data so could use them. I've learnt a lot when making it but here I'm completetly stuck, was trying do solve it for a whole day and it's just a death wall for me. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
Got it solved here: https://bpa.st/BFJA -- https://mail.python.org/mailman/listinfo/python-list
To check if number is in range(x,y)
I need to check if input number is 1-5. Whatever I try it's not working. Here are my aproaches to the problem: https://bpa.st/H62A What I'm doing wrong and how I should do it? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
I've also convert the choice to int() but doesn't help. -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12, Oscar wrote: > In article , > Bischoop wrote: >>I've also convert the choice to int() but doesn't help. > > Oh.. did not read this yet. How did you do this? In both places after > the input or during the comparison? If so, in which version? Only the > first version would work. The other two are just plain wrong. after the input, https://bpa.st/BFJA -- https://mail.python.org/mailman/listinfo/python-list
Re: Letter replacer - suggestions?
On 2020-12-07, Grant Edwards wrote: > On 2020-12-07, MRAB wrote: > >> Avoid a 'bare' except unless you _really_ mean it, which is >> virtually never. Catch only those exceptions that you're going to >> handle. > > And sometimes "handling" is just printing some extra stuff and then > re-raising the original exception: > > try: > something(): > except: > print() > raise > > Noted, thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-12, Joe Pfeiffer wrote: > Bischoop writes: > >> I've function asking question and comparing it, if is not matching 'yes' >> it does call itself to ask question again. The problem is that when >> function is called second time it returns old value or with additional >> else statement it returns none. >> >> Code: https://bpa.st/KVGA > > It calls itself again, but what does it return in that case? I've stated it returns old value that I've input first time, anyway output is also inluded in a paste but since you've asked: def question(): ask = input("Are you OK?:").lower() if ask != 'yes': question() return ask print (question()) #output: Are you OK?:no Are you OK?:no Are you OK?:yes no --- #Another way with 'elif' statment returns none def question(): ask = input("Are you OK?:").lower() if ask != 'yes': question() elif ask == 'yes': return ask print (question()) #output: Are you OK?:no Are you OK?:yes None #Tried also nested functions, same results: def question(): ask = input("Are you OK?:").lower() def check_question(n): if ask != 'yes': question() else: return ask m = check_question(ask) print (m) question() #output: Are you OK?:no Are you OK?:yes None Process finished with exit code 0 -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
On 2020-12-12, dn wrote: > On 12/12/2020 14:25, Bischoop wrote: >> >> >> >> I've function asking question and comparing it, if is not matching 'yes' >> it does call itself to ask question again. The problem is that when >> function is called second time it returns old value or with additional >> else statement it returns none. >> >> Code: https://bpa.st/KVGA >> >> How this functions should look properly? > > > In the event of "yes" the function returns a value (return ask). > When the function calls itself, what happens to the return-ed value? Well I've put the output in a paste as well, anyway here is what is in a paste: def question(): ask = input("Are you OK?:").lower() if ask != 'yes': question() return ask print (question()) #output: Are you OK?:no Are you OK?:no Are you OK?:yes no --- #Another way with 'elif' statment returns none def question(): ask = input("Are you OK?:").lower() if ask != 'yes': question() elif ask == 'yes': return ask print (question()) #output: Are you OK?:no Are you OK?:yes None #Tried also nested functions, same results: def question(): ask = input("Are you OK?:").lower() def check_question(n): if ask != 'yes': question() else: return ask m = check_question(ask) print (m) question() #output: Are you OK?:no Are you OK?:yes None Process finished with
Re: Letter replacer - suggestions?
On 2020-12-07, Marco Sulla wrote: > Not sure why you want to do this (it's schoolwork)? >Anyway, this is my version: > Thanks, seems nicer I think not to mention those exceptions. So far I'm just learning and doing everythin only for myself so do not think on others users but I know it's good to make a habit. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Letter replacer - suggestions?
On 2020-12-07, MRAB wrote: > > word = input( f'input word you want to change letters in: ') Yes, I've learn already that should use only when want to use variables I just started using this new f' string method. > > There's no need for the f prefix. > > > print(f' Your word to change: ,{word}') > > Is the comma a typo? > lol mixing old and new methods, just old habit. > > > change_this_list = list(change_this) > > replace_with_list = list(replace_with) > > > > while True: > > try: > > for element in word_list: > > for x in change_this_list: > > if element == x: > > to = word_list.index(element) > > replace = change_this_list.index(x) > > word_list[to] = replace_with_list[replace] > > new_word = ''.join(word_list) > > print(f'{new_word}') > > > You can make it a lot shorter and faster by using a dict. The entire > while loop section can be replaced with: > > replacements = dict(zip(change_this, replace_with)) > new_word = ''.join(replacements.get(letter, letter) for letter in word) > print(new_word Simply and nice, I wouldn't come with that yet at all, beyond my knowledge. Thanks a lot for feedback and suggestions. -- https://mail.python.org/mailman/listinfo/python-list
Function returns old value
I've function asking question and comparing it, if is not matching 'yes' it does call itself to ask question again. The problem is that when function is called second time it returns old value or with additional else statement it returns none. Code: https://bpa.st/KVGA How this functions should look properly? -- Thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Letter replacer - suggestions?
I worked on my wee script that replaces a letters: https://bpa.st/OYBQ . I would like to have some suggestions about the code from more experienced programmers, the code does work and do its job but perhaps could work in a better way. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem with rearanging list with paired letters next to each others
On 2020-11-11, MRAB wrote: >> > Points to note in your first code: > > 1. Modifying a list while iterating over it is a bad idea. > > 2. You're modifying the list that you're passing in and also returning > it. That's a bad idea. Either modify it in place or modify and return a > copy. > > 3. The line: > > m = (letter_list.index(x)) > > returns the position of the first occurrence of x. > > Points to note in your second code: > > 1. (See above) > > 2. (See above) > > 3. (See above) > > 4. 'i' goes from 0 to len(letter_list)-1, so i+1 goes from 1 to > len(letter_list), but the maximum index permitted by letter_list is > len(letter_list)-1, hence letter_list[i+1] will raise IndexError on the > last iteration. > > 5. 'i' goes from 0 to len(letter_list)-1, so i-1 goes from -1 to > len(letter_list)-2. letter_list[-1] returns the last (final) letter in > the list, and it's treated as a true. > > 6. This: > > x != letter_list[i+1] and letter_list[i-1] > > is checking whether: > > x != letter_list[i+1] > > is true and also whether: > > letter_list[i-1] > > is true. I see now I overcomplicated it, what is a good idea then? -- https://mail.python.org/mailman/listinfo/python-list
Problem with rearanging list with paired letters next to each others
Can anybody help?Here's the code that gives me a hedeache for second day https://bpa.st/XLOA If I have letter_list = ["a","a",,"b","b","c","c"] it's working correctly but if I have three or more of any letters for example:letter_list = ["a","a","a","b","b","c","c"], I'm ending up with some pairs somewhere. I took another way approach today: https://bpa.st/E7HQ, was thinking about iterating and checking if neighbour characters won't make a pair but I've end up with error: if x != letter_list[i+1] and letter_list[i-1]: IndexError: list index out of range andin addition: got 4 "a" (had 3only) and missing 1 "b" :-/ -- https://mail.python.org/mailman/listinfo/python-list
Any better way for this removal?
So I was training with slicing. Came to idea to remove text after second occurence of character, below is how I've figured it out, I know if it works it good but how you guys would made it in more pythonic way? text = "This is string, remove text after second comma, to be removed." k= (text.find(",")) #find "," in a string m = (text.find(",", k+1)) #Find second "," in a string new_string = text[:m] print(new_string) -- https://mail.python.org/mailman/listinfo/python-list
Re: strip() method makes me confused
On 2020-11-07, Alexander Neilson wrote: > Because the strip methods argument is the set of characters to remove from > either end. So it checks from the ends character by character until it finds > a character that isn’t in the set. Then it removes everything prior to that > (or after that at end of the string) and then returns the result. > > So your first example leaves “banana” as the string because all characters > after and before that string in the original string were found in the set. > > However in your second example the set only contains the comma and the string > neither begins nor ends with commas so if (first character) in (set > containing comma) returns false so it stops searching from that end and does > the same at the other end. > > https://www.programiz.com/python-programming/methods/string/strip > Yes, I got it know. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: strip() method makes me confused
On 2020-11-07, Frank Millman wrote: > On 2020-11-07 1:28 PM, Frank Millman wrote: >> On 2020-11-07 1:03 PM, Bischoop wrote: >>> > [...] >>> >>> another example: >>> >>> text = "this is text, there should be not commas, but as you see there >>> are still" >>> y = txt.strip(",") >>> print(text) >>> >>> output: >>> this is text, there should be not commas, but as you see there are still >>> >> > > P.S. If you wanted to remove all the commas, you could do it like this - > > y = txt.replace(',', '') > > I understand now what is happening thanks. Yes, I know about replace, it just was bothering me about those examples I've gave earlier. Thanks -- https://mail.python.org/mailman/listinfo/python-list
strip() method makes me confused
According to documentation strip method removes heading and trailing characters. Why then: txt = ",rrttggs...,..s,bananas...s.rrr" x = txt.strip(",s.grt") print(x) output: banana another example: text = "this is text, there should be not commas, but as you see there are still" y = txt.strip(",") print(text) output: this is text, there should be not commas, but as you see there are still -- https://mail.python.org/mailman/listinfo/python-list
Re: Incoming datas difficult to read "\r\n" and "\n"
On 2020-11-06, Chris Angelico wrote: > On Fri, Nov 6, 2020 at 11:51 PM Bischoop wrote: >> >> On 2020-11-06, Chris Angelico wrote: >> >> > You're currently dumping out the raw bytes. Not very interesting, and >> > that's why it's not easy to read. I would recommend (a) decoding the >> > bytes to text, and (b) splitting it on "\r\n", thus getting it >> > line-by-line. >> > >> > What you may want to consider, though, is using an actual IRC library. >> > It'll handle all kinds of details for you :) >> > >> >> right >> >> I've changed the line to: >> print(data.decode('utf8')) >> >> and prints it now nice but not sure how to apply yet: >> >> print (string.splitlines( )) >> >> and PING PONG matter. > > Cool. You're going to have to iterate over the lines and process each > one individually. IRC is a line-based protocol and every line has its > own meaning. But, again, this is where an IRC library would help > enormously; it'll do all of that parsing (including taking care of > edge cases that you might not have thought of), and let you just > handle the parts that are interesting, like responding to specific > messages from people. Yes, I know about irc libraries but I do it for educational purposes, when wrtiting it myself I do learn all the time new things. -- https://mail.python.org/mailman/listinfo/python-list
Re: Incoming datas difficult to read "\r\n" and "\n"
On 2020-11-06, Chris Angelico wrote: > You're currently dumping out the raw bytes. Not very interesting, and > that's why it's not easy to read. I would recommend (a) decoding the > bytes to text, and (b) splitting it on "\r\n", thus getting it > line-by-line. > > What you may want to consider, though, is using an actual IRC library. > It'll handle all kinds of details for you :) > right I've changed the line to: print(data.decode('utf8')) and prints it now nice but not sure how to apply yet: print (string.splitlines( )) and PING PONG matter. -- https://mail.python.org/mailman/listinfo/python-list
Incoming datas difficult to read "\r\n" and "\n"
I'm experimenting with irc bot. I've made it connecting, reading etc but everything is difficult to read. It's coming like one long string without breaking lines. How to mace it printing in new line after: \r\n or \n in data? -- b':weber.freenode.net 001 saaaki :Welcome to the freenode Internet Relay Chat Network saaaki\r\n:weber.freenode.net 002 saaaki :Your host is weber.freenode.net[162.213.39.42/6667], running version ircd-seven-1.1.9\r\n:weber.freenode.net 003 saaaki :This server was created Wed Dec 18 2019 at 21:37:52 UTC\r\n:weber.freenode.net 004 saaaki weber.freenode.net ircd-seven-1.1.9 DOQRSZaghilopsuwz CFILMPQSbcefgijklmnopqrstuvz bkloveqjfI\r\n:weber.freenode.net 005 saaaki CHANTYPES=# EXCEPTS INVEX CHANMODES=eIbq,k,flj,CFLMPQScgimnprstuz CHANLIMIT=#:120 PREFIX=(ov)@+ MAXLIST=bqeI:100 MODES=4 NETWORK=freenode STATUSMSG=@+ CALLERID=g CASEMAPPING=rfc1459 :are supported by this server\r\n:weber.freenode.net 005 saaaki CHARSET=ascii NICKLEN=16 CHANNELLEN=50 TOPICLEN=390 DEAF=D FNC TARGMAX=NAMES:1,LIST:1,KICK:1,WHOIS:1,PRIVMSG:4,NOTICE:4,ACCEPT:,MONITOR: EXTBAN=$,ajrxz CLIENTVER=3.0 SAFELIST ELIST=CTU KNOCK :are supported by this server\r\n:weber.freenode.net 005 saaaki CP -- My code: -- while 1: time.sleep(2) data=s.recv(2040) print(data) if data.find(b"PING"): s.send(b"PONG :pingis") - -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, duncan smith wrote: >> > from collections import Counter letters = 'att' letter_counts = Counter(letters) word = 'tolerate' wd_counts = Counter(word) for char, cnt in letter_counts.items(): > print (cnt == wd_counts[char]) > > > True > True word = 'auto' wd_counts = Counter(word) for char, cnt in letter_counts.items(): > print (cnt == wd_counts[char]) > > > True > False > > or, equivalent to the above loop, but breaking when the first False is > generated and returning the single Boolean that you're after, > all(cnt == wd_counts[char] for char, cnt in letter_counts.items()) > False > > There's still a lot of scope for improvement, but possibly not by doing > simple things lol I'm thinking about it for a couple days and you guys coming with few ideas to it like it's nothing. Pity I've wasted a decade with woman, now probably to old to learn anything new. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, Chris Angelico wrote: > > This seems strangely backwards for a Scrabble game. Normally you would > have a set of available tiles, and you have to form a word using only > those tiles, but it doesn't necessarily have to use them all. You seem > to have something where you must use all the tiles you have, and may > use any number of others. But, no matter; it can be done either way. > I know, it's useless I just came to idea to do something when was learning, now I remembered long time ago I've done it somehow with list and len() probably, this time I came to idea to rewrite using count. But it seems I'm crap and takes me hell a lot of time to get on it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-03, dn wrote: > > > The (full) specs are not clear. There's certainly room for > misunderstanding. I'd be happier if I could 'see' a full spec or > recognise a practical application, because then we'd be better able to > discuss facts. Meantime, we try to help with what we have been given... > > > The OP's sample code only realises "conforming word[s]" (good term > BTW!). The snippet does not report any "count". Similarly, there's no > facts to avoid ("I assume") an assumption about whether "Letters" may > include duplication - indeed: whether duplication has meaning or should > be regarded as user-error. > Let me clarify what I want to do: We all know Scrabble game. there's a file with Dictionary containing word in each line, the idea is to input some letters for example mentioned earlier: att, the script supposed to find all words in which letters: 'a','t','t' occur and print these words. It supposed not to print word: 'auto' because there's only one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the criteria becase we have in these words one 'a' and two 't' as user has input. I've checked collections counter but seems to complicated for me at this stage yet and I'm struggling with applying it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-02, dn wrote: > > > If you have a working Py2 version, once print-statements were changed > into functions, what errors were thrown-up? > > That was almost 15 if no more years ago when I was learning then had a long break beacause Life :-) Got married, working as Chef, now have some more time, working part time so a got back to old hobby and learning again, however I see now with age everything is going slower lol > Multiple loops written in Python are likely to be slower than same in > compiled code - which was probably part of the motivation for @Terry's > response. Plus, "re-use" - why write something ourselves if someone else > has already done the work? > For educating purposes? > > How about a change of tactics? > > - str.find() or .index() will locate a character within the string > (starting from character[0]/the left-hand side) > - if this fails, tears will fall... > - repeat, from the right > - if both results are the same character/position, it must be unique > within the string > - repeat for each character in "Letters" > > This process assumes that built-in functions are faster than exhaustive > scans written in Python, and thus (presumably) also that the number of > "Letters" is small in comparison with the lengths of words. > ha, everything seems easy only if you know that. Sorry mate, for you it's obvious for me: oh, OK. > > Once the algorithms are proven, a speed comparison might be an > interesting exercise... > > For extra credit: once you've solved both, and compared the alternatives > on your machine; post the code (and test data), and ask various > colleagues 'here' to repeat the speed/performance comparisons on other > machines. > > Will/should the results be identical? I'll look into that tomorrow, your sugestions guys and hopefully I've achieve these goals. Thanks again -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-01, duncan smith wrote: >> > > But this generates the letters counts for each word. They only need to > be generated once (outside the for loop). And using count requires > iterating over the letters / words for each x in letters (rather than > once). For a large enough collection of words you'd notice the difference. > You're pretty much right, it doesn't go too fast. I've done this years ago with Python2, had a bit free time now and wanted to ReLearn Python from starting old projects I've done in past but can't remember how I made it working lol. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find word by given characters
On 2020-11-01, Bischoop wrote: > I'm working on a script i which user inputs letters and then a printed > words containing those letters. The scripts works however I can't solve > one problem , it prints also words in which these letters occur more > than once. > --- > Fore example: > Letters: at > Output: auto, autobahn. > --- > > I supposed to not print word: "autobahn" because I've given it only one > letter "a". > Problem's solved. for word in words: if all(word.count(x) == letters.count(x) for x in letters): print(word) - Thanks for suggestions, I didn't had to use counter but going to look into as it seems useful and interesting. Thank You -- https://mail.python.org/mailman/listinfo/python-list
Find word by given characters
I'm working on a script i which user inputs letters and then a printed words containing those letters. The scripts works however I can't solve one problem , it prints also words in which these letters occur more than once. --- Fore example: Letters: at Output: auto, autobahn. --- I supposed to not print word: "autobahn" because I've given it only one letter "a". Here is a link to the code: https://bpa.st/UTAA Thanks in advance -- https://mail.python.org/mailman/listinfo/python-list
Re: Downloading Python
On 2020-07-31, Stefan Ram wrote: > > Don't download just IDLE in isolation. > > Instead download Python 3.8 from www.python.org/downloads > and properly install it following the installation > instructions for your operating system. > > This will then include IDLE. > > He's right. -- https://mail.python.org/mailman/listinfo/python-list
Re: python installation help
On 2020-07-10, Deepak Didmania <6073sum...@gmail.com> wrote: > please help me in installing python Well I don't think anybody here has a Wizard Glass Ball. You need to state what is your problem, what erro message you have during istallation. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Beginner] Spliting input
On 2020-06-25, Andrew Bell wrote: > Without knowing the problem you're having, it's hard to answer. > This seems generally correct. > > Error track: Traceback (most recent call last): File "splitting.py", line 1, in numb1,numb2=input("enter 1st and 2nd no ").split() ValueError: not enough values to unpack (expected 2, got 1) -- https://mail.python.org/mailman/listinfo/python-list
[Beginner] Spliting input
I try to split input numbers, for example: 12 so I cant add them, I tried separated split(' ') but it's not working. Any ideas how to do this? * numb1,numb2=input("enter 1st and 2nd no ").split() Avg=(int(numb1) + int(numb2)) / 2 print(Avg) * -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: close() the file when opening "with"?
On 2020-06-14, Chris Angelico wrote: > On Sun, Jun 14, 2020 at 8:16 PM Bischoop wrote: >> >> >> So far I learnt "with" closes the file opened therefore "Generally" no >> need to close() file. I'm worry about this "Generally", then close() or >> not? > > Where did you learn that? Can you cite a reference? > > If you use a with block, the file is guaranteed to be closed as you > exit that block. It's that simple. > > ChrisA Where I learnt what that "with" closes the file or that "Generally" no need to close() file when using "with"? -- https://mail.python.org/mailman/listinfo/python-list
close() the file when opening "with"?
So far I learnt "with" closes the file opened therefore "Generally" no need to close() file. I'm worry about this "Generally", then close() or not? -- https://mail.python.org/mailman/listinfo/python-list
change surface
I'm playing with pygame, https://bpa.st/6GOQ Not sure what is wrong here that object moves but draws another surface. -- https://mail.python.org/mailman/listinfo/python-list
Re: Phyton 32 or 64 bit?
On 2020-05-26, Alex Kaye wrote: > To all: > > The only stupid question is one that wasn't asked ! > > Alex > Well, visit FB and you'll change your mind. -- https://mail.python.org/mailman/listinfo/python-list
Re: Having trouble importing the python turtle on idle
On 2020-05-16, KINGHAMED io wrote: > On Sat, 16 May 2020 at 4:38 PM KINGHAMED io > wrote: > >> Hello my name is Hamed >> I have purchased python for kids. >> I have installed idle and Python launcher 3.8.3 with my 11 inch MacBook >> Air (Mac OS Sierra)version 10.12.6 >> I have followed all the instructions all the way through for installation >> I even downloaded activetcl and had no issues with instructions until >> chapter 4 page 45 >> which is importing the python turtle on to my screen. >> However I have troubleshooted every possible way to get this right even >> uninstalling and reinstalling Python several times. >> Can you please advise me on how to import the python turtle. >> -- https://mail.python.org/mailman/listinfo/python-list
Re: Why Python has no equivalent of JDBC of Java?
On 2019-05-19, Marco Sulla wrote: >blablabla >blablablalbla >blablalblalbalblabla There's no perfect language mate, in some one is easier in other not, normal surprised you notice it so late. -- https://mail.python.org/mailman/listinfo/python-list
Re: Dictionary
Dennis Lee Bieber wrote: On Mon, 30 Dec 2013 18:38:20 +, Bischoop mar...@jakis.adres.em declaimed the following: I have a txt file with some words, and need simply program that will print me words containing provided letters. For example: Type the letters: (I type: g,m,o) open the dictionary.txt check words containing:g,m,o in dictionary.txt if there are words containing: [g, m, o ] print words with g,m,o Vague requirement... Do you need: 1 any word containing any single letter 2 any word containing all supplied letters (is there a limit on how many letters?) 3 any word containing the supplied letters in the entered order, but not necessarily adjacent to each other 4 any word containing the supplied letters in adjacent sequence 5 any word that begins with the supplied sequence of letters 1.yes 2. Any combination with supplied letters. It would be great if possible that I could set also the combination for example: show me all words with: l,x 3. the order doesn't matter 4. doesnt matter 5 doesnt matter. -- https://mail.python.org/mailman/listinfo/python-list
Re: Dictionary
Walter Hurry wrote: On Mon, 30 Dec 2013 18:38:20 +, Bischoop wrote: I have a txt file with some words, and need simply program that will print me words containing provided letters. For example: Type the letters: (I type: g,m,o) open the dictionary.txt check words containing:g,m,o in dictionary.txt if there are words containing: [g, m, o ] print words with g,m,o Well, what have you tried so far, and what result did you get? The incredibly helpful people here will provide advice, guidance and pointers, but it won't help you at all if they just do your homework for you. Honestly Im newbie in Python, years ago (10 already) I wrote simply program something like a TEST: Capitals of Countries. You could learn the capitals of some countries, and then you could try to solve a test. I know it's seems so simply for you guys but I was quite pride of myself :-) Now because of free time I took my book which I used years ago about python and try to learn it again, and as motivation I try to write the program I described above just to give me a kick :-), however got no idea how to start it, I meand there is so many moduls (import this, import that), I know how to open, read file etc. Just stuck with that, got no clue what and how use this that what I need to seek the words from the files if I need a words with letters I want. -- https://mail.python.org/mailman/listinfo/python-list
Dictionary
I have a txt file with some words, and need simply program that will print me words containing provided letters. For example: Type the letters: (I type: g,m,o) open the dictionary.txt check words containing:g,m,o in dictionary.txt if there are words containing: [g, m, o ] print words with g,m,o -- https://mail.python.org/mailman/listinfo/python-list