Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
the
Jul 18, 2004

by Cowcaster
Let's say that a = 5 and b = 5 and c = 5

Is this a safe condition to check:

Python code:
if a == b == c:
      then print 'yes'
Or do I need to write something like this:

Python code:
if a == b and b == c:
      then print 'yes'

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

the posted:

Let's say that a = 5 and b = 5 and c = 5

Is this a safe condition to check:

Python code:
if a == b == c:
      then print 'yes'

Yes.

the
Jul 18, 2004

by Cowcaster
Follow up question: Let's say I have three lists, A contains 100 entries, B contains 1000 entries, and C contains 1000000 entries.

I want to compare them and find the matching entries.

My first thought was just to do a nested loop to check:

Python code:
for i in A:
      for j in B:
           for k in C:
                 if i[0] == j[0] == k[0]:
                       print 'match'
However I'm wondering, is it faster if I do two separate instead, like this?

Python code:
for i in A:
      for k in C:
            if i[0] == k[0]
                  D.append(i[0])

for l in D:
      for j in B:
           if l[0] == j[0]
                 print 'match'

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

the posted:

Follow up question: Let's say I have three lists, A contains 100 entries, B contains 1000 entries, and C contains 1000000 entries.

I want to compare them and find the matching entries.


code:
common = set(A) & set(B) & set(C)
common will also be a set, so if that matters just call list() on it.

the
Jul 18, 2004

by Cowcaster

good jovi posted:

code:
common = set(A) & set(B) & set(C)
common will also be a set, so if that matters just call list() on it.

Thanks, but the problem is that the lists won't have exact entries. I'm linking them by a unique ID that's included in all the lists, but they're lists of different things.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

the posted:

Thanks, but the problem is that the lists won't have exact entries. I'm linking them by a unique ID that's included in all the lists, but they're lists of different things.

If items in the lists have a unique ID, why aren't you storing them as a dictionary where the ID is the key and the other items in the list are the value? That would make it really easy to do set operations with just the IDs.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

the posted:

Thanks, but the problem is that the lists won't have exact entries. I'm linking them by a unique ID that's included in all the lists, but they're lists of different things.

That sounds really awkward, and you should think about how to store these items more efficiently.

Think about what "equality" really means for these objects. Consider encapsulating them in something (a class) that defines __eq__ and __hash__ in a logical way such that objects considered equal in your problem domain are actually treated as such. Don't let Python's default comparison behavior limit you, that's just a default.

the
Jul 18, 2004

by Cowcaster

BeefofAges posted:

If items in the lists have a unique ID, why aren't you storing them as a dictionary where the ID is the key and the other items in the list are the value? That would make it really easy to do set operations with just the IDs.

I'm using Beatbox to query a Salesforce database for different entries like Contacts and Accounts.

So a Contact query would look something like this:

['Contact', '00001123443AXQ', 'John Smith']

And an Account query might look something like this:

['Account', '00001123443AXQ', 'City of Austin,' 'TX', '20441']

And I'm running a comparison check for that account ID and storing the information I need when I find it.

I'll admit I haven't worked with dictionaries enough to know that it's possible to store everything like that in one.

QuarkJets
Sep 8, 2008

the posted:

I'm using Beatbox to query a Salesforce database for different entries like Contacts and Accounts.

So a Contact query would look something like this:

['Contact', '00001123443AXQ', 'John Smith']

And an Account query might look something like this:

['Account', '00001123443AXQ', 'City of Austin,' 'TX', '20441']

And I'm running a comparison check for that account ID and storing the information I need when I find it.

I'll admit I haven't worked with dictionaries enough to know that it's possible to store everything like that in one.

With a dictionary, you can have a list as a value. So the key for both dictionaries would be '00001123443AXQ' and the value in one dictionary would be ['Contact', 'John Smith'] and the other dictionary it would be ['Account', 'City of Austin', 'TX', '20441'].

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

QuarkJets posted:

With a dictionary, you can have a list as a value. So the key for both dictionaries would be '00001123443AXQ' and the value in one dictionary would be ['Contact', 'John Smith'] and the other dictionary it would be ['Account', 'City of Austin', 'TX', '20441'].

You could even have a dict as a value if it was useful to you.

{'00001123443AXQ': {'city': 'City of Austin', 'state': 'TX', 'zip': '20441'}}

If you were feeling crazy you could create a Contact and Account class and attach some behavior to them instead of using a dict.

QuarkJets
Sep 8, 2008

the posted:

I'm using Beatbox to query a Salesforce database for different entries like Contacts and Accounts.

So a Contact query would look something like this:

['Contact', '00001123443AXQ', 'John Smith']

And an Account query might look something like this:

['Account', '00001123443AXQ', 'City of Austin,' 'TX', '20441']

And I'm running a comparison check for that account ID and storing the information I need when I find it.

I'll admit I haven't worked with dictionaries enough to know that it's possible to store everything like that in one.

If query is a list of lists, and the account number is always index 1 of each sublist:

Python code:
contact_dict = {query[1] : query[0:1] + query[2:] for query in contact_query}
That would create a dictionary where the keys are account numbers and the values are the remainder of the list. The same line would work on the account query list of lists. Then you can easily compare account numbers

e: I would have suggested a class, but I wanted to elaborate on dictionaries for a little bit because dictionaries are cool. So what you should do is make dictionaries of class instances that hold your data instead of dictionaries of lists that hold your data

QuarkJets fucked around with this message at 18:48 on Jul 2, 2014

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

the posted:

I'm using Beatbox to query a Salesforce database for different entries like Contacts and Accounts.

So a Contact query would look something like this:

['Contact', '00001123443AXQ', 'John Smith']

And an Account query might look something like this:

['Account', '00001123443AXQ', 'City of Austin,' 'TX', '20441']

And I'm running a comparison check for that account ID and storing the information I need when I find it.

I'll admit I haven't worked with dictionaries enough to know that it's possible to store everything like that in one.

I think what they are trying to suggest is that you work with dictionaries that look like this:

code:
contacts = {
    '00001123443AXQ': {'name': 'John Smith'},
    '00005786351ABC': {'name': 'Clark Kent'},
}
accounts = {
    '00001123443AXQ': {
        'location': 'City of Austin',
        'state': 'TX',
        'whatever this is': '20441'
    },
    '00008578547XYZ': {
        'location': 'New York',
        'state': 'New York',
        'whatever this is': '56789'
    },
}
or possibly, if it makes things easier,

code:
contacts = {
    '00001123443AXQ': {'id': '00001123443AXQ', 'name': 'John Smith'}
    '00005786351ABC': {'id': '00005786351ABC', 'name': 'Clark Kent'},
}
accounts = {
    '00001123443AXQ': {
        'id': '00001123443AXQ',
        'location': 'City of Austin',
        'state': 'TX',
        'whatever this is': '20441'
    },
    '00008578547XYZ': {
        'id': '00008578547XYZ',
        'location': 'New York',
        'state': 'New York',
        'whatever this is': '56789'
    },
}
as this means you can do things like (if accounts1 and accounts2 were two dictionaries like the ones above)

code:
accounts1_ids = set(accounts1.keys())
accounts2_ids = set(accounts2.keys())
if accounts1_ids == accounts2_ids:
    print("accounts1 and accounts2 contain the same accounts!")
else
    print("accounts1 and accounts2 do not contain the same accounts!")
The values in the dictionaries do not need to again be dictionaries, they could be objects of type Contact or Account (where Contact and Account are classes you defined).

the
Jul 18, 2004

by Cowcaster
Thanks, guys. Looks like this is working well. A good way to simplify the process and information handling. Much thanks!

Optimus Prime Ribs
Jul 25, 2007

Does anyone have any idea why Flask would be causing connection refusals (i.e. socket error 10061) on any given port using the basic "hello world" script on the website:
Python code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=42985)
But this basic test script I wrote works just fine:
Python code:
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
server.bind(("0.0.0.0",42985))
server.listen(5)

while True:
    client = server.accept()
    print "Client connected"
    client[0].send("hello world\r\n\r\n")
    client[0].close()
This is running on a fresh CentOS install (other than the OS and the poo poo it uses there's only Python, Perl, and vsftpd installed), on which I have iptables disabled for testing purposes. I only wrote the test script to prove that the port 42985 is externally visible (or any other port I put in there). I've never had Flask be installed and then have the example from the site not work, so I'm at an absolute loss as to how to fix it. There aren't any errors and everything looks like it's running as it should; Flask is just causing connection refusals.

I also installed Flask using pip install Flask if that matters. It installed everything Flask depends on, such as Werkzeug, no problem.

Pollyanna
Mar 5, 2005

Milk's on them.


I've been wondering about that, actually. I commonly find myself in a situation where I have data such as a bunch of subsets, complicated objects, and huge flat dictionaries. Is there a specific pattern to creating those kindsa data structures, or is it more or less what's easiest?

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

the posted:

Thanks, guys. Looks like this is working well. A good way to simplify the process and information handling. Much thanks!

I know you've found a solution you're happy with, but I briefly glanced at beatbox and it looks like it lets you directly send SQL queries, in which case it might be faster to do a join in your query and let the server do the heavy lifting instead of trying to merge your datasets locally.

the
Jul 18, 2004

by Cowcaster

BeefofAges posted:

I know you've found a solution you're happy with, but I briefly glanced at beatbox and it looks like it lets you directly send SQL queries, in which case it might be faster to do a join in your query and let the server do the heavy lifting instead of trying to merge your datasets locally.

...Go on...

(I don't know what you mean by join in your query)

Space Kablooey
May 6, 2009


the posted:

...Go on...

(I don't know what you mean by join in your query)

You are probably firing two or more of those:

One may be:

SELECT id_butt, whatever1 FROM butts

And the other may be:

SELECT id_fart, id_butt, whatever2 FROM farts


The result is that you have now two separated sets of data that are logically related. Modern databases are handy in that relational databases are all the rage for quite some time now. Instead of having two sets of separated but related data, you can have only one set of related data, saving you the hassle of JOINing them yourself. The database excels in that already. Something like this:

SELECT b.id_butt, b.whatever1, f.id_fart, f.whatever2 FROM butts b, farts f WHERE f.id_butt = b.id_butt;

My SQL is quite rusty, so that may not be quite right (sqlalchemy :allears:), so I'll just leave you a link to the CoC SQL megathread. Sorry for not being more helpful.

ohgodwhat
Aug 6, 2005

QuarkJets posted:

e: I would have suggested a class, but I wanted to elaborate on dictionaries for a little bit because dictionaries are cool. So what you should do is make dictionaries of class instances that hold your data instead of dictionaries of lists that hold your data

Or namedtuples for the values of the dictionary.

the
Jul 18, 2004

by Cowcaster

Got it, I'll look into that tomorrow, thanks!

Optimus Prime Ribs
Jul 25, 2007

Optimus Prime Ribs posted:

My Flask problem...

Been fighting with this for hours and talked with some goons on IRC whom couldn't figure it out either, so I'm quite prepared to say "gently caress Flask" and use something else (Flask is the only thing that won't work on my server).

What is a good alternative to Flask? Or would that question be better for the web design/development thread?

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

Optimus Prime Ribs posted:

Been fighting with this for hours and talked with some goons on IRC whom couldn't figure it out either, so I'm quite prepared to say "gently caress Flask" and use something else (Flask is the only thing that won't work on my server).

What is a good alternative to Flask? Or would that question be better for the web design/development thread?

I know nothing of your requirements, but you should just use Django.

Hed
Mar 31, 2004

Fun Shoe
If you need the light weight of flask, try bottle.

Optimus Prime Ribs
Jul 25, 2007

The March Hare posted:

I know nothing of your requirements, but you should just use Django.

Isn't Django intended for large scale web applications? Anything I'll be developing won't be super complex, and Django looks like a hell of a beast of a web framework that would probably be overkill. First thing that I'm doing to be making will just be a basic website to show my portfolio and contact information, and after that probably just a simple game that will mostly run off of HTML5/JavaScript.

Hed posted:

If you need the light weight of flask, try bottle.

I do like lightweight frameworks, and bottle looks pretty interesting. I've got it installed and working on my server, so I'll play around with it and see what I think.

Thanks. :)

e:

Flask is working now, and I didn't change anything. :iiam:

Optimus Prime Ribs fucked around with this message at 06:28 on Jul 3, 2014

QuarkJets
Sep 8, 2008

Is there an easy way to get OpenCV into a portable anaconda installation? I've tried to do this myself (in CentOS), but somehow I keep getting a cv2 module that's simply hosed. I try to do an image resize and it gives me an array full of 0s with a handful of non-zero pixels, and if I try to create a bilateral filter then it just instantly seg faults.

Dominoes
Sep 20, 2007

BigRedDot posted:

This is a really good question, but also fairly technical one, your best bet is the mailing list anaconda@continuum.io or the GH issue tracker https://github.com/ContinuumIO/anaconda-issues
Thanks - submitted issues to both. My main issue with this is that I switched to Anaconda to make package management easier, but the workarounds for PyQt5 nullify this advantage. While I got the workarounds done on Windows by installing binaries, I still haven't figured it out on Ubuntu - the PyQt5 package uses the system Python3, and I'm no good at building things from source.

QuarkJets
Sep 8, 2008

Dominoes posted:

Thanks - submitted issues to both. My main issue with this is that I switched to Anaconda to make package management easier, but the workarounds for PyQt5 nullify this advantage. While I got the workarounds done on Windows by installing binaries, I still haven't figured it out on Ubuntu - the PyQt5 package uses the system Python3, and I'm no good at building things from source.

You may want to try building from source a bit more; it's often extremely easy, just more time-consuming.

Literally Elvis
Oct 21, 2013

A friend was working on a rot13 script to learn Python, so I gave it a shot myself to compare. I wanted to get it down to a lower line count, so I moved the results of the if-statements onto the same line, is that acceptable?
code:
def rot13(phrase):
    result, words= "", list(phrase)
    for x in range(len(words)):
        char = ord(words[x])                      
        if char == 32: result += " "                                        #spaces 
        elif 109 < char <= 122 or 77 < char <= 90: result += chr(char - 13) #lowercase
        elif 90 < char <= 109 or 65 < char <= 77: result += chr(char + 13)  #uppercase 
        else: result += words[x]                                            #anything else
    return result  

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Literally Elvis posted:

A friend was working on a rot13 script to learn Python, so I gave it a shot myself to compare. I wanted to get it down to a lower line count, so I moved the results of the if-statements onto the same line, is that acceptable?
code:
def rot13(phrase):
    result, words= "", list(phrase)
    for x in range(len(words)):
        char = ord(words[x])                      
        if char == 32: result += " "                                        #spaces 
        elif 109 < char <= 122 or 77 < char <= 90: result += chr(char - 13) #lowercase
        elif 90 < char <= 109 or 65 < char <= 77: result += chr(char + 13)  #uppercase 
        else: result += words[x]                                            #anything else
    return result  

No, not really. Line count is just a number. It's less readable to me, separating the condition from the action is difficult on a line that long.

Also, you don't need to iterate over range(len(words)). You can just iterate over words itself.

qntm
Jun 17, 2009

Literally Elvis posted:

A friend was working on a rot13 script to learn Python, so I gave it a shot myself to compare. I wanted to get it down to a lower line count, so I moved the results of the if-statements onto the same line, is that acceptable?
code:
def rot13(phrase):
    result, words= "", list(phrase)
    for x in range(len(words)):
        char = ord(words[x])                      
        if char == 32: result += " "                                        #spaces 
        elif 109 < char <= 122 or 77 < char <= 90: result += chr(char - 13) #lowercase
        elif 90 < char <= 109 or 65 < char <= 77: result += chr(char + 13)  #uppercase 
        else: result += words[x]                                            #anything else
    return result  

That approach is not terribly readable (you could consider lining the "result" statements up vertically), but the real bad news is that technically this doesn't reduce the "line count". You just have two SLOCs (an "if" and a "result +=") on a single line in your text editor. I believe that in theory you could actually put the whole program (as is) on one line.

No Safe Word
Feb 26, 2005

Also if you really just want to code golf it, you can just cheat and leverage the batteries included

code:
>>> phrase = "The quick brown fox jumps over the lazy dog"
>>> import codecs
>>> codecs.getencoder('rot-13')(phrase)[0]
'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'
:haw:

Literally Elvis
Oct 21, 2013

good jovi posted:

No, not really. Line count is just a number. It's less readable to me, separating the condition from the action is difficult on a line that long.

Also, you don't need to iterate over range(len(words)). You can just iterate over words itself.

qntm posted:

That approach is not terribly readable (you could consider lining the "result" statements up vertically), but the real bad news is that technically this doesn't reduce the "line count". You just have two SLOCs (an "if" and a "result +=") on a single line in your text editor. I believe that in theory you could actually put the whole program (as is) on one line.

thoroughly noted and script edited accordingly.
code:
def rot13(phrase):
    result, words= "", list(phrase)
    for char in words:
        uni = ord(char)                      
        if uni == 32: result += " "               #spaces 
        elif 109 < uni <= 122 or 77 < uni <= 90:  #lowercase
            result += chr(uni - 13) 
        elif 90 < uni <= 109 or 65 < uni <= 77:   #uppercase
            result += chr(uni + 13)   
        else:                                     #anything else
            result += char                    
    return result  

No Safe Word posted:

Also if you really just want to code golf it, you can just cheat and leverage the batteries included

code:
>>> phrase = "The quick brown fox jumps over the lazy dog"
>>> import codecs
>>> codecs.getencoder('rot-13')(phrase)[0]
'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'
:haw:

I know that part of what makes Python great is the thoroughness of it's included functions, but I like implementing simple things like this because I think it's good practice. v:shobon:v

EDIT: are things like single line variable declarations okay?

Literally Elvis fucked around with this message at 21:10 on Jul 3, 2014

EAT THE EGGS RICOLA
May 29, 2008

Literally Elvis posted:


EDIT: are things like single line variable declarations okay?

Anything that decreases readability is not okay.

namaste friends
Sep 18, 2004

by Smythe

EAT THE EGGS RICOLA posted:

Anything that decreases readability is not okay.

Dear God, I am maintaining code written by a mad scientist that is written like this. Please don't obfuscate your code.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Literally Elvis posted:

code:
    result, words= "", list(phrase)
    for char in words:

You don't have to explicitly cast phrase to a list. You can iterate over a string, and it will just return each character.

code:
>>> phrase = "The quick brown fox"
>>> for character in phrase:
...      print character
...
T
h
e

q
u
i
c
k

b
r
o
w
n

f
o
x
>>>
And if you did convert it to a list, words would not be an appropriate name for the result.

code:
>>> phrase = "The quick brown fox"
>>> list(phrase)
['T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ' ', 'b', 'r', 'o', 'w', 'n', ' ', 'f', 'o', 'x']
>>> phrase.split(' ')
['The', 'quick', 'brown', 'fox']

EAT THE EGGS RICOLA
May 29, 2008

Someone make a version of code golf where you win by writing the most easily readable code pls

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord

No Safe Word posted:

Also if you really just want to code golf it, you can just cheat and leverage the batteries included

code:
>>> phrase = "The quick brown fox jumps over the lazy dog"
>>> import codecs
>>> codecs.getencoder('rot-13')(phrase)[0]
'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'
:haw:

I had no idea of this, I thought codecs had only serious stuff!

Here's a dumb version just to show off some stdlib:

Python code:
import string
import collections
import itertools

lowercase_deque = collections.deque(string.ascii_lowercase)
uppercase_deque = collections.deque(string.ascii_uppercase)
lowercase_deque.rotate(13)
uppercase_deque.rotate(13)

ROT13_TABLE = str.maketrans(string.ascii_letters,
                            ''.join(itertools.chain(lowercase_deque,
                                                    uppercase_deque)))

def rot13(s):
    return s.translate(ROT13_TABLE)

theguyoncouch
May 23, 2014
Said friend here. This is how mine ended up. first time with python but i tried to cover all my bases. probably not the best

code:
def cif(words): 							#shifting cipher
	result, new_char = "", "" 					#declaring what I can
	for char in words:						#looping per each character in phrase
		cap = char.isupper()					#Checks if letter is captilized. Saves this in cap.
		ltr = ord(char.lower()) + shift 			#converts to lower-case as well as shifting the ascii number
		if ltr > 122: ltr -= 26  				#if it goes above the range of lower-case letters it loops it back
		elif ltr < 97: ltr += 26 				#if it goes above the range of lower-case letters it loops it back
		if char.isalpha(): 					#checks to see if char is an alphabetical letter
			if cap == True: ltr -= 32			#reverts ltr back to it's capitalized state
			new_char = chr(ltr)      			#assigns ltr in to char after reverting to character
		else: new_char = char					#if it is not an alphabetical letter it prints as is
		result += new_char					#joining characters back into string
	return result							#completes and returns string

EAT THE EGGS RICOLA
May 29, 2008

theguyoncouch posted:

Said friend here. This is how mine ended up. first time with python but i tried to cover all my bases. probably not the best

Use actual words, don't put compound statements on one line, get rid of most of the comments (your code should self-document for something this simple), put the declarations on separate lines, and join your string like this:

code:
rotated_phrase = []
for letter in phrase:
    (...rotate letter...)
    rotated_phrase.append(rotated_letter)
return ''.join(rotated_phrase)
It's way more efficient than computing, storing, and discarding a new string every time you add to it.

edit:

HardDisk posted:

Don't use tabs. Use spaces, preferably 4.

aag, that too

EAT THE EGGS RICOLA fucked around with this message at 23:27 on Jul 3, 2014

Adbot
ADBOT LOVES YOU

Space Kablooey
May 6, 2009


theguyoncouch posted:

Said friend here. This is how mine ended up. first time with python but i tried to cover all my bases. probably not the best

code:
def cif(words): 							#shifting cipher
	result, new_char = "", "" 					#declaring what I can
	for char in words:						#looping per each character in phrase
		cap = char.isupper()					#Checks if letter is captilized. Saves this in cap.
		ltr = ord(char.lower()) + shift 			#converts to lower-case as well as shifting the ascii number
		if ltr > 122: ltr -= 26  				#if it goes above the range of lower-case letters it loops it back
		elif ltr < 97: ltr += 26 				#if it goes above the range of lower-case letters it loops it back
		if char.isalpha(): 					#checks to see if char is an alphabetical letter
			if cap == True: ltr -= 32			#reverts ltr back to it's capitalized state
			new_char = chr(ltr)      			#assigns ltr in to char after reverting to character
		else: new_char = char					#if it is not an alphabetical letter it prints as is
		result += new_char					#joining characters back into string
	return result							#completes and returns string

Don't use tabs. Use spaces, preferably 4.

  • Locked thread