Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

01-24-2015 , 09:21 AM
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.
Programming homework and newbie help thread Quote
01-24-2015 , 09:25 AM
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.
Programming homework and newbie help thread Quote
01-24-2015 , 11:57 AM
Quote:
Originally Posted by ChrisV
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.
Programming homework and newbie help thread Quote
01-24-2015 , 05:57 PM
Quote:
Originally Posted by ChrisV
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
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).
Programming homework and newbie help thread Quote
01-24-2015 , 06:50 PM
Quote:
Originally Posted by adios
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.
Programming homework and newbie help thread Quote
01-25-2015 , 05:20 AM
Quote:
Originally Posted by ChrisV
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?
Programming homework and newbie help thread Quote
01-25-2015 , 08:27 AM
Quote:
Originally Posted by Craggoo
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).
Programming homework and newbie help thread Quote
01-25-2015 , 10:08 AM
Quote:
Originally Posted by ChrisV
.....

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.
Programming homework and newbie help thread Quote
01-25-2015 , 10:55 AM
I enjoy all the discussion on what makes something un-Pythonagonal
Programming homework and newbie help thread Quote
01-25-2015 , 11:20 AM
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.
Programming homework and newbie help thread Quote
01-25-2015 , 03:16 PM
Quote:
Originally Posted by ChrisV
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.
Programming homework and newbie help thread Quote
01-25-2015 , 05:23 PM
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.
Programming homework and newbie help thread Quote
01-26-2015 , 09:46 AM
Quote:
Originally Posted by daveT
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.
Programming homework and newbie help thread Quote
01-26-2015 , 12:46 PM
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)
Programming homework and newbie help thread Quote
01-26-2015 , 04:10 PM
Quote:
Originally Posted by well named
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.
Programming homework and newbie help thread Quote
01-26-2015 , 11:16 PM
I was extrapolating to uses outside of the command line. No idea about stdin.
Programming homework and newbie help thread Quote
01-27-2015 , 12:04 AM
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.
Programming homework and newbie help thread Quote
01-27-2015 , 01:22 AM
@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.
Programming homework and newbie help thread Quote
01-27-2015 , 04:18 PM
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.
Programming homework and newbie help thread Quote
01-27-2015 , 05:40 PM
Quote:
Originally Posted by cookies4u
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!
Programming homework and newbie help thread Quote
01-27-2015 , 07:58 PM
Internet question pet peeve! Please do tell us what the solution to your problem was.
Programming homework and newbie help thread Quote
01-27-2015 , 08:50 PM
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.
Programming homework and newbie help thread Quote
01-27-2015 , 10:46 PM
Ah cool. Thanks!
Programming homework and newbie help thread Quote
01-28-2015 , 01:49 AM
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=
Programming homework and newbie help thread Quote
01-28-2015 , 11:45 AM
Quote:
Originally Posted by cookies4u
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.
Programming homework and newbie help thread Quote

      
m