python - a collatz program automate the boring stuff [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi all I have read through the previous answers to this question and can get the code to run. What I want to understand is why my code doesn't run.
Thanks
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
print('Enter a number')
number = int(input())
while number != 1:
print(int(collatz(number)))

You are not updating number in your while loop so you are stuck in an infinite loop.
You should assign return value of collatz to number back, to update number.
while number != 1:
number = collatz(number)
print(number)

Related

Why is this code so much faster in Python 2 than Python 3? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
The community is reviewing whether to reopen this question as of 4 days ago.
Improve this question
This is an algorithm for calculating the least number of perfect squares, that, when added, equal n
def numSquares(n):
square_nums = [i**2 for i in range(0, int(math.sqrt(n))+1)]
dp = [float('inf')] * (n+1)
dp[0] = 0
for i in range(1, n+1):
for square in square_nums:
if i < square:
break
dp[i] = min(dp[i], dp[i-square] + 1)
return dp[-1]
It runs pretty fast in Python 2, but horrendously slow in Python 3. Anyone know why?

Reading ints in input in a Python program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I have to take input from the user then the operator has to print what number is before the input and after the input like:
input= 3
has to print 2 and 4
I used range, did I do it wrong? I am just a beginner in Python.
number=int(input)
for num in range(number ,+ 1, -1):
print(num)
You first need to use input() to let the user register a number.
Then, simply print the number with number - 1 and number + 1.
number = int(input("What is your number? "))
print(f"{number - 1} {number + 1}")
Outputs to:
What is your number? 3
2 4
you don't need range do this task
num = int(input())
print(num-1, num+1)
Other answers which say that you don't require a loop are perfectly fine, however I want to add a little suggestion in case you need to print more than just the number before and after. Maybe (as your first implementation suggests) you want to print the 5 numbers before and after. In this case you can do:
R = 5 #range
N = int(input("Enter your number. "))
numbers = [ i for i in range(N-R,N+R+1) if i != N]
print(numbers)

Sum of digit of a number using recursion in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
Here in this program, I tried to understand but couldn't get completely.
How is this recursive function doing the sum and returning total sum of this? Please explain me in detail?
# Recursive Python3 program to
# find sum of digits of a number
# Function to check sum of
# digit using recursion
def sum_of_digit( n ):
if n < 10:
return n
return (n % 10 + sum_of_digit(n // 10)) # how this is working ?
num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)
The best way to understand a recursive function is to dry run it.
First you need to understand what n % 10 mean is. this means the remainder of a n when divided by 10.
In this case when we divide 12345 by 10 , we get 5 as remainder.
so n % 10 part of code becomes 5.
Now, the second part is n//10 which gives you 1234 that are remaining digits.
Applying the same function again will give you 4 + sum_of_digit(123) and so on.
Even if this do not clear your confusion try, running this code on paper with some small number.

Create a function to determine if a number is even [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
As the home assignment, I have two code cells. In the first one, I need to write a code, while the second check the written function (it was made by a professor)
[Cell1]
def is_even_number(num):
'''
Returns True if num is even number, otherwise False
Parameters
----------
num : an integer
Returns
-------
True if num is even number, otherwise False
'''
# YOUR CODE HERE
while num:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
[Cell2]
assert_true(is_even_number(2), msg='2 is an even number.')
assert_true(not is_even_number(1), msg='1 is not an even number')
As a result of run Cell2, I see the message NameError: name 'assert_true' is not defined
I think it should be assertTrue . If it's using the module unittest. Here's the link

How could I loop a code involving a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm fairly new to python and I was wondering if someone was able to help me with looping this block of code and I did looping in the past but this one involves a list element having to change every time 1 through to 10 and I don't know how I could make that change.
print ("Question 1: ")
print (questions[0])
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(questions[0]):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
The closest way to do so while maintaining your code is the following
for index, question in enumerate(questions):
print ("Question {}: ".format(index+1))
print (question)
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(question):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
Note that you should avoid using eval because it is unsafe. Recommended alternatives are to either make a dictionary with pre-baked questions and answers, e.g.
questions = {'What is 5 + 4?' : 9,
'What is 3 - 1?' : 2}
Or programmatically come up with questions and answers.

Categories