Python Version of My Java Homework

Jan 17, 2009 17:25

le_bebna_kamni knows Java really well, which has come in handy for tutoring, I can tell you ( Read more... )

java, computers, hacking, python, computer

Leave a comment

Comments 7

loop_bell January 18 2009, 02:32:23 UTC
Here's a neat trick I've recently learned in Python for conditional assignments:

This:

if hour == 1:
pluralHour = ""
else
pluralHour = "s"

Is the same as this:

pluralHour = "s" if hour == 1 else ""

I think the second actually shows a little more clearly what is being done, especially in cases like this where the if clause is short. (When the if clause is really long, it tends to make the lines get unreadably long when you do it this way)

In lojban terms, think of it as a sort of SE variety of conditianals -- the x2 gets rotated out to the front and then x1 and x3 follow. Or I also think of it as "inside out" notation, because the part that's normally in the middle comes first.

Reply

matt_arnold January 18 2009, 02:53:12 UTC
Oh, that's good!

Reply


le_bebna_kamni January 18 2009, 03:46:14 UTC
As requested, here is my code. Let me just say that at least half of the cursing was from Matt's request *after* I had coded it the first time, to display my loop in the same format as his did, with the same spacing, punctuation, and pluralization. ;P

The print function -- which I had used originally -- has extra spaces by default that make the same formatting in a loop impossible to implement. Here's what I came up with:seconds = input('Enter the number of seconds: ')

time = [("hour",seconds/3600), ("minute",(seconds%3600)/60), ("second",(seconds%3600)%60)]

result = ''
for index,item in enumerate(time):
    name,value = item
    if value != 1:
        name = name + "s"
    if index == len(time)-1:
        result += "and "
    result += `value` + " " + name
    if index != len(time)-1:
        result += ", "

print "\t", result
I've read that using index to refer to loops is not very Pythonic (damn you, Java, for corrupting me!). Is there another way that I could run the loop without making explicit [numerical] reference to the last ( ... )

Reply


anyaristow January 18 2009, 08:31:14 UTC
My first python program :)

def plural( num):
if num == 1:
return ""
else:
return "s"

totalSeconds = input("How many seconds?")
hours = totalSeconds / 3600
remainingSeconds = totalSeconds % 3600
minutes = remainingSeconds / 60
seconds = remainingSeconds % 60

print str(hours) + " hour" + plural( hours) + ", " + str(minutes) + " minute" + plural( minutes) + ", and " + str(seconds) + " second" + plural( seconds) + "."

Reply

le_bebna_kamni January 18 2009, 16:08:05 UTC
Nice!

Reply

matt_arnold January 18 2009, 16:58:21 UTC
I like that approach best.

What other programming languages have you used?

Reply

anyaristow January 18 2009, 18:36:33 UTC
Most of them. Enough to be proficient? Recently enough to remember them? Just C and lsl.

Reply


Leave a comment

Up