How do i reduce the number of outputs? - python

Suppose I input n=5, how do i get the first 5 numbers as the output and not 10?
#fibonacci sequence
n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
a=a+b
b=a+b
print(a)
print(b)

The way you are adding a and b in the for loop is wrong. If you use print twice it will print twice per loop.
n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
a, b = a + b, a
print(a)

n=int(input('Enter number of numbers: '))
a=1
b=0
for i in range(1,n+1):
a, b = a + b, a
print(a)
The problem with your approach is you go with step 2 each time. For example on one iteration you go from a=5, b=3 to a=13, b=8. So there is 2 * 5 outputs.

Try this out:
n = int(input('Enter number of numbers: '))
def fib(n):
curr, next_ = 1, 1
for _ in range(n):
yield curr
curr, next_ = next_, curr + next_
print(list(fib(n)))

Related

Incrementing from within for loop

I am trying to generate 5 unique random numbers and I have written a for loop for it:
for i in range(5):
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
If x is not in a, only then i should be incremented. I can do this with while loop but want to know if we can do this with a for loop.
You can do this by converting a range into list.
Please follow the given example code.
a = list()
n = 2
myrange = list(range(n)) # converting your range into list
for i in myrange:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
else :
# add current i again in the rangelist at starting position
myrange.insert(0,i)
You can't change how many times for i in range() loop runs. Changing i in the loop has no effect on the range() object.
You can use a nested loop that keeps asking until it gets a number that's not found.
for _ in range(5):
while True:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
break
Here are some approaches:
Option 1 :
Using an infinite value in the range function :
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)
Option 2 :
Using itertools.count:
import itertools
for i in itertools.count(start=1):
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)

How to draw numbers from a new line?

there is a code with prime numbers (which are displayed in the desired range)
Make simple numbers appear on the new line.
Here is the code:
a, b = map(int, input().split())
ls = []
for i in range(a, b + 1):
if all(i % n != 0 for n in range(2, i)):
ls.append(str(i))
if len(ls):
print(' '.join(ls))
else:
print(0)
I think you need a loop for print the result
print('= Enter the range (a,b) =')
a, b = map(int, input().split())
ls = []
for i in range(a, b + 1):
if all(i % n != 0 for n in range(2, i)): # check the numbers
ls.append(str(i))
print('========= Result ========')
#print the result
for number in ls:
print(number)
print('========== End ==========')

Check 3 Integers to see if they are Fibonacci triple

I am trying to input 3 integers and determine if they are Fibonacci Triples. A Fibonacci Triple is three consecutive Fibonacci numbers. Can someone help me figure out where I'm going wrong. Thanks!
def fibs():
a, b = 0, 1
yield a
yield b
while True:
a,b = b, a + b
yield b
fibInput = (input("please enter 3 numbers separated by commas: "))
n, o, p = [int(i) for i in fibInput.split(',')]
#print(n,o,p) TEST
for fib in fibs():
if n == fib and o == fib and p == fib:
print("Your numbers are a fibonacci triple.")
break
if fib > n and fib > o and fib > p:
print("your numbers are not a fibonacci triple.")
break
if n == fib and o == fib and p == fib:
You're not checking whether the three numbers are consecutive Fibonacci numbers. You're checking whether they're all the same Fibonacci number.
In your loop fib has the same value.
You could write other generator for Fibonacci triples
def fib_triple():
it = iter(fibs())
a = it.next()
b = it.next()
c = it.next()
while True:
yield(a, b, c)
a, b, c = b, c, it.next()

Creating Python Factorial

Evening,
I'm an intro to python student having some trouble.
I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)
The 'classic' factorial function in school is a recursive definition:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
If you just want a way to fix yours:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
If you want a test for numbers less than 1:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Or, test n after input:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Here is a functional way using reduce:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800
You are actually very close. Just update the value of n with each iteration:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)
I am new to python and this is my factorial program.
def factorial(n):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)
factorial(5)
You could do something like this.
def Factorial(y):
x = len(y)
number = 1
for i in range(x):
number = number * (i + 1)
print(number)
#Factorial using list
fact=list()
fact1=input("Enter Factorial Number:")
for i in range(1,int(fact1)+1):
fact.append(i)
print(fact)
sum=fact[0]
for j in range(0,len(fact)):
sum*=fact[j]
print(sum)
i=1
f = 1
n = int(input("Enter n: "))
if n>=0:
while n >= i:
f=i*f
i+=1
print(f)
I am using this code in order to calculate factorial and it works.(Python 3.8)

Solving Project Euler #2 in Python

I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum

Categories

Resources