Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.
Related
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)
This question already has answers here:
Implementing the collatz function using Python
(8 answers)
Closed 5 years ago.
Note: I was trying to figure out why my while statement did not evaluate to False when the integer was, so I don't believe this is a duplicate
Doing an automating the boring stuff exercise in python where the program receives an input and reduces it to 1 using the following algorithm.
#even / 2
#odd * 3 + 1
def collatz():
print("Enter number:")
number = input()
try:
data = int(number) # Input Validation
while int(data) != 1:
if data % 2 == 0: #Number is even
data = int(data/2)
print(data)
if data % 2 == 1: # Number is odd
data = int(3*data+1)
print(data)
except:
print("Please input a valid value")
collatz()
collatz()
Instead of the while loop breaking, when the number is reduced to 1. The loop continues and it multiplies 1 by 3 and adds 1(Just as normal odd number). Btw many int conversions were done as I thought it may have returned a floating point.
So please tell me where are the unncessary int conversions and how to break it using a while statement. Any cleanup to code is appreciated
There are a few things that you should neaten up to make your code work properly and just generally better:
Rename data to n, this isn't going to make much of a difference, but I would say it just makes more sense.
There is no need to do endless conversions to int, n only needs to be converted from a string to an integer once.
Don't put your entire code in a function then call it once, instead have the main algorithm in a smaller function which you then can call from the main body of your code or even create another function to call the algorithm which handles the inputting side of things.
Use the integer division operator (//) instead of the floating point divider (/), since the number will be even, you can be sure that the decimal place will be 0.
You don't need to check if n % 2 is 0 and then on the next line check if it n % 2 is 1, you can just use an if ... else clause.
And that's about it! Here's what it looks like:
#even / 2
#odd * 3 + 1
def collatz(n):
while n != 1:
if n % 2 == 0: #Number is even
n = n // 2
else:
n = n * 3 + 1
print(n)
number = input("Enter number:")
try:
number = int(number)
collatz(number)
except ValueError:
print("Please input a valid value")
And a test shows it works (input of 24):
12
6
3
10
5
16
8
4
2
1
I'm working on a problem that involves putting in an input, integer n, that when doing so will print off the following 4 "multiples" of the integer. I need to do this for 3 integers, n = 5, n = 0, n = 3.
Original Question:
Implement a program that requests a positive
integer n from the user and prints the first four multiples of n: Test
your module for n = 5; n = 0 and n = 3.
The output of the code should look like:
>>>
Enter n: 5
5
10
15
20
So, what I've come up with so far is this
n = (input("Enter n:"))
This allows me to input an integer value.
Next using print(n), this will print the value I input (Ex. number 5), but I'm not sure how to print off multiples of it after. I realize it's a loop question, most likely involving if or in, but I'm not sure where to go after this.
You've pretty much figured out the question on your own. The correct code is:
n = int(input("Enter n:"))
for i in range(4):
print(n*(i+1))
So, what this for loop does for you is repeat your print statement 4 times, where you give i the values of the expression range(4).
If you just print(range(4)), you'll see that it evaluates to [0,1,2,3]. That's why I had to add 1 to it each time.
The int() function call is needed because input() returns a string, not a number. So if we want the mathematical operators to do what we expect, we need to first convert it to a number (in this case, an integer).
This is the general logic:
n = (input("enter n:"))
for(int i = 1; i <= 4; i++){
print(int(float((n))*i);
}
if you want the list to start with 0 you can do this, it has an error but it can be fixed...
number = int(input("Give a number:"))
for multiples in range(10):
getal1 = number * multiples
print("\t The", str(multiples + 1) + "e multiple of," + number, "is", str(getal1) + ".")
Here is the problem from leetcode:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
question 1: from my understanding, if 1 happens,return True else it will infinitely runs the loop where i understand from this sentence "or it loops endlessly in a cycle which does not include 1."
However,after i found some answer to this questions from internet, i found my understanding was wrong.It is supposed to be if 1 happens return True,**also if any number repeats in the set, then end the loop and return False.**Well, be honestly, the problem says "or it loops endlessly in a cycle which does not include 1." why we just let the program run endlessly in a cycle as it states??
questions 2: For the second question, i think it is about understanding the codes.This is what i found from internet:
def isHappy(n):
stop = {1}
while n not in stop:
stop.add(n)
n = sum(int(d)**2 for d in str(n))
return n == 1
From this codes, i can understand that if 1 happens, it will stop running the while loop and return True.However, if repeat number happens in the set, i think it also will stop running the while loop and return True,becuase next line followed by while statement is still return n==1.However, in fact it will output False.e.g
since 89 repeats again in the set, output False.
Sorry for my wordy description.Simply speaking, my questions is how this false comes out? in the coding, there is no place explicitly return False
The isHappy function you posted is correct.
This is how it works -
It will calculate the squares of the digits and save it in n.
If n is 1 it stops. Else, it appends n to change list and loops. But as soon as n is any number which is there in the change list, the loop breaks.
In Python, when control comes out of the loop, it has the last values stored in variables. So, n has the last calculation stored.
Now, if n is 1, n == 1 returns True else False.
Hope that helps.
This is how I did , even though it is a bit messy
#Python program to check if a number is a happy number
#Creating an user defined function which returns True if the number is happy else False
def happy(num) :
#Creating a copy of the number in a string and a iterating point
copy = str(num)
square = num
#Proceeding with while loop due to unknown iterations
while True : #inifinte loop
square = sum(int(j) ** 2 for j in list(str(square))) #Sum of the number's digit squares
if square == 1:
test = True
break
elif square == 4:
test = False
break
return test
check = int(input('Enter the number: '))
print('The number {} {} a happy number'.format(check, ('is') if happy(check) == True else ('is not')))
below is a popular solution to the happy number problem. this key is the sum of square of each digit did not appear in the past, otherwise, there will be an endless loop.
class Solution:
# #param {integer} n
# #return {boolean}
def isHappy(self, n):
s=set()
while n!=1 and n not in s:
s.add(n)
n= sum([int(x)**2 for x in str(n)])
return n==1