LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   3x+1 in python, correct? (https://www.linuxquestions.org/questions/programming-9/3x-1-in-python-correct-631743/)

raskol 03-30-2008 03:11 PM

3x+1 in python, correct?
 
how do u keep intendation when posted? its intendented now as i see it but it comes out unintendented.

main question: is this a correct implementation of the 3x+1-program listed some posts below?
http://www.linuxquestions.org/questi...roblem-631581/

Code:

a=raw_input("do the 3x+1 on this number: ")
a=int(a)
b=0
while a!=1:
    if a==a/2*2:
        a=a/2.0
        print a
    else:
        a=a*3+1
        print a
    b=b+1

print b

raw_input()

i get b=1076 when doing it on 6. but it seems u will always divide until it becomesso small that maybe the program does something weird?

also in the else-part do i need to do a=a*3.0+1 or is it ok with just 3?

angrybanana 03-30-2008 04:01 PM

[ code]
put code here
[/code]

no space between the [] and "code". Also if you have javascript enabled you can just hit the "#" button when you post and it'll do it for you.

Maligree 03-30-2008 04:06 PM

Code:

a=raw_input("what's the number, master? ")
a=int(a)
b=0

while a!=1:
        if a%2==0:
                print str(a)+" (even)"
                a=(a/2)
        else:
                print str(a)+" (odd)"
                a=a*3+1
        b+=1

print "reached 1 after "+str(b)+" loops"

Worked for me.

(Wow, it's been a while since the last time I wrote anything in Python. I forgot how beautiful it is..)

Dan04 03-30-2008 04:15 PM

Use the // operator instead of / if you want to do int division.

raskol 03-30-2008 04:19 PM

Quote:

Originally Posted by Dan04 (Post 3105226)
Use the // operator instead of / if you want to do int division.

a//2*2 is the same as a/2*2 no?

Dan04 03-30-2008 08:04 PM

Nope.

Originally, Python's / operator did floor division if its operands were both of type int or long, and true division otherwise. That is, 1/2 == 0, but 1.0/2.0 == 0.5. That behavior works fine for a statically-typed language like C, but in Python it caused problems. For example, consider the function

Code:

def mean(num_list):
    return sum(num_list) / len(num_list)

mean([3.0, 4.0]) == 3.5, but mean([3, 4]) == 3. A lot of people complained about this. So Python decided to have two distinct division operators: / and //.

The // operator does floor division, even with floats.

Starting with Python 3.0 (currently in alpha and scheduled for final release in September), the / operator on ints will return the same as 1.0*x/y . As a transitional measure, this new behavior has been available since Python 2.2 if you start your script with:

Code:

from __future__ import division
Always do this. It's less error prone, and will make the transition to 3.0 easier.


All times are GMT -5. The time now is 10:44 PM.