convention range value in python - python

i can't understand this convention range in python, range(len(s) -1) for representing all elements including the last one. For me makes no sense like when I print all elements the last one is not included in the list. Someone could help me understand this logic?
this>
s = "abccdeffggh"
for i in range(len(s) -1):
print(i)
result this
0
1
2
3
4
5
6
7
8
9

you are trying to print range to compiler you saying like this print numbers greter than 1 and below than 10 to the output not include 1 and 10 compiler only print 2,3,4,5,6,7,8,9 in your case
s = "abccdeffggh"
this s string length must be 11 if you print like this
s = "abccdeffggh"
for i in range(len(s)):
print(i)
you get output as 1,2,3,4,5,6,7,8,9,10 that is the numbers between 0 and 11
but in your code you have subtract -1 from the length then your range is become -1 and 10 then compiler print all numbers between the -1 and 10 it not include -1 and 10
try this code
s = "abccdeffggh"
print(len(s))
print(len(s)-1)
for i in range(len(s)):
print(i)

Related

I'm learning and tyring to create a for loop

I am trying to create a for loop and I want the output to be this:
0 is even.
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
And all I have gotten this far:
my_range=range(0,11)
for i in my_range:
print(i)
and the output is all the numbers:
0
1
2
3
4
5
6
7
8
9
10
You just need to do is, change your print function as -
print(i," is", 'even.' if (i % 2 == 0) else 'odd.')
What you need to use here is conditional statements along with 'String Interpolation' in python.
The Below code will give you the desired output:
my_range=range(0,11)
for i in my_range:
if i%2:
print("{} is odd".format(i))
else:
print("{} is even".format(i))

What's the cleanest way to print an equally-spaced list in python?

Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.
For example, the below does not work:
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)
Desired output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.
If I have missed a similar SO question, feel free to vote to close.
You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
frmt = "{:>3}"*len(lst)
print(frmt.format(*lst))
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
items=range(10)
''.join(f'{x:3}' for x in items)
' 0 1 2 3 4 5 6 7 8 9'
If none of the other answers work, try this code:
output = ''
space = ''
output += str(list[0])
for spacecount in range(spacing):
space += spacecharacter
for listnum in range(1, len(list)):
output += space
output += str(list[listnum])
print(output)
I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))

Number half Pyramid Python

I'm trying to print a half pyramid that stars on the left side in python.
So far, this is my code
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in range(1, i):
print(j, end = " " )
print("\n")
and my output is
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
However, my output is meant to be in the opposite order:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How can I make this change?
Just reverse the second loop -- the one that prints that actual numbers:
for j in range(i-1, 0, -1):
The last parameter controls the "step", or how much the variable changes on each loop iteration. Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
...
Reverse the range by adding the third argument (-1). Also format your numbers to use 2 places, so 10 is not pushing the last line to the right. Finally, the last print should probably not have \n, since that is already the default ending character of print:
for i in range(1,12):
for j in range(12 - i):
print(" ", end = "")
for j in range(i-1, 0,-1):
print(str(j).rjust(2), end = "" )
print()
You could just reverse the range that you print out as numbers
for i in range(1,12):
for j in range(12 - i):
print(" ", end = " ")
for j in reversed(range(1, i)):
print(j, end = " " )
print("\n")
The problem is in your second for loop, as you are looping from 1 to i, meaning you start off with 1 being printed first, and every following number until (not including) i.
Fortunately, for loops are able to go in reverse. So, instead of:
for j in range(1, i)
You could write:
for j in range((i-1), 0, -1)
Where the first parameter is signifies where the loop starts, the second is where the loop finishes, and the third signifies how large our jumps are going to be, in this case negative. The reason we are starting at i-1 and finishing at 0 is because loops start at exactly the first given number, and loop until just before the second given number, so in your given code the loop stops just before i, and so this one starts just before i as well, although you could remove the -1 if you wish to include 12 in the pyramid.

Python range() giving the wrong list

I am using this little code to generate a weighted modulo-103 checksum.
The problem is that when I run the following code:
def checksum_bar(array):
s = array[0]
s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
I get the following result for x when entering a array of length 10:
1
2
3
4
5
6
7
8
9
10
But when I run the following code (3rd line commented):
def checksum_bar(array):
s = array[0]
#s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
It gives me the result I want, even though I didn't change the iteration:
2
3
4
5
6
7
8
9
10
Am I missing something here? I would like to know if someone can reproduce the same result and some explanation would be very nice too.
The two sets of code provided will give the same result, because the range function is sure to start from 2

Formatting lists

I need to create a function that takes inputs of lists from the user and returns them as such:
>>> print_table([[0,1,2,3,4,5],[0,1,4,9,16,25],[0,1,8,27,64,125]])
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
>>> print_table(times_table(6,6))
0 0 0 0 0 0 0
0 1 2 3 4 5 6
0 2 4 6 8 10 12
0 3 6 9 12 15 18
0 4 8 12 16 20 24
0 5 10 15 20 25 30
0 6 12 18 24 30 36
The times_table refers to my current code:
def times_table(s):
n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(n+1):
s = ''
for col in range(n+1):
s += '{:3} '.format(row * col)
print(s)
Help me if you can....
To get two values as input from the user, i.e. number of columns and rows, you can do as follows:
in_values = input('Please enter two positive integers between 1 and 15, separated by comma (e.g. 2,3): ')
m,n = map(int, in_values.split(','))
print(m,n)
To print out a formatted list of lists, you may wish to consider using string formatting through the format() method of strings. One thing I notice in your upper example is that you only get to 3 digits, and the space between the numbers seems to be unchanging. For lists with large numbers, this will likely mess up the formatting of the table. By using the format() method, you can take this into account and keep your table nicely spaced.
The easiest way I can think of to accomplish this is to determine what is the single largest number (most digits) in the entire list of lists and then incorporate that in the formatting. I would recommend you read up on string formatting for the python type string (including the mini formatting language).
Assuming s is the argument passed in to print_table:
maxchars = len(str(max(max(s))))
This will provide the largest number of characters in a single entry in the list. You can then utilize this number in the formatting of the rows in a for loop:
for lst in l:
output = ""
for i in lst:
output += "{0:<{1}} ".format(i, maxchars)
print(output)
the line output += "{0:<{1}} ".format(i, maxchars) means to print the number ({0} maps to the i in the call to format) left adjusted (<) in a space of characters "maxchars" wide ({1} maps to maxchars in the call to format).
So given your list of lists above, it will print it as:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
but if the numbers are much larger (or any of the numbers are much larger, such as the 125 being replaced with 125125, it will unfortunately look like this because it is padding each item with the appropriate number of character spaces to contain a number of 6 characters:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125125
The above example takes a variable number of characters into account, however you could also format the string using an integer by replacing the {1} with an integer and omitting the maxchars portion (including both setting it and it being passed to format) if that is sufficient.
output += "{0:<4} ".format(i)
Optionally, you could figure out how to determine the largest number in a given column and then just format that column appropriately, however I am not going to put that in this answer.

Categories

Resources