i am looking for help. We need to write a program that prints all numbers in the range of (n -20,n + 20). In addition, the program asks you beforehand to input a number. If that number is not even or multiple of 10, you need to take a guess again. Only if the number is even and multiple by 10 the program prints the range aforementioned. I struggle with that.
I came up with that solution:
i = int(input("please enter a number: "))
while (i % 10 == 0) and ((i % 2) == 0):
x = 20
while (x >= 0):
print(i - x)
x = x - 1
break
but it will only print the range n-20 and not +20 and it also won't ask you again if you input a false number.
I know there is also the possibility to use for I in range() but I am at a loss for ideas at the moment.
Thank you!
You can simply do:
while True:
i = int(input("please enter a number: "))
if i % 10 == 0:
for x in range(i-20,i+21):
print(x)
break
It will keep on asking until it satisfies the condition.
Better make use of range, something like:
x = 20
for number in range(i - x, i + x + 1):
print(number)
Note: range(1, 5) creates a generator which yields the numbers 1 to 4, excluding 5. Thus the i + 20 + 1.
Doing it the hard way: you want to start from i-20, so:
n = i - 20
and go to i+20, so:
while n < i+20:
print(n)
n += 1
All there is to it.
Or, the easy way, aka one liner using range
print(range(i-20, i+20), sep="\n")
Start with
i = 1
while not (i % 10 == 0):
i = int(input("please enter a number: "))
to keep asking until valid input is entered and the problem is solved.
Related
I need to write a code that asks for user input 'num' of any number and calculates the sum of all odd numbers in the range of 1 to num. I can't seem to figure out how to write this code, because we had a similar question about adding the even numbers in a range that I was able to figure out.
I've also added the lines of code that I've written already for any critiques of what I may have done right/wrong. Would greatly appreciate any help with this :)
total = 0
for i in range(0, num + 1, 1):
total = total + i
return total
total = sum(range(1, num + 1, 2))
if you really need a for loop:
total = 0
for i in range(1, num+1, 2):
total += i
and to make it more exotic, you can consider the property that i%2==1 only for odd numbers and i%2==0 for even numbers (caution: you make your code unreadable)
total = 0
for i in range(1, num+1):
total += i * (i % 2)
You can invent a lot more ways to solve this problem by exploiting the even-odd properties, such as:
(-1)^i is 1 or -1
i & 0x1 is 0 or 1
abs(((1j)**i).real) is 0 or 1
and so on
The range function has three parameters: start, stop, and step.
For instance: for i in range(1, 100, 2) will loop from 1-99 on odd numbers.
Easiest solution
You can use math formula
#sum of odd numbers till n
def n_odd_sum(n):
return ((n+1)//2)**2
print(n_odd_sum(1))
print(n_odd_sum(2))
print(n_odd_sum(3))
print(n_odd_sum(4))
print(n_odd_sum(5))
1
1
4
4
9
Using filter:
start_num = 42
end_num = 500
step = 7
sum([*filter(lambda x: x % 2 == 1, [*range(start_num, end_num+1, step)])])
You can use the math formula (works every time):
num = int(input("Input an odd number: "))
total = (1+num)**2//4
print(total)
Output:
Input an odd number: 19
100
total = 0
num = int(input())
for i in range(num+1):
if i%2 == 1:
total += i
print (total)
The % operator returns the remainder, in this case, the remainder when you divide n/2. If that is 1, it means your number is odd, you can add that to your total.
You can of course do it in 1 line with python, but this might be easier to understand.
I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
M = M + 1
print(sum)
This is my python code, every time I run the program, it prints the number twice. (1 1 4 4 9 9 etc.) Just confused on why this happening - in intro to computer programming so any help is appreciated (dumbed down help)
My guess is the print statement is not indented inside the if statement properly. As the sum wont increase for an even number and every other number is even
Make sure you have everything indented properly
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
print(sum)
M = M + 1
My best bet would be to add M++ line after the scope of if statement.
What really is happening that your increment only works when it is inside the if statement but this is logically incorrect because it should increment everytime loop executes.
Get rid of eval() you really do not need it. and replace it with int(). By default input() is a string by default so int() converts it to an integer.
You are using a reserved keyword sum
Try running sum.__doc__. You will see that sum is actually an inbuilt function. You should not create a variable the same name as an inbuilt function. However you can use an underscore (described in pep8) and this will create a working variable.
Corrected code:
M = int(input("Input the first number "))
N = int(input("Input the second number(greater than M) "))
sum_ = 0
while M <= N:
if M % 2 == 1:
sum_ = sum_ + M
M = M + 1
print(sum_)
Okay, i have made my code so that a user can input 7 numbers and times them by 1 for the odd index numbers and 3 for the even:
num = str(input("Please enter 7 numbers")
length = len(num)
while length < 7 or length ? 7:
num = input("Only enter 7 numbers")
string = ''
for t in range(1,8):
if t % 2 == 0:
string += str(t * 3)
else:
string += str(t) + ' '
print(string)
This works fine, but now i need to add all the numbers up and take it away from the highest 10 so for example, all the numbers add up to 53 i need to take that away from 60 which leaves me 7, that will be my eight number, then after i have got that number i print it out, how do i get it to add the numbers up and the take it away from the highest 10 and output the difference of the two into the numbers i already have?
Thanks
Brad
If you have a number, x, which is equal to 53, then going up should be math.ceil(x) except that math.ceil() rounds for 1. To account for that, we divide by 10, use math.ceil(), and then multiply by 10 again:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x
Brad could you clarify your question? Also your above code does not work.
Missing a bracket on the first line and this isn't valid while length < 7 or length ? 7:
I believe this is what you're looking for:
def take_away_from_nearest(number, nearest):
return nearest - (number % nearest)
Usage:
>>> take_away_from_nearest(53, 10)
7
edit:
If I understand you correctly, this would be the entire code:
while True:
# this is just an easy way to keep asking until the input is correct
num = input("Please enter 7 numbers: ")
if len(num) == 7:
break
weird_sum = 0 #here's where we're gonna sum up the numbers; the "eighth number"
for index, character in enumerate(num):
if index % 2 == 0: # index is odd, so count the character thrice
print(3 * int(character))
weird_sum += 3 * int(character)
else: # index is even
print(int(character))
weird_sum += int(character)
print(10 - (weird_sum % 10)) # 10 minus (weird_sum modulo 10)
# and finally, adding them all up and checking whether it ends with 0:
print((10-(weird_sum % 10) + weird_sum) % 10 == 0) # prints True
I was about to code a program which evaluates a polynomial. But the code below is just a try-out for that. The code below gives an output that stops when "counter = t"... I want it to give an output up to when counter=0. How can that be? I wanted to treat every number(input) as a coefficient of the polynomial. If I was successful doing this, I'm planning to make a list then for every, say, element in the list, I will then multiply it to a certain number raised to its index then add them up so that I've evaluated a polynomial.. Am I clear? And will my plan work out?? Thank you so much.. Please help..
t = input("Enter degree of Polynomial: ")
while t < 0:
print ("Not possible! ")
t = input("Enter degree of Polynomial: ")
counter = 0
while counter < t:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
counter += 1
THe ouput goes like this:
Enter degree of polynomial: 5
n: 5
3125
n:4
256
n:3
27
then it ends.. it should continue asking for an input n up to five times..
Try to use raw_input() and keep in mind that raw_input() returns always a string. So you have to convert the returned string to an integer like:
>>> x = int(raw_input("foo: "))
Then it is possible to test something like x > 2 etc. Without casting to integers the following would happen:
>>> "2" > 1
True
>>> "2" > 3
True
First of all: Well done - it's only a little mistake: Remove the "syntactic whitespace" in your last line, or remove it completly
Secondly: Don't forget to add the values ;-) - and with regards to your headline, this is best done with a python list.
The problem seems (to me) that you are having the loop depend on 2 variables, where you perhaps expected it to be only dependent on 1.
Perhaps this works a little better:
while t > 0:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
Something like this?
while True:
degree = int(raw_input("Enter degree of Polynomial: "))
if degree >= 0:
break
print ("Not possible!")
x = float(raw_input("x = "))
y = 0.0
for exponent in reversed(range(degree)):
k = float(raw_input("k[{0}] = ".format(exponent)))
y += k * (x ** exponent)
print("y = ", y)
This solves a polynomial of the form:
y = (k[N-1] * (x ^ N-1) + (k[N-2] * (x ^ N-2) + ... + k[0]