Two Plus Two Publishing LLC
Two Plus Two Publishing LLC
 

Go Back   Two Plus Two Poker Forums > >

Notices

Programming Discussions about computer programming

Reply
 
Thread Tools Display Modes
Old 01-24-2015, 09:21 AM   #226
ChrisV
Carpal \'Tunnel
 
ChrisV's Avatar
 
Join Date: Jul 2004
Location: Adelaide, Australia
Posts: 40,134
Re: Programming homework and newbie help thread

I just wrote my first Python program. How exciting.

So let's imagine we can convert the letters into the numbers 0 to 25 (zero-basing, because that's how we roll). Reversing the original shift will involve subtracting the shift from those numbers. But if we get a result outside of that range, we want to convert it back into that range. The usual tool for doing this is modulus, which is the % symbol in Python. And indeed if we look at this, (-1 % 26) is 25, meaning that subtracting 1 from 0 will roll us back around to 25. Adding 1 to 25 yields 26 and (26 % 26) is 0, so that all seems in order as well. So far, assuming we had the numbers 0 to 25 in the variable letterCode, it would look like this:

Quote:
(letterCode - shiftValue) % 26
So how do we convert letters to numbers and back again? All letters have sequential ASCII codes, we could use that. Python provides the ord() and chr() functions for converting back and forth. ord('A') turns out to be 65, so if I subtract 65 from the ord() value of each letter I'll get numbers between 0 and 25. Then after I do the mathsy stuff above, I can add 65 to it again and convert back to letters.

Quote:
chr(((ord(char) - 65 - shiftValue) % 26) + 65)
The full program:

Code:
cipherText = "FRQJUDWXODWLRKVBRXKDYHGHFOBSWHGWKHPHVVDJH"
shiftValue = input("Please enter an integer shift value from 1 to 26: ")

result = ""
for char in cipherText:
    result = result + chr(((ord(char) - 65 - shiftValue) % 26) + 65)  
print result
When run and given "3" this returns the following:

Quote:
CONGRATULATIOHSYOUHAVEDECLYPTEDTHEMESSAGE
Someone screwed up the cyphertext.

Note, the above only works for capital letters. You can run whatever the Python equivalent of ToUpper is on the cyphertext to get around this.
ChrisV is offline   Reply With Quote
Old 01-24-2015, 09:25 AM   #227
ChrisV
Carpal \'Tunnel
 
ChrisV's Avatar
 
Join Date: Jul 2004
Location: Adelaide, Australia
Posts: 40,134
Re: Programming homework and newbie help thread

As far as checking user input goes, my understanding is that the "Pythonic" way of doing things is to "seek forgiveness, not ask permission", which is to say that you treat shiftValue as an int until something goes wrong, at which point you handle the error. This seems like an insane way of doing things to someone like me raised on strongly typed languages, but it seems like that's the deal.
ChrisV is offline   Reply With Quote
Old 01-24-2015, 11:57 AM   #228
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

Quote:
Originally Posted by ChrisV View Post
As far as checking user input goes, my understanding is that the "Pythonic" way of doing things is to "seek forgiveness, not ask permission", which is to say that you treat shiftValue as an int until something goes wrong, at which point you handle the error. This seems like an insane way of doing things to someone like me raised on strongly typed languages, but it seems like that's the deal.
Python utilizes duck typing.
adios is offline   Reply With Quote
Old 01-24-2015, 05:57 PM   #229
daveT
S.A.G.E. Master
 
daveT's Avatar
 
Join Date: Jun 2005
Location: La La Land
Posts: 23,135
Re: Programming homework and newbie help thread

Quote:
Originally Posted by ChrisV View Post
As far as checking user input goes, my understanding is that the "Pythonic" way of doing things is to "seek forgiveness, not ask permission", which is to say that you treat shiftValue as an int until something goes wrong, at which point you handle the error. This seems like an insane way of doing things to someone like me raised on strongly typed languages, but it seems like that's the deal.
Code:
shiftValue = int(input("Please enter an integer shift value from 1 to 26: "))
This will throw an error if the input is not an integer. This does not convert floats to ints either.

Quote:
Originally Posted by ChrisV View Post
result = result + chr(((ord(char) - 65 - shiftValue) % 26) + 65)
[/code]
I don't like this at all. This is not platform, seed, or language (English, French) agnostic.

And this is in Python3:

Code:
import string
s = string.ascii_uppercase ## assuming all uppercase?

cipherText = "FRQJUDWXODWLRKVBRXKDYHGHFOBSWHGWKHPHVVDJH"

shiftValue = int(input("Please enter an integer shift value from 1 to 26: "))

result = ""
for char in cipherText:
    result += s[s.index(char) - (len(s) - shiftValue)]
print(result)
Don't get me wrong, there is a time for bit-shifting, but I think it is little overboard for this kind of problem, as you create something confusing, hard to reason about, and very difficult to extend and modify.

I'll let the OP figure out how to check for value ranges.

(to get the same result as ChrisV, you need to enter 23).
daveT is offline   Reply With Quote
Old 01-24-2015, 06:50 PM   #230
ChrisV
Carpal \'Tunnel
 
ChrisV's Avatar
 
Join Date: Jul 2004
Location: Adelaide, Australia
Posts: 40,134
Re: Programming homework and newbie help thread

Quote:
Originally Posted by adios View Post
Python utilizes duck typing.
The bit that skeeves me out isn't duck typing, it's the embracing of not validating stuff as a stylistic end in itself. The advantage of duck typing is flexibility and rapid development, not that it's just somehow better.

To use a kind of bad analogy, if you leave a parachute out of a plane because there's an emergency and you don't have time to get one, or whatever, then that's one thing. But if there's one sitting there and you have space for it and you're like "oh no, I don't use parachutes, that's not Pythonic" that's something else.

Dave's solution looks fine. If there's a problem with input I want to know about it straight away, not potentially hundreds of lines down the track where I am going to need to debug to figure out the problem. It seems like asking for trouble.
ChrisV is offline   Reply With Quote
Old 01-25-2015, 05:20 AM   #231
Craggoo
culled
 
Craggoo's Avatar
 
Join Date: Sep 2006
Location: R.I.P. ItzPenzoo 12-09-11
Posts: 12,533
Re: Programming homework and newbie help thread

Quote:
Originally Posted by ChrisV View Post
The bit that skeeves me out isn't duck typing, it's the embracing of not validating stuff as a stylistic end in itself. The advantage of duck typing is flexibility and rapid development, not that it's just somehow better.

To use a kind of bad analogy, if you leave a parachute out of a plane because there's an emergency and you don't have time to get one, or whatever, then that's one thing. But if there's one sitting there and you have space for it and you're like "oh no, I don't use parachutes, that's not Pythonic" that's something else.

Dave's solution looks fine. If there's a problem with input I want to know about it straight away, not potentially hundreds of lines down the track where I am going to need to debug to figure out the problem. It seems like asking for trouble.
To sum it up, it's very "unpython-like" to validate that the parameters/inputs/whatever they're called in python are what you expect them to be?
Craggoo is offline   Reply With Quote
Old 01-25-2015, 08:27 AM   #232
ChrisV
Carpal \'Tunnel
 
ChrisV's Avatar
 
Join Date: Jul 2004
Location: Adelaide, Australia
Posts: 40,134
Re: Programming homework and newbie help thread

Quote:
Originally Posted by Craggoo View Post
To sum it up, it's very "unpython-like" to validate that the parameters/inputs/whatever they're called in python are what you expect them to be?
My understanding is that it's un-Pythonic to validate TYPE. Imagine I wrap that caesar decryption code up in a function that rather than prompting the user to enter a shiftValue, accepts it as a parameter from client code. The Python way is that it is rude for me to demand that it's actually an int. "Duck typing" means that I should accept anything that has the behaviours I want. If I get passed some thing that isn't an int, but behaves like an int for my purposes, I should be OK with that. This allows a greater variety of code to reuse my function.

So far so good. I don't really like this sort of vagueness for large systems, but it has its place. Where I stop being OK with this is when I actually am prompting the user for input, and therefore I know that either they inputted an int or some string that can't be converted to an int. If it can't, then that's a showstopper - my program won't run. I know I don't have some exotic "acts like an int" class on my hands, so it's OK for me to check if it's an int straightaway.

Under normal "duck typing" circumstances, the earliest possible time for me to check if I've been passed an unsuitable parameter is simply the first time it stops behaving like an int. I'm OK with that, what I'm not OK with is turning that into a style guide and not immediately checking if I have an int IF I know there's no chance that "duck typing" applies in a given situation.

For checking whether my "int" (or something that quacks like an int) is within the range 0-25, I don't think it's considered "unPythonic" to do that. (It's also not necessary, if we're using the modulus method).
ChrisV is offline   Reply With Quote
Old 01-25-2015, 10:08 AM   #233
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

Quote:
Originally Posted by ChrisV View Post
.....

So far so good. I don't really like this sort of vagueness for large systems, but it has its place. Where I stop being OK with this is when I actually am prompting the user for input, and therefore I know that either they inputted an int or some string that can't be converted to an int. If it can't, then that's a showstopper - my program won't run. I know I don't have some exotic "acts like an int" class on my hands, so it's OK for me to check if it's an int straightaway.

Under normal "duck typing" circumstances, the earliest possible time for me to check if I've been passed an unsuitable parameter is simply the first time it stops behaving like an int. I'm OK with that, what I'm not OK with is turning that into a style guide and not immediately checking if I have an int IF I know there's no chance that "duck typing" applies in a given situation.

For checking whether my "int" (or something that quacks like an int) is within the range 0-25, I don't think it's considered "unPythonic" to do that. (It's also not necessary, if we're using the modulus method).
Seems like you could use an exception handler to detect a bogus operator input and re-prompt.
adios is offline   Reply With Quote
Old 01-25-2015, 10:55 AM   #234
Anais
Carpal \'Tunnel
 
Anais's Avatar
 
Join Date: Mar 2006
Posts: 6,666
Re: Programming homework and newbie help thread

I enjoy all the discussion on what makes something un-Pythonagonal
Anais is offline   Reply With Quote
Old 01-25-2015, 11:20 AM   #235
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

I was thinking if I was tasked with this assignment I would look a library call or iif one isn't available just find one and see if I needed to modify it.

Here's one solution I found One Python Caesar Cypher Solution

Code:
 
import sys 

def encrypt(k):
	plaintext = raw_input('Enter plain text message: ')
	cipher = ''
	
	for each in plaintext:
		c = (ord(each)+k) % 126
		
		if c < 32: 
			c+=31
			
		cipher += chr(c)
		
	print 'Your encrypted message is: ' + cipher

def decrypt(k):
	cipher = raw_input('Enter encrypted message: ')
	plaintext = ''
	
	for each in cipher:
		p = (ord(each)-k) % 126
	
		if p < 32:
			p+=95
						
		plaintext += chr(p)
		
	print 'Your plain text message is: ' + plaintext

def main(argv):
	if (len(sys.argv) != 3):
		sys.exit('Usage: ceaser.py <k> <mode>')
		
	if sys.argv[2] == 'e':
		encrypt(int(sys.argv[1]))
	elif sys.argv[2] == 'd':
		decrypt(int(sys.argv[1]))
	else:
		sys.exit('Error in mode type')


if __name__ == "__main__":
	main(sys.argv[1:])
No exception handling, looks to be a clean solution that you can run from the command line and that can be imported by other Python code. I then would try a lot of test data to break it. Not sure but Python unit testing would be desirable I would think.
adios is offline   Reply With Quote
Old 01-25-2015, 03:16 PM   #236
Allen C
journeyman
 
Join Date: Oct 2004
Posts: 379
Re: Programming homework and newbie help thread

Quote:
Originally Posted by ChrisV View Post
My understanding is that it's un-Pythonic to validate TYPE. Imagine I wrap that caesar decryption code up in a function that rather than prompting the user to enter a shiftValue, accepts it as a parameter from client code. The Python way is that it is rude for me to demand that it's actually an int. "Duck typing" means that I should accept anything that has the behaviours I want. If I get passed some thing that isn't an int, but behaves like an int for my purposes, I should be OK with that. This allows a greater variety of code to reuse my function.

So far so good. I don't really like this sort of vagueness for large systems, but it has its place. Where I stop being OK with this is when I actually am prompting the user for input, and therefore I know that either they inputted an int or some string that can't be converted to an int. If it can't, then that's a showstopper - my program won't run. I know I don't have some exotic "acts like an int" class on my hands, so it's OK for me to check if it's an int straightaway.

Under normal "duck typing" circumstances, the earliest possible time for me to check if I've been passed an unsuitable parameter is simply the first time it stops behaving like an int. I'm OK with that, what I'm not OK with is turning that into a style guide and not immediately checking if I have an int IF I know there's no chance that "duck typing" applies in a given situation.

For checking whether my "int" (or something that quacks like an int) is within the
I'm not ok with it either but I disagree that it's not pythonic to check that. It's just crazy in any language to let the program go on with random user input that might not work.

My evidence is that the most pythonic way would be to use a library such as argparse. And it coerces all user options into your specified type and handles it for you (typically ending the program with an error message) if it can't. I would expect you should do the same if you roll your own.
Allen C is offline   Reply With Quote
Old 01-25-2015, 05:23 PM   #237
daveT
S.A.G.E. Master
 
daveT's Avatar
 
Join Date: Jun 2005
Location: La La Land
Posts: 23,135
Re: Programming homework and newbie help thread

Adios, correct me if I am wrong, but doesn't ord, modulo 126, and p += x, assume a certain character encoding? I'm lost on why we'd need to convert to bits for this problem. I can see it if you are doing xor, but using xor still assumes the transmitter and receiver are using the same platforms, but would be (I think) platform agnostic if you encode / decode on the same machine.
daveT is offline   Reply With Quote
Old 01-26-2015, 09:46 AM   #238
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

Quote:
Originally Posted by daveT View Post
Adios, correct me if I am wrong, but doesn't ord, modulo 126, and p += x, assume a certain character encoding? I'm lost on why we'd need to convert to bits for this problem. I can see it if you are doing xor, but using xor still assumes the transmitter and receiver are using the same platforms, but would be (I think) platform agnostic if you encode / decode on the same machine.
Assuming a certain character encoding sure. On exclusive (xor) you not sure what platform considerations your referring to. You pose interesting questions. Could you elaborate some on the failure modes for this implementation. I am not trying to defend that code in any way. I just find this to be interesting and informative. So I would enjoy seeing the failure modes that envision.
adios is offline   Reply With Quote
Old 01-26-2015, 12:46 PM   #239
well named
poorly undertitled
 
well named's Avatar
 
Join Date: Jun 2007
Location: esse est coesse
Posts: 75,418
Re: Programming homework and newbie help thread

The logic works with ASCII (latin-1) or the ASCII region of UTF-8 which is identical. It won't work properly with anything else. There is probably a generalizable solution for a simple rotating cypher if it doesn't make the assumptions about ASCII, i.e doesn't modulo 126 or assume a lowest possible printable character at 32. The assumptions are there because the output of a caesar cypher is still intended to be readable text, and otherwise it won't be in ASCII, since you end up with control characters. But a rotation mod 255 on each byte would not have character encoding issues, just the cyphertext wouldn't necessarily be readable.

I'm not 100% sure about endianness issues but you can use something like htonl() (there must be a python implementation in the network stuff somewhere)
well named is offline   Reply With Quote
Old 01-26-2015, 04:10 PM   #240
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

Quote:
Originally Posted by well named View Post
The logic works with ASCII (latin-1) or the ASCII region of UTF-8 which is identical. It won't work properly with anything else. There is probably a generalizable solution for a simple rotating cypher if it doesn't make the assumptions about ASCII, i.e doesn't modulo 126 or assume a lowest possible printable character at 32. The assumptions are there because the output of a caesar cypher is still intended to be readable text, and otherwise it won't be in ASCII, since you end up with control characters. But a rotation mod 255 on each byte would not have character encoding issues, just the cyphertext wouldn't necessarily be readable.

I'm not 100% sure about endianness issues but you can use something like htonl() (there must be a python implementation in the network stuff somewhere)
Well does STDIN in say Saudi Arabia not stream UTF-8? I have to confess I don't know. Put another way when is something else besides UTF-8 streamed on STDIN? I don't see why endianness is a consideration here either.
adios is offline   Reply With Quote
Old 01-26-2015, 11:16 PM   #241
well named
poorly undertitled
 
well named's Avatar
 
Join Date: Jun 2007
Location: esse est coesse
Posts: 75,418
Re: Programming homework and newbie help thread

I was extrapolating to uses outside of the command line. No idea about stdin.
well named is offline   Reply With Quote
Old 01-27-2015, 12:04 AM   #242
daveT
S.A.G.E. Master
 
daveT's Avatar
 
Join Date: Jun 2005
Location: La La Land
Posts: 23,135
Re: Programming homework and newbie help thread

To be fair, my biggest f-u computer moments surround character encoding issues and I do get that, as long as you encode bit-right N then you can decode bit-left N no matter the encoding, but I still worry about what would happen if we used another encoding. I suppose my reaction is visceral more than logical.

The xor stuff was more thinking about why you'd convert.

I think that using ord() is over-kill for a simple shift-array-by-N problem. At the end of the day, you are moving characters which happen to take a position in an array, and I don't see the reasoning for going any level closer to the metal for this, and let's be honest, what use is conversion to someone who is just starting out? I think it is better to learn how to manipulate arrays.

I feel sorry for the crowd who just wants newbie help. Endianess just got tossed down, oh my...

I know there's better posters here for this kind of chat.
daveT is offline   Reply With Quote
Old 01-27-2015, 01:22 AM   #243
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

@Dave - Good catch on the character encoding. I found this link on the character encoding as it applies to STDIN for Python 3.

STDIN Encoding as it Pertains to Python 3
Quote:
Python 3 does not expect ASCII from sys.stdin. It'll open stdin in text mode and make an educated guess as to what encoding is used. That guess may come down to ASCII, but that is not a given. See the sys.stdin documentation on how the codec is selected.

Like other file objects opened in text mode, the sys.stdin object derives from the io.TextIOBase base class; it has a .buffer attribute pointing to the underlying buffered IO instance (which in turn has a .raw attribute).

Wrap the sys.stdin.buffer attribute in a new io.TextIOWrapper() instance to specify a different encoding:

import io
import sys

input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
Alternatively, set the PYTHONIOENCODING environment variable to the desired codec when running python.
So indeed you are correct. Interesting. I didn't look into Python 2.7 very much but there are similar concerns with encoding.
adios is offline   Reply With Quote
Old 01-27-2015, 04:18 PM   #244
cookies4u
grinder
 
Join Date: Aug 2014
Posts: 467
Re: Programming homework and newbie help thread

i'm taking a Visual Basic class, and for our first assignment i can't figure out how to adjust the size/location values of a picture box control under the properties list. everytime i try entering different values, they automatically switch back to the default when i click the cursor on something else.

i swear i tried googling this and skimming some youtube tutorials but i get nothing. btw, if it matters this is for Visual Studio 2012 since that's what our book is based on.
cookies4u is offline   Reply With Quote
Old 01-27-2015, 05:40 PM   #245
cookies4u
grinder
 
Join Date: Aug 2014
Posts: 467
Re: Programming homework and newbie help thread

Quote:
Originally Posted by cookies4u View Post
i'm taking a Visual Basic class, and for our first assignment i can't figure out how to adjust the size/location values of a picture box control under the properties list. everytime i try entering different values, they automatically switch back to the default when i click the cursor on something else.

i swear i tried googling this and skimming some youtube tutorials but i get nothing. btw, if it matters this is for Visual Studio 2012 since that's what our book is based on.
nevermind, got it

stupid editing time limit!
cookies4u is offline   Reply With Quote
Old 01-27-2015, 07:58 PM   #246
Benholio
Carpal \'Tunnel
 
Benholio's Avatar
 
Join Date: Jun 2004
Location: Atlanta, GA
Posts: 8,292
Re: Programming homework and newbie help thread

Internet question pet peeve! Please do tell us what the solution to your problem was.
Benholio is offline   Reply With Quote
Old 01-27-2015, 08:50 PM   #247
cookies4u
grinder
 
Join Date: Aug 2014
Posts: 467
Re: Programming homework and newbie help thread

hah, sorry. well, i was trying to import a picture into a picture box that was pretty much covering the entire form. in the "picture box tasks" menu, you can adjust the size mode to "stretch image" to make it fit the picture box. but apparently (as far as i can tell), you have to size the picture box the way you want it before importing the image, otherwise you can't resize it (the picture box) after importing the image.
cookies4u is offline   Reply With Quote
Old 01-27-2015, 10:46 PM   #248
Benholio
Carpal \'Tunnel
 
Benholio's Avatar
 
Join Date: Jun 2004
Location: Atlanta, GA
Posts: 8,292
Re: Programming homework and newbie help thread

Ah cool. Thanks!
Benholio is offline   Reply With Quote
Old 01-28-2015, 01:49 AM   #249
cookies4u
grinder
 
Join Date: Aug 2014
Posts: 467
Re: Programming homework and newbie help thread

tried loading some sln files that go with this course in Studio but can't get them to work, i get this error:

Quote:
C:\Users\David\Downloads\Two Form Project\Two Form Project.vbproj : error : The project file could not be loaded. Could not find a part of the path 'C:\Users\David\Downloads\Two Form Project\Two Form Project.vbproj'. C:\Users\David\Downloads\Two Form Project\Two Form Project.vbproj
i don't expect anyone to, but just in case you feel like checking, the files come from the zip link on this page: http://www.cengagebrain.com/cgi-wads...5077925&token=
cookies4u is offline   Reply With Quote
Old 01-28-2015, 11:45 AM   #250
adios
Carpal \'Tunnel
 
Join Date: Sep 2002
Location: Russian Troll
Posts: 21,392
Re: Programming homework and newbie help thread

Quote:
Originally Posted by cookies4u View Post
tried loading some sln files that go with this course in Studio but can't get them to work, i get this error:
....
Looks like you need to mimic the folder structure of the project solution you are trying to download. You can probably change an environment variable that specifies the root folder. Not sure though. Again VS user interface can be maddening to work with.
adios is offline   Reply With Quote

Reply
      

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off


Forum Jump


All times are GMT -4. The time now is 06:56 AM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
Copyright 2008-2017, Two Plus Two Interactive
 
 
Poker Players - Streaming Live Online