python: How to sum a series using an increment number - python

n = int(input('Enter n: '))
count = 1
sum = 0
number = 1
while (count <= n):
sum = sum + number
count = count + 1
number = number + 2
print('Sum =', sum)
Is it possible to use the same concept for 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 .... + n

You could use a list comprehension to make this more elegant and pythonic:
def sum_series(start, end):
return sum([i**2 for i in range(start, end+1)])
print(sum_series(1,10))
Output:
385
Or using higher order functions:
>>> sum(map(lambda x: x**2, range(1,11)))
385

Something like this should do
n = int(input('Enter n: '))
count = 1
sum = 0
while (count <= n):
sum = sum + count*count
print("{s}+".format(s=sum)
count = count + 1
print('Sum =', sum)

Related

Primal number task

Hi I have task that that I dont know how to do. Basically I need to write primal numberswhere is only difference by 2 numbers, only primal number which is either two more or two less than another prime number and then print every pair of these primes that are less than or equal to 100.
Here is how it should look like.
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
Here is my code.I don't know how to eliminate these that are more than 2
for b in range(1, n):
if b>2:
for p in range(2, b):
if (b%p) ==0:
break
else:
print(b )
Without changing your existing code, you could do:
lastprime = 2
for b in range(1, n):
if b>2:
for p in range(2, b):
if (b%p) ==0:
break
else:
if b == lastprime + 2:
print(lastprime, b)
lastprime = b
It should be a bit more efficient by using Sieve of Eratosthenes:
sieve = [True for _ in range(n + 1)]
current_number = 2
while (current_number * current_number <= n):
if (sieve[current_number] == True):
for i in range(current_number * current_number, n + 1, current_number):
sieve[i] = False
current_number += 1
primes = [index for index in range(2, n + 1) if sieve[index]]
for i in range(len(primes) - 1):
first = primes[i]
second = primes[i + 1]
if first + 2 == second:
print(f'{first} {second}')
or even more efficient:
sieve = [False] * 2 + [True] * (n - 1)
for number in range(int(n ** 0.5 + 1.5)):
if sieve[number]:
for i in range(number * number, n + 1, number):
sieve[i] = False
primes = [i for i, prime in enumerate(sieve) if prime]
for i, first in enumerate(primes[:-1]):
second = primes[i + 1]
if first + 2 == second:
print(f'{first} {second}')
Explanation:
https://www.geeksforgeeks.org/sieve-of-eratosthenes/

How to write Python program with output like this: Limit: 18 The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

My code looks like this at the moment:
limit = int(input("Limit:"))
number = 1
sum = 1
while sum < limit:
number = number + 1
sum = sum + number
print(f"The consecutive sum:{sum}")
Add the numbers you're using in a separate list. Then use str.join() to join these numbers with a ' + '.
limit = int(input("Limit:"))
number = 1
total = number
numbers = [str(number)]
while total < limit:
number = number + 1
total = total + number
numbers.append(str(number)) # Need to convert to string here because str.join() wants a list of strings
print(f"The consecutive sum: {' + '.join(numbers)} = {total}")
Which prints the required output:
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
limit = int(input("Limit:"))
number = 1
sum = 1
print("The consecutive sum: 1", end = " ")
while sum < limit:
number += 1
sum += number
print(f'+ {number}', end = " ")
print(f'= {sum}')
Output Will Be:
Limit:18
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

The sum of the digits is incorrect. Why?

i can't understand why the output of my code concatnates the digits instead of showing their sum:
#Get a number, and show the number of digits and the sum of the digits.
num = int(input('Enter a number: '))
j = 0
i = 1
k = 0
while i < num:
i = i*10
j += 1
k += (num - k)%i
print (f' The number has {j} digit(s), and the sum is: {k}')
Follow the code. Let's say num = 432:
i = 1 * 10 = 10
j = 0 + 1 = 1
k = 0 + (432 - 0)%10 = 2
---
i = 10 * 10 = 100
j = 1 + 1 = 2
k = 2 + (432 - 2)%100 = 2 + 32 = 34
---
i = 100 * 10 = 1000
j = 2 + 1 = 3
k = 34 + (432 - 34)%1000 = 34 + 398 = 432
This algorithm is most definitely not adding every digit. There are several ways to do what you intend in python. One way is inputting the number as a string and summing every digit casting them as integers inside a generator:
num = input('Enter a number: ')
total = sum(int(digit) for digit in num)
print(total)
If you want the number to be an integer since the beginning, you can also do this:
num = int(input('Enter a number: '))
total = 0
while num > 0:
digit = num%10
total += digit
num /= 10 # num //= 10 in python 3
print(total)

Trying to outputting a math equation with for loop in python

So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:
z= 1
while z > 0:
for i in range(len(list)):
print(list[i],"+", end=" ")
z = 0
print("=",sum(list),end=" ")
This is what i am trying and output is:
2 + 5 + 6 + 9 + 1 + = 23
What should I do if I want to output n integers and n-1 plus signs between integers?
You may use str.join that accept an iterable of strings. You need to map each int to str then join them using the + and print the result
values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values)) # 2 + 5 + 6 + 9 + 1 = 23
# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)
Use join:
def printfn(alist):
expr = " + ".join((map(str, alist)))
sum_val = sum(alist)
print("{} = {}".format(expr, sum_val))
a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6
b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10
Another possibility is to use sep= parameter of print() function.
For example:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
Prints:
2 + 5 + 6 + 9 + 1 = 23
You can use enumerate(), starting with an index of 1
>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
if i == len(l):
# If the current item is the length of the list then just append the number at this index, and the final sum
s += str(v) + ' = ' + str(sum_)
else:
# means we are still looping add the number and the plus sign
s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23
Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0
list = [2,5,6,9,1]
z= 1
while z > 0:
for i in range( len(list)-1 ):
print(list[i],"+", end=" ")
print (list[len(list)-1],end=" ")
print("=",sum(list),end=" ")
z = 0

What is wrong with my program? Amicable program

Question 3: Amicable
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
def abundant(n):
while n > 0:
a = n
k = n
y = 0
total = 0
while k > y or n == 0:
if n % k == 0:
y = n // k
if k != n:
total = total + k + y
if k == y:
total = total - y
k -=1
total = total + 1
print(total)
def abundant2(n):
b = n
x = n
y = 0
total2 = 0
while x > y or n == 0:
if n % x == 0:
y = n // x
if x != n:
total2 = total2 + x + y
if x == y:
total2 = total2 - y
x -=1
total2 = total2 + 1
print(total2)
if total == b and total2 == a:
print('Amicable!')
amicable_numbers2 = int(total2)
amicable_numbers = int(total)
else:
print('Nope')
return abundant2
n += 1
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
nums = [amicable_numbers2, amicable_numbers]
nums2 = [n for n in nums if n >= amicable_numbers2 and n <= amicable_numbers]
return nums2
# return a value that is less than amicable_numbers2 and less than amicable_numbers???

Categories

Resources