Printing 5 numbers in a row - python

I have to write a program to print the numbers 1 to 50, but with 5 numbers in a row, like:
1,2,3,4,5
6,7,8,9,10
like that till 50 without using lists
for i in range(2,51):
if i%5==0:
print i
this is giving me 5,10,15,20
Please help me

A few hints:
The first parameter for the range() function is incorrect. It must be 1 not 2. The start index included, the ending one is excluded. This is btw a very good practice to avoid bugs.
With the modulo operator you found a way of detecting every 5 values; you could use this to print a line when that happens. You then would be left with having to find a way to not output a line when you output one value at at time; look in the python documentation for way to make the print() function do this. (attention, things have changed in the area of print with Python 3.0, but you seem to be using a 2.x version given your example)
An alternative approach is to use the 3rd argument of the range() function, to step though the sequence, in increments of 5). Such a range would give you 1, 6, 11, 16 etc. in sequence, and you can use this number as the first of each line, and simple addition for the following ones.

You can start almost like you did (except you need to start from 1 - that 2 is really weird!-):
for i in range(1,51):
if i % 5 == 0:
print i
but then you need to segue into an else clause for that if, because you do want to print something even when i is not a multiple of 5 -- just something different from the simple print i you're already doing when i is a multiple of 5...:
else:
print i, ',',
As other answers already said, the trailing comma means "no newline yet"!-) ((It's plainer and more sensible in Python 3.whatever, but you're clearly using Python 2.something, and in those versions this is what you need to do)).

I've never used Python, but this should be close if not right.
for i in range(1,51):
print i;
print ",";
if (i%5==0)
{ print "\n";}

Also, remember that using print will cause a new line to start. Unless as noted above a comma is used afterwards.
You can collect values using a string for printing out later.

Some Hints
To print 1 to 50, you need to pass n+1 for eg, 1 to 51 in range function, its (i=1;i<51,i++) in C alike syntax
print comma if you want between every digits
to print line break for every 5, you can just use current if i%5==0: but print blank line, instead of i
To concatenate num + string "," you can use `i` or str(i) , you can do like `i` +","
If you dont need comma in the end, you could do like i%5 print "," else print "\n" =>
(i%5 and "," or "\n")
print i will print i line by line, and print i, will print in the same line
just my 2 cents

for i in range(1,51):
if i%5 == 0:
print i
else:
print i, ",",

(there used to be python code here)
EDIT: My apologies, didn't realize this was homework. I reeeally need to check tags before answering. Here's an explanation of what needs to happen.
Obviously you know that you're trying to output consecutive numbers from 1 to 50, so you'll need a counter. You've figured out that it'll require a range() call, but it needs to be from 1 to 51, not from 2 to 50.
The reason the range() call needs to be from 1 to 51 is this: it will start the variable i at 1, then check to see if it has reached its goal (51) before looping. If the goal is reached (meaning if i == 51) it will quit the loop without executing the loop's code. So rather than go from 1 to 50, you go from 1 to 51 so that we don't skip the 50th iteration.
Next, you're going to want to have the numbers appear on-screen. But using python's print command prints each number on a new line! That's obviously not what you want. So you're going to have to create a buffer string to append each number to until you're ready to print the line. You can call it 'output' or whatever.
Personally, I like to clear the buffer BEFORE the for loop just to be sure no residual memory traces find their way into the output. Call me paranoid. So I write output = "" on a line before the loop.
Now you've got a buffer string, all you need to do is follow a logical flow:
Add i to the buffer output.
If i is a multiple of 5, print the buffer output and reset it back to an empty string. (We do this so that we can start the buffer for the next line.)
If i is NOT a multiple of 5, add a comma to the output buffer, so that the next number added will be after the comma.
Continue our loop.
These steps should be pretty simple to figure out. Step 2 you've already seen before... To check if a number is a multiple of another number, simply use %. If A % B == 0 then A is a multiple of B.
This should be a pretty straightforward explanation for how to solve this problem. Hope it helps.
And sorry for ruining your learning experience by posting the answer! Now you'll understand why the answer works.

for i in range(1,51):
if i%5 != 0:
print str(i)+',' , # trailing comma means no \n
else:
print i

this code will give you the required output.
#python
for i in range(1,51):
if i%5 == 0:
print (i)#this will give \n at the end
else:
print (i,end=",")#this will print the numbers with coma at the end
you can put 'end="" ' to print without a space
for space 'end=" "'

In one statement, you can unpack a generator expression withing print and utilise the sep argument. The benefit of this solution is there's no need for explicit if / else conditional logic.
k, n = 5, 50
print(*(','.join(map(str, range(i, i+k))) for i in range(1, n+1, k)), sep='\n')
# 1,2,3,4,5
# 6,7,8,9,10
# 11,12,13,14,15
# 16,17,18,19,20
# 21,22,23,24,25
# 26,27,28,29,30
# 31,32,33,34,35
# 36,37,38,39,40
# 41,42,43,44,45
# 46,47,48,49,50

Related

Python: Display all even numbers between two integers inclusive, with a limit the number of times the code accepts input

Link to question: https://www.spoj.com/UTPEST22/problems/UTP_Q2/
From what I understand, the question is divided into 2 parts:
Input
The first input is an integer that limits the number of time the user can provide a set of integers.
From the second line onwards, the user provides the sequence of integers up until the specified limit.
The set of integers are arranged in ascending order, separated only by a space each.
Output
For each sequence of integers, the integers in it are looped over. Only those that are even are printed as outputs horizontally.
from sys import stdin
for x in range(1, 1+ int(input())):
# number of cases, number of times the user is allowed to provide input
for line in stdin:
num_list = line.split()
# remove the space in between the integers
num = [eval(i) for i in num_list]
# change the list of numbers into integers each
for numbers in range(num[0], num[-1] + 1):
# the first integer is the lower bound
# the second the upper bound
if numbers % 2 == 0:
# modulo operation to check whether are the integers fully divisible
print(numbers, end = ' ')
# print only the even numbers, horizantally
Can anyone please provide some insights on how to make changes to my code, specifically the loop. I felt so messed up with it. Screenshot of the result.
Any help will be appreciated.
You can use restructure the code into the following steps:
Read each case. You can use the input function here. A list comprehension can be used to read each line, split it into the lower and upper bound and then convert these to integers.
Process each case. Use the lower and upper bounds to display the even numbers in that range.
Using loops: Here is an example solution that is similar to your attempt:
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
for val in range(case[0], case[1] + 1):
if val % 2 == 0:
print(val, end=' ')
print()
This will produce the following desired output:
4 6 8 10 12 14 16 18 20
2 4 6 8 10 12 14 16
-4 -2 0 2 4 6
100 102 104 106 108
Simplify using unpacking: You can simplify this further by unpacking range. You can learn more about unpacking here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
lower = case[0] if case[0] % 2 == 0 else case[0]
print(*range(lower, case[1] + 1, 2))
Simplify using bit-wise operators: You can simplify this further using the bit-wise & operator. You can learn more about this operator here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
print(*range(case[0] + (case[0] & 1), case[1] + 1, 2))
So first of obviously ask user to input the range however many times they specified, you can just split the input and then just get the first and second item of that list that split will return, by using tuple unpacking, then append to the ranges list the range user inputted but as a Python range object so that you can later easier iterate over it.
After everything's inputted, iterate over that ranges list and then over each range and only print out the even numbers, then call print again to move to a new line in console and done.
ranges = []
for _ in range(int(input())):
start, end = input().split()
ranges.append(range(int(start), int(end) + 1))
for r in ranges:
for number in r:
if number % 2 == 0:
print(number, end="")
print()
Here's my solution:
n = int(input())
my_list = []
for i in range(n):
new_line = input().split()
new_line = [int(x) for x in new_line]
my_list.append(new_line)
for i in my_list:
new_string = ""
for j in range(i[0], i[1]+1):
if (not(j % 2)): new_string += f"{j} "
print(new_string)
Read the first value from stdin using input(). Convert to an integer and create a for loop based on that value.
Read a line from stdin using input(). Assumption is that there will be two whitespace delimited tokens per line each of which represents an integer.
Which gives us:
N = int(input()) # number of inputs
for _ in range(N):
line = input()
lo, hi = map(int, line.split())
print(*range(lo+(lo&1), hi+1, 2))
There are a few issues here but I'm guessing this is what's happening: you run the code, you enter the first two lines of input (4, followed by 3 20) and the code doesn't print anything so you press Enter again and then you get the results printed, but you also get the error.
Here is what's actually happening:
You enter the input and the program prints everything as you expect but, you can't see it. Because for some reason when you use sys.stdin then print without a new line, stdout does not flush. I found this similar issue with this (Doing print("Enter text: ", end="") sys.stdin.readline() does not work properly in Python-3).
Then when you hit Enter again, you're basically sending your program a new input line which contains nothing (equivalent to string of ""). Then you try to split that string which is fine (it will just give you an empty list) and then try to get the first element of that list by calling num[0] but there are no elements in the list so it raises the error you see.
So you can fix that issue by changing your print statement to print(numbers, end = ' ', flush=True). This will force Python to show you what you have printed in terminal. If you still try to Enter and send more empty lines, however, you will still get the same error. You can fix that by putting an if inside your for loop and check if line == "" then do nothing.
There is still an issue with your program though. You are not printing new lines after each line of output. You print all of the numbers then you should go to the newline and print the answer for the next line of input. That can be fixed by putting a print() outside the for loop for numbers in range(num[0], num[-1] + 1):.
That brings us to the more important part of this answer: how could you have figured this out by yourself? Here's how:
Put logs in your code. This is especially important when solving this type of problems on SPOJ, Codeforces, etc. So when your program is doing that weird thing, the first thing you should do is to print your variables before the line of the error to see what their value is. That would probably give you a clue. Equally important: when your program didn't show you your output and you pressed Enter again out of confusion, you should've gotten curious about why it didn't print it. Because according to your program logic it should have; so there already was a problem there.
And finally some side notes:
I wouldn't use eval like that. What you want there is int not eval and it's just by accident that it's working in the same way.
We usually put comments above the line not below.
Since it appears you're doing competitive programming, I would suggest using input() and print() instead of stdin and stdout to avoid the confusions like this one.
SPOJ and other competitive programming websites read your stdout completely independent of the output. That means, if you forget to put that empty print() statement and don't print new lines, your program would look fine in your terminal because you would press Enter before giving the next input line but in reality, you are sending the new line to the stdin and SPOJ will only read stdout section, which does not have a new line. I would suggest actually submitting this code without the new line to see what I mean, then add the new line.
In my opinion, the variable numbers does not have a good name in your code. numbers imply a list of values but it's only holding one number.
Your first if does not need to start from 1 and go to the number does it? It only needs to iterate that many times so you may as well save yourself some code and write range(int(input())).
In the same for loop, you don't really care about the value of variable x - it's just a counter. A standard practice in these situations is that you put _ as your variable. That will imply that the value of this variable doesn't really matter, it's just a counter. So it would look like this: for _ in range(int(input())).
I know some of these are really extra to what you asked for, but I figured you're learning programming and trying to compete in contests so thought give some more suggestions. I hope it helped.
Steps for simple solution
# taking input (number of rows) inside outer loop
# l = lower limit, u = upper limit, taking from user, then converting into integer using map function
# applying logic for even number
# finally printing the even number in single line
for j in range(int(input())):
l, u = map(int, input('lower limit , upper limit').split())
for i in range(l, u+1):
if i%2 == 0: # logic for even number
print(i, end=' ')

Print prints one space too much

I was currently finishing up my project that concerned ciphering a sentence using a key matrix.
As of now, all the calculations are done and correct, the only thing left is for me to print the output to the screen and voila.
What you can see above is my current output.
The Key matrix is printed just how I want it to be printed and all is good with Encrypted message as well, except that my print prints one space more than what is needed. This is quite problematic because of the fact that the project is going to be verified with a bot, so even though it changes nothing on the screen (except when piping into cat -e) the bot is still going to pick it up.
My print function looks like the following:
def the_output_printer(key_matrix, encrypted_matrix, matrix_size):
length = (len(sys.argv[1]));
if (length == 0):
exit(84);
lines = round(length / matrix_size, 0);
if (length % matrix_size != 0):
lines += 1
lines = int(lines);
print("Key matrix:");
for line_index_key in range(0, matrix_size):
for col_index_key in range(0, matrix_size):
if (col_index_key != matrix_size - 1):
print("{}".format(key_matrix[line_index_key][col_index_key]), end="\t");
if (col_index_key == matrix_size - 1):
print("{}".format(key_matrix[line_index_key][col_index_key]), end="\n");
print("\n", end="");
print("Encrypted message:")
for line_index in range(0, lines):
for col_index in range(0, matrix_size):
print("{}".format(encrypted_matrix[line_index][col_index]), end=" ");
print();
I tried something simillar to what I've done for Key Matrix but it didn't really work out.
Any ideas as how to not print that last " "?
Thank you all for reading!
As I'm still new to python please excuse my horrible coding style, I'm still working on it.
Your problem is that each iteration of your nested for loop prints your end argument, one space. That's fine assuming you want one between all elements, but it doesn't know to skip it on the last iteration of the nested loop.
There's more than one way to solve this, but because you mentioned being new to Python I'll stick to a simple one - instead of printing each number, collect up the numbers in a single list and then pass that list to print(). print() defaults to adding a separator between its arguments but not after the final one.
message_elements = []
for line_index in range(0, lines):
for col_index in range(0, matrix_size):
message_elements.add("{}".format(encrypted_matrix[line_index][col_index]))
print(*message_elements)
The * operator in the final print() unpacks the list, as if you'd specified each of its elements as an argument to print(). It's equivalent to:
print(message_elements[0], message_elements[1], ...)
Once you're more experienced with Python there are ways to more concisely collect up the matrix elements into a list, or to avoid an intermediate list at all and use a single expression to do it. But this should work and changes as little as I can from your existing code.
Alright, I figured it out :)!
The problem was that as I'm still new to Python, I once again messed up how
range() functioned.
My previous attempt at fixing this resembled:
if (line_index == lines and col_index == matrix_size):
print("{}".format(encrypted_matrix[line_index][col_index]));
else:
print("{}".format(encrypted_matrix[line_index][col_index]), end=" ");
I ommited the fact that while using
in range(foo)
the value stops at foo - 1, or quite simply while it is strictly inferior to foo.
The fix was quite simply to add -1 to my if statement, EXACTLY the same thing I forgot when i was doing my key_matrix printing part. The fixed part of the function now looks lice this:
if (line_index == lines - 1 and col_index == matrix_size - 1):
print("{}".format(encrypted_matrix[line_index][col_index]));
else:
print("{}".format(encrypted_matrix[line_index][col_index]), end=" ");
Which gives me the correct output :). Thank you everyone but I figured it out after re-reading the code few times.

Am I using a Python loop wrongly or am I just missing something?

I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)

How to print values in a list on separate lines? Must use a for statement.

I need to use a for statement in order to print each value of a list on separate lines. When using the for statement it prints the entire list on one line. Additionally when trying to print just the values in the list on the same line it appears with double brackets instead of single.
Numbers=range(5,25,4)
NumberSequence=[]
NumberSequence.append(Numbers)
print NumberSequence
for elem in NumberSequence:
print elem
NumberSequence2=[]
Numbers2=range(26,0,-7)
NumberSequence2.append(Numbers2)
print NumberSequence2
for digits in NumberSequence2:
print digits
That is because you made a list and then put it inside of another list. If I understand you correctly, you want to print each individual number on a separate line. This can be done with:
Numbers = range(5,24,4)
for elem in Numbers:
print elem
Also, as #roganjosh mentioned, you seem to be using Python 2 which is rather old, slower than Python 3, and it's days of being supported are numbered. I highly recommend you make the switch to python 3 :)

Iterating over a string in Python

I want to make a script which will type string letters one by one
def autotype(info):
count = len(info) #Countign number of letters of the string
splitlist = list(info)
i = int(count) #getting an error on this line! it accept i=int(0) but my loop doesnt work because of this
while i>0:
sys.stdout.write(splitlist[i])
time.sleep(0.2)
i -= 1
info = str("hello world")
autotype(info)
the error is: list index out of range
how do i fix it?
The length of a list is the number of elements in a list. But, lists start at index 0, and so they will end at index length - 1. So, to fix your code as is, it should be i = count - 1. (You don't need to cast it to an int, it's already one.)
Better yet, rather than iterating using a counter in a while loop, just use a for loop. You can use the for loop to iterate over the characters in a string.
for ch in info:
sys.stdout.write(ch)
sys.stdout.flush() # as mawimawi suggests, if you don't do this, it will
# actually just come out all on one line at once.
time.sleep(0.2)
You also don't need to cast "hello world" to a string - it's already one.
Your script is quite un-pythonic. Here is something that would do the same. Strings are iterables, so:
def autotype(info):
for x in info:
sys.stdout.write(x)
sys.stdout.flush() # you need this, because otherwise its' buffered!
time.sleep(0.2)
That's all you need.
You're starting your loop at i=len(info), which is one more than the final index in the string. The last index in a string (or other iterable) is len(string) - 1, because indices begin at 0.
Note that in Python, you can (and are encouraged to) make use of the natural language constructs and the fact that collections are easy to iterate over:
for letter in reversed(info): # Much clearer way to go backwards through a string
sys.stdout.write(letter)
Since you've clarified in your comments that you actually want to go forwards through the text, you can just take out the reversed bit. The code as you posted will iterate backwards through the text, not forwards -- another benefit to using the standard iteration techniques is that it's much easier to see if you've done something you didn't mean to do!
for letter in info: # Very clear that you're going forward through the string
sys.stdout.write(letter)
Finally, as others have mentioned, you should add an explicit call to sys.stdout.flush() after every write, because otherwise there's no guarantee that you'll see output at regular intervals (it could be written to the buffer but not flushed to the screen until much later).
Lists are zero-indexed, so the last element is at len(info)-1.
To fix this, you need to subtract 1 from the count:
i = int(count) - 1
Indexes are counted from zero... if you have 5 items in a list, then indexes are 0,1,2,3,4
you are setting index out of bounds in this line:
i = int(count)
If count is 5 then max index is 4.
To fix this change that line into:
i = int(count) - 1
Next thing, you won't print the first character.
to fix that change a line:
while i>0:
into:
while i>=0:
By the way all your characters are printed backwards.
Unidiomatically, but concisely:
import time
import sys
autotype = lambda instr:map((lambda ch:(sys.stdout.write(ch), time.sleep(0.2))), instr)
autotype("hello world")
The main problem with the above code is that it's not usual to sequence two functions using tuple if you don't care for their return values.
Here is code to "make a script which will type string letters one by one"
print info
If what you need is to type letters in a string consecutively, there is no need to reinvent the wheel.
More than likely, your question was underspecified.

Categories