Start loop from certain number to n number in python - python

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.

Related

python for loop to get the factorial of a number?

# 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

loop numbers down and up and not using recursion in python

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

range countdown to zero

I am taking a beginner Python class and the instructor has asked us to countdown to zero without using recursion. I am trying to use a for loop and range to do so, but he says we must include the zero.
I searched on the internet and on this website extensively but cannot find the answer to my question. Is there a way I can get range to count down and include the zero at the end when it prints?
Edit:
def countDown2(start):
#Add your code here!
for i in range(start, 0, -1):
print(i)
The range() function in Python has 3 parameters: range([start], stop[, step]). If you want to count down instead of up, you can set the step to a negative number:
for i in range(5, -1, -1):
print(i)
Output:
5
4
3
2
1
0
As another option to #chrisz's answer, Python has a built-in reversed() function which produces an iterator in the reversed order.
start_inclusive = 4
for i in reversed(range(start_inclusive + 1)):
print(i)
outputs
4
3
2
1
0
This can be sometimes easier to read, and for a well-written iterator (e.g. built-in range function), the performance should be the same.
In the below code n_range doesn't need to be told to count up or down, it can just tell if the numbers ascend or descend through the power of math. A positive value divided by it's negative equivalent will output a -1 otherwise it outputs a 1.
def n_range(start, stop):
return range(start, stop, int(abs(stop-start)/(stop-start)))
An input of 5, -1 will output
5
4
3
2
1
0

Multiples of 3 and 5 | Appending multiples to lists

I'v been studying Python for less than a month and am currently working on Project Euler.
So ironically I'm stuck on the first question. Check out my app road below and I would love some input as to where I have messed up. Or using the wrong logic.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
My Logic/Code Flow
sum = multiple_three + multiple_five
multiple_three = []
multiple_five = []
def multiple_three(bignumber):
for number in range(bignumber):
if number % 3 == 0:
multiple_three.append(number)
def multiple_five(bignumber):
for number in range(bignumber):
if number % 5 == 0:
multiple_five.append(number)
bignumber = 1000
multiple_five(bignumber)
multiple_three(bignumber)
print multiple_three
print multiple_five
Let's see.
We can start by using the fact that range has a step argument. So something like range(0,10,3) would get you 0,3,6,9.
So, for starters, we have
sum(range(0,1000,3)) + sum(range(0,1000,5))
But wait! Numbers divisible by 15 are divisible by both 5 and 3! We're counting them twice! Uh, uh, let's subtract them out
sum(range(0,1000,3)) + sum(range(0,1000,5)) - sum(range(0,1000,15))
Hum. I think we're still missing something here. Is there an easier way to add together an arithmetic progression? Could have sworn that there was...
something like (a_0 + a_n)*n/2, where n is the number of terms, maybe...
def sum_of_arithmetic_progression(start,stop,step):
n = (stop-start)//step #floor division :P
end = start + step*n
return (start + end)*n/2.0
sum_of_arithmetic_progression(0,1000,3)+sum_of_arithmetic_progression(0,1000,5)-sum_of_arithmetic_progression(0,1000,15)
This is what worked for me. Let me know if it worked for you too.
def multiples_of_3_or_5():
for number in xrange(1000):
if not number % 3 or not number % 5:
yield number
print sum(multiples_of_3_or_5())
You are not printing sum. But apart from that, you are counting numbers like 15 twice, i.e as a multiple of 3 as well as 5.
A quick solution would be to
print(sum(set(multiple_three+multiple_five)))
Here multiple_three+multiple_five gives a concatenated list. set identifies the unique elements, and sum will output the sum. Better would be to use "or"operator and append the numbers in a single loop as #Destry Amiott has suggested.

Getting the number of digits of nonnegative integers (Python) [duplicate]

This question already has answers here:
How to find length of digits in an integer?
(31 answers)
Closed 6 years ago.
The question asks:
<< BACKGROUND STORY:
Suppose we’re designing a point-of-sale and order-tracking system for a new burger
joint. It is a small joint and it only sells 4 options for combos: Classic Single
Combo (hamburger with one patty), Classic Double With Cheese Combo (2 patties),
and Classic Triple with Cheese Combo (3 patties), Avant-Garde Quadruple with
Guacamole Combo (4 patties). We shall encode these combos as 1, 2, 3, and 4
respectively. Each meal can be biggie sized to acquire a larger box of fries and
drink. A biggie sized combo is represented by 5, 6, 7, and 8 respectively, for the
combos 1, 2, 3, and 4 respectively. >>
Write an iterative function called order_size which takes an order and returns the number of combos in the order. For example, order_size(237) -> 3.
Whereby I should have
order_size(0) = 0
order_size(6) = 1
order_size(51) = 2
order_size(682) = 3
My code is:
def order_size(order):
# Fill in your code here
if order > 0:
size = 0
while order > 0:
size += 1
order = order // 10
return size
else:
return 0
But I don't get the order // 10 portion. I'm guessing it's wrong but I can't think of any stuff to substitute that.
No need for iterative function, you can measure the length of the number by "turning" it into a string:
num = 127
order = len(str(num))
print(order) # prints 3
But if you really want to do it iteratively:
def order(num):
res = 0
while num > 0:
num = int(num / 10)
res += 1
return res
print(order(127)) # prints 3
How about this:
from math import log
def order_size(order):
if order <= 0: return 0
return int(log(order, 10) + 1)
Some samples (left column order, right column order size):
0 0
5 1
10 2
15 2
20 2
100 3
893 3
10232 5
There are a couple errors in your suggested answer.
The else statement and both return statements should be indented a level less.
Your tester questions indicate you are supposed to count the digits for nonnegative integers, not just positive ones (i.e. you algorithm must work on 0).
Here is my suggested alternative based on yours and the criteria of the task.
def order_size(order):
# Fill in your code here
if order >= 0:
size = 0
while order > 0:
size += 1
order = order // 10
return size
else:
return 0
Notice that
By using an inclusive inequality in the if condition, I am allowing 0 to enter the while loop, as I would any other nonnegative single digit number.
By pushing the first return statement back, it executes after the while loop. Thus after the order is counted in the variable size, it is returned.
By pushing the else: back, it executes in the even the if condition is not met (i.e. when the numbers passed to order_size(n) is negative).
By pushing the second return back, it is syntactically correct, and contained in the else block, as it should be.
Now that's taken care of, let me address this:
But I don't get the order // 10 portion.
As of Python 3, the // is a floor division (a.k.a integer division) binary operation.
It effectively performs a standard division, then rounds down (towards negative infinity) to the nearest integer.
Here are some examples to help you out. Pay attention to the last one especially.
10 // 2 # Returns 5 since 10/2 = 5, rounded down is 5
2 // 2 # Returns 1 since 2/2 = 1, rounded down is 1
11 // 2 # Returns 5 since 11/2 = 5.5, rounded down is 5
4 // 10 # Returns 0 since 4/10 = 0.4, rounded down is 0
(-4) // 10 # Returns -1 since (-4)/10 = -0.4, rounded down is -1
For nonnegative numerator n, n // d can be seen as the number of times d fits into n whole.
So for a number like n = 1042, n // 10 would give you how many whole times 10 fits into 1042.
This is 104 (since 1042/10 = 104.2, and rounded down we have 104).
Notice how we've effectively knocked off a digit?
Let's have a look at your while loop.
while order > 0:
size += 1
order = order // 10
Every time a digit is "knocked off" order, the size counter is incremented, thus counting how many digits you can knock off before you hit your terminating step.
Termination occurs when you knock of the final (single) digit. For example, say you reduced order to 1 (from 1042), then 1 // 10 returns 0.
So once all the digits are "knocked off" and counted, your order will have a value of 0. The while loop will then terminate, and your size counter will be returned.
Hope this helps!
Disclaimer: Perhaps this isn't what you want to hear, but many Universities consider copying code from the Internet and passing it off as your own to be plagiarism.

Categories