Run and Re-run "block" of code

This is the place for queries that don't fit in any of the other categories.

Run and Re-run "block" of code

Postby webmanoffesto » Sat Apr 20, 2013 11:38 am

I'm new to Python and I'm doing the Udacity CS101 course.

If I write three versions of a program (Version1, Version2, Version3) and inside each program I want to run the same block of code

for example
Code: Select all
print "Test set 1, answer = 9", biggest(3, 6, 9)
    #>>> 9

    print "Test set 2, answer = 9", biggest(6, 9, 3)
    #>>> 9

    print "Test set 3, answer = 9", biggest(9, 3, 6)
    #>>> 9


How do I make that into a one line command. I don't think I need to "define a function" such as "def run_tests():" because I'm not "acting" on any pieces of data. What would you recommend?
webmanoffesto
 
Posts: 6
Joined: Sat Apr 20, 2013 11:28 am

Re: Run and Re-run "block" of code

Postby hansn » Sat Apr 20, 2013 4:35 pm

I'm not sure exactly what you want to do.

Please try to rephrase your question, maybe post the code you are working on, and I will try to answer.
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: Run and Re-run "block" of code

Postby setrofim » Sat Apr 20, 2013 5:47 pm

Code: Select all
>>> data = [(3, 6, 9), (6, 9, 3), (9, 3, 6)]
>>> for i, d in enumerate(data, 1):
...     print "Test set {}, answer = 9".format(i), max(*d)
...
Test set 1, answer = 9 9
Test set 2, answer = 9 9
Test set 3, answer = 9 9

Or, if you really want a "one line command", then
Code: Select all
>>> from __future__ import print_function
>>>
>>> map(lambda x: print("Test set {}, answer = 9".format(x[0]), max(*x[1])), enumerate([(3, 6, 9), (6, 9, 3), (9, 3, 6)], 1))
Test set 1, answer = 9 9
Test set 2, answer = 9 9
Test set 3, answer = 9 9
[None, None, None]

I would not advise doing it this way though.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: Run and Re-run "block" of code

Postby snippsat » Sat Apr 20, 2013 8:14 pm

This is the task.
Code: Select all
# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.

 def biggest (a,b,c):
     #Your code
User avatar
snippsat
 
Posts: 171
Joined: Thu Feb 21, 2013 12:04 am

Re: Run and Re-run "block" of code

Postby setrofim » Sat Apr 20, 2013 8:28 pm

Yeah, I assumed biggest() would be part of the task, however OP wan't asking how to implement biggest() (at least, I didn't interpret their post to be asking that). Using max(), I could post working code answering the question they asked without "spoiling" the implementation of biggest(). Perhaps I should have clarified that that was what I was doing, and that OP should replace max() with biggest() in their code. Thanks for pointing that out, snippsat.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], puck2020 and 3 guests

cron