# factorial program
n = int(input())
fact = 1
for i in range(n,1,-1): #line4 # this line print the range in reverce
fact = fact*i
print(fact)
some explain the line4. how is the for loop printing the n in reverse?
The 3 main parameters of the range() function are start, stop and step. If you start at n to stop on 1 and decrease the index variable by 1 unit every time the loop executes, it will loop the values in reverse order.
For example:
n=10
for i in range(n,1,-1):
print(i)
This loop will start at i=10, as you can see from the step value, it will decrease its value by 1 until reach the stop value (exclusive), in this case, 1 too. So the output will be:
10
9
8
7
6
5
4
3
2
Related
I have used this code to determine the value of e^pi with a specified tolerance in spyder(Python 3.8).
from math import*
term=1
sum=0
n=1
while (abs(e**pi-term))>0.0001:
term=term*pi/n
sum+=term
n+=1
print(sum,e**pi)
I ran this code several times. But spyder is not showing anything when I run this code. I am new to python. So now I have no way to know whether this code is correct or not. It would be beneficial if you could verify whether this code is valid or not.
Okay, so the taylor series for e^x is sum n=0 to inf of x^n / n! which you seem to be doing correctly by multiplying by pi/n during each iteration.
One problem I noticed was with your while loop condition. To check the error of the function, you should be subtracting your current sum from the actual value. This is why you enter the infinite loop, because your term will approach 0, so the difference will approach the actual value, e^pi, which is always greater than .0001 or whatever your error is.
Additionally, since we start n at 1, we should also start sum at 1 because the 0th term of the taylor series is already 1. This is why you enter the infinite loop, because
Therefore, our code should look like this:
from math import*
term = 1
sum = 1
n = 1
while (abs(e ** pi - sum)) > 0.0001:
term = term * pi / n
sum += term
n += 1
print(sum,e**pi)
Output:
23.140665453179782 23.140692632779263
I hope this helped answer your question! Please let me know if you need any further clarification or details :)
The while loop does not end.
I have stuck in a condition to break out of the loop (at 10,000 cycles) to show this:
from math import*
term=1
sum=0
n=1
while (abs(e**pi-term))>0.0001:
term=term*pi/n
sum+=term
n+=1
if n > 10_000:
print('large n')
break
print(sum,e**pi)
If you replace the while loop with a for loop, then you can see each iteration as follows.
term=1
sum=0
for n in range(1, 101):
term=term*(math.pi)/n
sum+=term
print(n, sum, math.e**math.pi)
And this is the result for the first 10 items:
1 3.141592653589793 23.140692632779263
2 8.076394854134472 23.140692632779263
3 13.244107634184441 23.140692632779263
4 17.30281976060121 23.140692632779263
5 19.852983800478555 23.140692632779263
6 21.188246569333145 23.140692632779263
7 21.787511098653937 23.140692632779263
8 22.02284172901283 23.140692632779263
9 22.104987615623955 23.140692632779263
10 22.13079450701397 23.140692632779263
The numbers are getting larger, hence the while loop was never exited (and your laptop probably got quite hot in the process !!).
I was trying to make this infinite generator in python:
import math
def all_primes():
count = 2
while True:
flag = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
flag = False
if flag:
yield count
else:
count += 1
for i in all_primes():
print(i)
but in the output it always gives me 2. Why is that?
You don't augment count after finding a prime, so you're always returning the same value (3).
Your prime generator is going to take longer and longer between each prime as you move forward.
Here's an infinite prime generator that is more efficient. It is inspired from the sieve of Eratosthenes but uses a dictionary to only propagate multiples as it reaches a non-prime number and moves the prime multiple to the next multiple that hasn't been flagged as non-prime yet:
def genPrimes():
yield 2 # get the first prime out of the way
skips = dict() # multiples to skip {Multiple:2xPrime}
multiples = ((p*p,2*p) for p in genPrimes()) # multiples of primes
skipMark,_ = next(multiples) # skipping coverage
N = 1 # prime candidate (odd numbers)
while True:
N += 2 # next prime candidate
if N >= skipMark: # extend skips coverage
skipMark,stride = next(multiples) # 1st multiple and stride
skips[skipMark] = stride
if N in skips: # not a prime (multiple of a prime)
stride = skips.pop(N) # get prime multiple steps
multiple = N + stride # advance skip to next multiple
while multiple in skips:
multiple += stride # not already skipped
skips[multiple] = stride
else: # N is prime
yield N # return it
oputut:
for p in genPrimes(): print(p)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
...
The skips dictionary contains roughly one entry per √P (where P is the number of primes found so far) and doesn't require pre-allocating memory. This approach trades space for a gain in time.
The reason your code is always yielding '3' is that 'flag' is always true. Working through the math in the for loop with int(math.sqrt(count)+1) makes it so the loop only goes from 2 -> 2. So the only thing checked is if 3 % 2 == 0 which is never true. Therefore flag is always false and the count is never incremented.
Thats because the for loop is never itering. If count=3 then int(math.sqrt(count) + 1) is gonna return 2, so the range of your for loop is gonna be (2,2), therefore it will never iterate, and the flag value is not going to change, and therefore count value is always gonna be the same.
How to start a loop from certain number to n numbers in python.
Example: starting loop from 2 but ending based on n numbers
If I start a loop from 2 but wish to go through next 5 numbers how to achieve that?
2
3
4
5
6
7
Range will do that for you
start = 2
length = 6
for i in range(start, start + length):
print(i)
Or you could leave range alone and add your offset onto the number inside the loop
for i in range(0, length):
print(i+start)
Which would be less common but depending on the scenario this might be more readable.
I have a small problem with my code. I can't seem to figure out how to do this. I can get it to work with two for loops. But in the exercise it says that i only can use one loop to get the result.
The code is supposed to execute this:
bounce2(4):
4
3
2
1
0
1
2
3
4
What I have come up with:
def bounce2(n):
for x in range(n,-1,-1):
print(x)
Which prints out 4,3,2,1,0
But now i dont know what to do..
I have tried different if statements such as:
def bounce2(n):
for x in range(n,-1,-1):
print(x)
if n == 0:
x = x + 1
print(x)
But they only print one integer because they are out of the loop.
Same thing goes if i try to make the if-statement inside the loop, then it prints out something like 433221100. I dont know how to get the numbers to switch places. The print statement should also be an integer and not a string. So i can't use replaced.
Really need help to figure out the logic. All help is appreciated.
So, a little bit of my thought process before showing you the code. Clearly there are nine lines, or more generally n * 2 + 1 lines. Because we need to count down to 0 and back up. That's how many times you need to call print.
Now, if you add line numbers to the expected output and think of it as a table describing a function f(i, n) where i is the line number, and n is the starting and ending value. what is f? Can you write down the formula? e.g.
i f(i, 4)
0 4
1 3
2 2
3 1
4 0
5 1
6 2
7 3
8 4
We can write down the basic structure of the code, we still don't know what f look like but assume we have it:
for i in range(2*n+1):
print f(i)
And, what is f? Now you need to be a little creative and maybe experiment a bit. What I did was to try basic arithmetic combinations of i and n to match f(i, n), and I quickly noticed that n - i works until we reach the second half of the output, which only differs by a - sign.
i f(i, 4) n - i
0 4 4
1 3 3
2 2 2
3 1 1
4 0 0
5 1 -1
6 2 -2
7 3 -3
8 4 -4
Soooo, take the absolute value of n - i or i - n, whatever.
def f(i, n):
return abs(n-i)
Here is what I believe to be a pretty elegant solution:
def bounce(n):
for x in range(-n, n+1):
print(abs(x))
Our loop goes from the negative of n to the positive of n, printing the absolute value.
Since you need to count n times downwards, and another n times upwards, and 1 comes from counting 0, instead of actually counting downwards and then upwards in two separate loops, we can use one loop to count upwards 2 * n + 1 times, which effectively is like counting towards n and then bouncing off n, so we can simply calculate the "distance" to n instead, which is the absolute value of n - x:
def bounce2(n):
for x in range(2 * n + 1):
print(abs(n - x))
so that bounce2(4) would output:
4
3
2
1
0
1
2
3
4
a very simple solution will be:
for i in range(n, -(n+1), -1):
print(abs(i))
this like mirroring numbers around some point.
in your case that point is zero and to have identical mirroring use abs
Try the below, have a list l with a element of str(n) iterate trough the range of n times 2, then check x is bigger than n+2 if it is add 1 to n, otherwise subtract 1 from n, both cases append to l, then at the end, do str.join to join '\n' (newline) with l:
def bounce2(n):
l=[str(n)]
for x in range(n*2):
if x>n+2:
n+=1
l.append(str(n))
else:
n-=1
l.append(str(n))
return '\n'.join(l)
print(bounce2(4))
Output:
4
3
2
1
0
1
2
3
4
I cheated after giving up of how to figure out how to print digits backwards making a function for it but I still do not quite understand how it works. For instance why does it print the digits backwards and not in order?
def print_digits(n):
"""
>>> print_digits(13789)
9 8 7 3 1
>>> print_digits(39874613)
3 1 6 4 7 8 9 3
>>> print_digits(213141)
1 4 1 3 1 2
"""
while n > 0:
print n % 10
n = n / 10
I would appreciate a line by line explanation starting with the while loop. I've tried tracing it in my head and on paper but just can't grasp the code in the function.
In the first line in the loop the '%' operator devides the number given by 10 and returns the rest only, means the fraction of the division (25 : 10 = 2.5, so it returns the 5 only!).
The line 'n/10' then does exactly the other way around and stores part left of the comma into the variable itself, as the '/' operator returns only the left part of the comma.
In short you can say:
n%10 returns only the rest of the divison
n/10 "throws" the rest of the division away
the code repeats
% operator returns the remainder of division. (20%3=2,24%5=4).
When you divide a number by 10 remainder is always the last digit.
For example 123/10=12 & remainder is 3. So 123%10=3.
Inside the while loop while n is greater than 0 the last digit of n is printed.
And because of the line n=n/10, n becomes n/10. Here integer division has used so finally value of n will become 0 and then the loop will stop.( if n is initially 123 value of n will change as 123,12,1,0 and then loop will stop.)