other options for solving tasks with list - python-3.x

Task:
Write a program that reads from the standard input and will return the:
sum
difference
product
of all elements in the given list.
Input
An integer n (1 <= n <= 500) that denotes the number of elements in the list. The following n integers are the next elements of the list.
Output
Three integers:
sum
difference
product
of all the elements of the list.
And these are my ideas, but I still get a mistake
from sys import stdin
def Simple_list_arithmetic():
print("Enter a positive number: ")
n = int(stdin.readline())
l = []
if n >= 1 and n <= 500:
for i in range(1, n+1):
l.append(i)
#print(l)
suma = 0
for add in range(0, len(l)):
suma = suma + l[add]
print(suma)
#return suma
difference = 2
for substract in range(0, len(l)):
difference = difference - l[substract]
print(difference)
#return difference
product = 1
for increase in range(0, len(l)):
product = product * l[increase]
print(product)
return suma, difference, product
else:
print("Wrong number.")
still wrong
suma = 0
q = [suma + l[add] for add in range(0, len(l))]
print(sum(q))
difference = 2
w = [difference - l[substract] for substract in range(0, len(l))]
print(list(w))
product = 1
e = [product * l[increase] for increase in range(0, len(l))]
print(sum(e))
still wrong
if n >= 1 and n <= 500:
for x in range(1, n+1):
print(x)
print("\n")
suma = 0
for add in range(1, n+1):
suma = suma + add
print(suma)
difference = 2
for substract in range(1, n+1):
difference = difference - substract
print(difference)
product = 1
for increase in range(1, n+1):
product = product * increase
print(product)
with map() and lambda still wrong
t = list(map(lambda add: suma + l[add], range(0, len(l))))
#return sum(t)
y = list(map(lambda increase: increase * l[increase], range(0, len(l))))
#print(y[-1])
#print(y)

try this:
x = int(input("Enter a positive number: "))
if x >= 1 and x <= 500:
sum = 0
for i in range(x,501):
sum +=i
print(sum)
diff = 2
for i in range(x,501):
diff -= i
print(diff)
prod = 1
for i in range(x, 501):
prod *= i
print(prod)

Related

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million

sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.
Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5+1)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
What about about this:
def isPrime(x):
prime = True
for i in range(2, x):
if x % i == 0:
prime = False
break
else:
continue
return prime
primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922
This code will take a few minutes to execute. Buckle up!!
def sumPrimes(n):
sum =0
for i in range(2 ,n):
for j in range(2, int(i / 2) +1):
if (i % j) == 0:
break
else:
sum += i
return sum
print(sumPrimes(2000000))
If you iterating over all numbers below 2 million, you might as well sieve them using the Sieve of Eratoshenes:
from math import ceil, sqrt
def sieve(n):
nums = list(range(2,n+1))
primes = []
p = 2
k = 1+ ceil(sqrt(n))
while p < k:
primes.append(p)
nums = [num for num in nums[1:] if num % p > 0]
p = nums[0]
return primes + nums
Then sum(sieve(2000000)) evaluates to 142913828922. It takes about 5 seconds to run on my machine.

How to check if this input is a negative number

I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True

List Index out of range, trying to get the [-1] position

I've tested to see if the list is empty and I'm sure it's not empty. So why this error continues?
The code is to find the smallest amount of factorial to a sum is equal to N.
def fat(n):
if n == 0 or n == 1:
return 1
else:
return n * fat(n - 1)
n = int(input())
ns = [x+1 for x in range(n)]
listaFat = []
l = []
for x in ns:
if fat(x) < n:
listaFat.append(x)
maior = max(listaFat)
listaFat.remove(maior)
print(listaFat)
print(len(listaFat))
while (fat(listaFat[-1]) + fat(maior)) < n:
l.append(listaFat[-1])
if len(listaFat) > 0:
listaFat.remove(listaFat[-1])
continue
else: break
print(l)
print(listaFat)

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

Nth Fibonacci number

I am failed to print only the nth fibonacci number.
In my code, when the user said to print nth trem it print the series upto nth term but i want to get the output only the nth term
e.g
if I say num=4
out put should be 2
please guide
here is the code:
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
print(Nth,end=' , ')
N1 = N2
N2 = Nth
sum += 1
The print stmt should be outside the loop
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
N1 = N2
N2 = Nth
sum += 1
print(Nth,end=' , ')
Simpler code, from the "How to Think Like a Comptuer Scientist: Python" book,
def fibonacci (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Just call fibonacci passing your nth term as the argument.
to achieve that output you can simply decrease the value of n by 1 and then carry on all the computation.
For example:
def fib(n):
n = n-1
a, b = 0, 1
count = 1
while count <= abs(n):
next = a + b
a = b
b = next
count += 1
return a

Resources