Python: Adding odd numbers together from an input - python

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)

Related

WAP in python script to input a multidigit number and find each of the number's factorial

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}')

Change in variable values upon recursion, Python 3

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.

Python 3 - Program that requests positive integer and prints first 4 multiples of it

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) + ".")

Printing primes less than 100?

I am new to programming and trying to write a program that prints primes less than 100. When I run my program I get an output that has most of the prime numbers, but I also have even numbers and random odd numbers. Here is my code:
a=1
while a<100:
if a%2 == 0:
a+=1
else:
for i in range(2,int(a**.5)+1):
if a%i != 0:
print a
a+=1
else:
a+=1
The first part of my code is meant to eliminate all even numbers (doesn't seem to fully work). I also don't fully understand the part of my code (for i in).
What exactly does the "for i in" part of the code do? What is 'i'?
How can I modify my code that it does accurately find all of the primes from 1-100?
Thanks in advance.
See the comments on your post to find out why your code doesn't work. I'm just here to fix your code.
First of all, make use of functions. They make code so much more readable. In this case, a function to check if a number is a prime would be a good idea.
from math import sqrt
def is_prime(number):
return all(number%i for i in range(2, int(sqrt(number))+1))
There isn't much left to do now - all you need is to count how many primes you've found, and a number that keeps growing:
primes= 0
number= 1
while primes<100:
if is_prime(number):
print number
primes+= 1
number+= 1 # or += 2 for more speed.
Suddenly it's very easy to read and debug, is it not?
I'm going to try to guide you without giving you any code to help you learn, you should probably start from scratch I think and make sure you know how each part of your code works.
Some things about primes, 1 isn't prime and 2 is so you should start with a=3 and print 2 immediately if you want to eliminate even numbers.
By doing that, you will then be able to just increment a by 2 rather than 1 as you're doing now and just skip over even numbers.
As you loop a to be less than 100, you need to check if each value of a is prime by making another loop with another variable that loops downward through all numbers that could possibly divide a (less than or equal to a's square root). If that variable divides a, then exit the inner loop and increment a, but if it makes it all the way to 1, then a is prime and you should print it, then increment a.
There's several things wrong with what you're doing here:
You don't find the first 100 primes, you find the primes less than 100 with while a < 100
You print a every time a is evenly divisble by i, and then increment a. But you've gotten ahead of yourself! a is prime only if it is not divisble by any value i, but you fail to keep track of whether it's failed for any i.
You add +1 to the range up to the square root of the number - but that's not necessary. The square root of the number is the largest number that could possibly be the smaller of two factors. You don't need to add 1 because that number is _bigger than the sqare root - in other words, if a is evenly divisble by sqrt(a)+1 , then a / (sqrt(a)+1) will be smaller than sqrt(a)+1 and therfore would have already been found.
You never print the list of primes you found; you print a every time you find a number that is not a factor ( primes have no factors other than one and themselves, so you're not printing prime numbers at all!)
This might get you thinking in the right direction:
a=0
primes = []
while len(primes) < 100:
a = a + 1
prime=True
maxfactor = int(a ** .5)
for i in primes:
if i == 1:
continue
if i > maxfactor:
break
if a % i == 0:
print a, " is not prime because it is evenly divisble by ", i
prime=False
break
if prime:
print "Prime number: ", a
primes.append(a)
for p in primes:
print p

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Categories

Resources