Compute a range python - python

I'm stuck on a range. It should be pretty simple by for some reason I can't figure it out. So i have a range of (x,y) and it should add every number within that range however once it gets to the third it should double and then continue adding them.
start = int(input())
end = int(input())
sum = 0
a = range (start,end)
for i in range (start,end):
sum = sum + i
i += 1

start = int(input())
end = int(input())
sum = 0
for i, v in enumerate(range(start,end+1)): #7+1 as it's non inclusive
sum+=v
if (i+1)%3 == 0: #every 3 it *2
sum *=2
print(sum)
and it outputs 72, as expected

Iterate over the range with step=3, and within that loop add the sum of each smaller range to the total before multiplying it by two.
total, start, end = 0, int(input()), int(input()) + 1
for i in range(start, end, 3):
total += sum(range(i, min(i+3, end)))
total *= 2
print(total)
2
7
72

Related

How to write a for loop program that finds the sum of all odd numbers in a range, but does not use the if function

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 want to find the sum of the number which i have

I have some code where I must find the multiples of number 3 and then summarize them
I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found.
I have tried so many times and tried to find the solution on google, but could not find
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them
It's easier than you think:
sum(range(0, 1000, 3))
Explanation:
range is defined as such: range([start], end[, step]) so range(0, 1000, 3) means go from 0 to 1000 in steps of 3
The sum function will sum over any iterable (which includes range)
You need a variable to hold the sum (If you are in learning stage):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit:
To answer your comment use condition or condition:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result variable to which you can keep adding:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter and sum:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)

Sum of all prime numbers between 1 and N in Python

I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.

Largest Adjacent Numbers- Values Incrementing Incorrectly

I am writing this program to find the 13 adjacent digits in this number that, when added together, have the largest sum. When I run it, however, the b value does not start at 12; it starts at some obscenely high number and I cannot figure out why. Any idea why my a and b values are not incrementing correctly?
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
a = 0
b = 12
greatest = 0
while b != len(str(num)):
num = str(num)
newNum = num[a:b]
total = 0
for num in newNum:
num = int(num)
total += num
if total > greatest:
greatest = total
a+=1
b+=1
print(b)
print(greatest)
The main issue is that you are reusing num in the inner loop, which renders the "original" num wrong after the first run.
Additionally, if you want a 13 digits run-in, you'd better start with b = 13
And furthermore, there is no need for str(num) since it is already a string, and no need to change b along the program. You can also replace the inner loop with a sum upon map.
Here is what it should look like after these changes:
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
index = 0
run_in = 13
greatest = 0
while index + run_in < len(num):
num_slice = num[index: index + run_in]
slice_sum = sum(map(int, num_slice))
if slice_sum > greatest:
greatest = slice_sum
index += 1
print(greatest)
If you are into super functions, you can create the same effect with a list comprehension and a max closure, iterating all possible indexes (until the length of the number minus the run in):
greatest = max(sum(map(int, num[index: index + run_in])) for index in range(len(num) - run_in))
def largest(num, k):
num = str(num)
if len(num) < k: raise ValueError("Need a number with at least {} digits".format(k))
currsum = sum(int(i) for i in num[:k])
answer = currsum, 0
i = k+1
while i < len(num):
currsum -= int(num[i-k])
currsum += int(num[i])
if currsum > answer[0]: answer = currsum, i
i += 1
return answer
total, ind = largest(myNum, 13)
print("The maximum sum of digits is {}, starting at index {}".format(total, ind))

Why are these lines of code in python only outputting the same answer?

I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))

Categories

Resources