Python Range Step Increasing - python

Is it possible to increase each step in range? Something like this:
for num in range(1, 40, i++) :
print(i)
...
1
2
3
4
...
Or step in range has only fixed size?

Yes, step in range has fixed size.
Something like this gives the output you want.
>>> j=0
>>> for i in xrange(1,40):
j+=i
print j

I think you want an increasing step size with each iteration?
The code below does this
>>> for i in (i+sum(range(i)) for i in (range (1,10))):
... print i
...
1
3
6
10
15
21
28
36
45
>>>

A while loop will result in cleaner code:
step = 1
i = 1
while i < 40:
print i, step
i += step
step +=1
result:
1 1
2 2
4 3
7 4
11 5
16 6
22 7
29 8
37 9

Using For loop
j = 0
for i in range(1,22):
j += i
if j <= 22:
print(j, end=" ")
Output:
1 3 6 10 15 21

Related

How to make a while loop for a multiplication table?

I am trying to create a multiplication chart with a while loop for an assignment but I am having a hard time getting the expected output.
I have tried everything I can think of. I am new to the coding world.
#While loop
print('While Loop')
print()
x = 1
y = 1
z = 1
while x <= 12:
print(x ,end='\t')
x += 1
while y <= 12:
print('\n')
print(y,'\t')
y += 1
while z <= 12:
print(x*z ,end='\t')
z += 1
z = 0
x = 1
I expect the output to be
but I get
.
Short answer: you use x*z when you calculate the product, but you use y as a "row counter" and z as a "column counter" so it should be y*z. Furthermore you should increment the y after the inner while loop.
Since you use y as the "row counter" and z as the "column counter", you should print y * z as the answer of that specific multiplication. Furthermore you increment y too soon: you should increment it after the while loop, and reset z to 1, like:
print('While Loop')
print('x', end='\t') # print a cross
x = 1
while x <= 12:
print(x ,end='\t')
x += 1
y = 1
while y <= 12:
print('')
print(y,end='\t')
z = 1 # reset to 1
while z <= 12:
print(y*z ,end='\t') # use y * z
z += 1
y += 1 # incerement after while loop
print()
Using for loops
There are also some minor formatting issues. For example you should first print('X', end='\t') since otherwise the columns do not match correctly.
That being said, you make things way harder than these should be. You can make use of a for loop instead, like:
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, 13)))
for r in range(1, 13):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, 13)))
or in a function:
def mulgrid(n):
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, n+1)))
for r in range(1, n+1):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, n+1)))
For example:
>>> mulgrid(1)
x 1
1 1
>>> mulgrid(2)
x 1 2
1 1 2
2 2 4
>>> mulgrid(5)
x 1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
>>> mulgrid(7)
x 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

Python: Two Nested Loops

I'm trying to find coding for Python version 3 doing these two things in basic coding (a loop nested inside another loop). I understand the basic premise of:
for i in range(10)
for j in range(10)
but I think it's the "i+___" math that's giving me trouble. I'm having trouble giving me these three types of outputs:
First:
0
0 1
0 1 2
0 1 2 3
Second:
10
11 12
13 14 15
16 17 18 19
Third:
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
Any help would be greatly appreciated.
For python version 3.
First:
for i in range(4):
for j in range(i+1):
print(j, end="")
print()
Second:
x=10
for i in range(1,5):
for j in range(x,i+x):
print(str(j)+" ", end="")
x+=i
print()
Third:
for i in range(3):
print((str(i)+" ")*9)
Third:
j=[]
for i in xrange(0,3):
j.append([i]*9)

write a program that prints a nested loop in Python

I'm trying to print a nested loops that looks like this:
1 2 3 4
5 6 7 8
9 10 11 12
This is what I have so far:
def main11():
for n in range(1,13)
print(n, end=' ')
however, this prints the numbers in one line: 1 2 3 4 5 6 7 8 9 10 11 12
You can do that using string formatting:
for i in range(1,13):
print '{:2}'.format(i),
if i%4==0: print
[OUTPUT]
1 2 3 4
5 6 7 8
9 10 11 12
Modulus Operator (%)
for n in range(1,13):
print(n, end=' ')
if n%4 == 0:
print
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print(n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Or if you want it nicely formatted the way you have in your post:
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print("% 2s"%n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Most of the time when you write a for loop, you should check if this is the right implementation.
From the requirements you have, I would write something like this:
NB_NB_INLINE = 4
MAX_NB = 12
start = 1
while start < MAX_NB:
print( ("{: 3d}" * NB_NB_INLINE).format(*tuple( j+start for j in range(NB_NB_INLINE))) )
start += NB_NB_INLINE

Grouping list of integers in a range into chunks

Given a set or a list (assume its ordered)
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
I want to find out how many numbers appear in a range.
say my range is 10. Then given the list above, I have two sets of 10.
I want the function to return [10,10]
if my range was 15. Then I should get [15,5]
The range will change. Here is what I came up with
myRange = 10
start = 1
current = start
next = current + myRange
count = 0
setTotal = []
for i in myset:
if i >= current and i < next :
count = count + 1
print str(i)+" in "+str(len(setTotal)+1)
else:
current = current + myRange
next = myRange + current
if next >= myset[-1]:
next = myset[-1]
setTotal.append(count)
count = 0
print setTotal
Output
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 8]
notice 11 and 20 where skipped. I also played around with the condition and got wired results.
EDIT: Range defines a range that every value in the range should be counted into one chuck.
think of a range as from current value to currentvalue+range as one chunk.
EDIT:
Wanted output:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 10]
With the right key function, thegroupbymethod in the itertoolsmodule makes doing this fairly simple:
from itertools import groupby
def ranger(values, range_size):
def keyfunc(n):
key = n/(range_size+1) + 1
print '{} in {}'.format(n, key)
return key
return [len(list(g)) for k, g in groupby(values, key=keyfunc)]
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)
You want to use simple division and the remainder; the divmod() function gives you both:
def chunks(lst, size):
count, remainder = divmod(len(lst), size)
return [size] * count + ([remainder] if remainder else [])
To create your desired output, then use the output of chunks():
lst = range(1, 21)
size = 10
start = 0
for count, chunk in enumerate(chunks(lst, size), 1):
for i in lst[start:start + chunk]:
print '{} in {}'.format(i, count)
start += chunk
count is the number of the current chunk (starting at 1; python uses 0-based indexing normally).
This prints:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
20 in 2
If you don't care about what numbers are in a given chunk, you can calculate the size easily:
def chunk_sizes(lst, size):
complete = len(lst) // size # Number of `size`-sized chunks
partial = len(lst) % size # Last chunk
if partial: # Sometimes the last chunk is empty
return [size] * complete + [partial]
else:
return [size] * complete

Categories

Resources