![]() |
|
|
|
| ||||||
|
Welcome to the The ProgrammersTalk Community forums. You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today! If you have any problems with the registration process or your account login, please contact contact us. |
![]() |
![]() | | LinkBack | Thread Tools | Display Modes | ![]() |
| |||
| Help with Python Does anyone know how to make the program running until the ouput becomes 1? If hail(x) = x/2 if x is even(i.e., x%2 is 0) and hail(x) = 3x+1 if x is odd(i.e., x%2 is 1) example: Please enter a starting value: 3 Output will be: 3 10 5 16 8 4 2 1 so far wat i came up with was: Code: x = int(raw_input("Please enter a starting value:"))
def hail(x):
if x % 2 == 0:
return x / 2
else:
return (3*x)+1
output = hail(x)
print output Last edited by TeraTask : 11-03-2007 at 01:34 PM. Reason: Added code tags |
| |
| |||
| a solution """ Here's a solution that uses a bastardized "do while" loop(without out the do) and recursion. you need the recursion to reprocess the result. do while loops have been considered unpythonic, although that attitude that is changing """ Code: x = int(raw_input("Please enter a starting value:"))
def hail(x):
if x % 2 == 0:
return x / 2
else:
return (3*x)+1
while True:
x = hail(x) # recursive function call
output = x # don't really need the extra variable but it makes things clearer
print output
if output == 1:
break Last edited by TeraTask : 11-03-2007 at 01:33 PM. Reason: Added code tags |
| The Following 2 Users Say Thank You to writtinfool For This Useful Post: | ||
HelloWorld (11-03-2007), TeraTask (11-03-2007) | ||
![]() |
| Thread Tools | |
| Display Modes | |
| |