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.
Related
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=' ')
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)
I was writing a Python program which includes printing a array created from user input in the order the user inputed each item of the array. Unfortunately, I have had few problems with that; Once it repeated the first item twice with one of the set, and then in another set it put the last 2 items at the beginning.
I checked the array in the shell and the array contained the right amount of items in the right order, so I don't know what is going on. My script looks something like this:
i = 1
lines = []
for i in range (1, (leng + 1)):
lines.append(input())
input() # The data stripped is not used, the input is a wait for the user to be ready.
i = 0
for i in range (0, (leng + 1)):
print(lines[i - len(lines)])
I searches found me nothing for my purposes (but then again, I could have not used the correct search term like in my last question).
Please answer or find a duplicate if existing. I'd like an answer.
Don't you just want this?
for line in lines:
print(line)
EDIT
As an explanation of what's wrong with your code... you're looping one too many times (leng+1 instead of leng). Then you're using i - len(lines), which should probably be okay but is just the equivalent of i. Another fix for your code could be:
for i in range(len(lines)):
print(lines[i])
SECOND EDIT
Rewriting your full code to what I think is the simplest, most idiomatic version:
# store leng lines
lines = [input() for _ in range(leng)]
# wait for user to be ready
input()
# print all the lines
for line in lines:
print(line)
my_str="ellezagchickenbndodetballigatoraaaolmeznacattleeblrctacfenarcesssadlritfhftrarrssos aoiarefaareppohssarghcerumrheirmmwildfcumeboimltaairfovindalbiglalobehoeasiaxuesabldinbbccrhhrtylrlahsifdlogkrctlaiareogoldfinchefnnddmneepoletnarntadodinosauroxofoeclictnahpelepalgaierhohcaorkcocyatrmoacrflamingoerefafloechateehchdracaribou"
def create_2d_list(N):
output_list=[]
counter=0
for row in range(0,N):
temp=[]
for col in range(0,N):
temp.append(my_str[counter])#you can add a charcter instead of counter
counter=counter+1
output_list.append(temp[:])
return output_list
N=18
x=create_2d_list(N)
for row in range(0,N):
total=0
s="|"
for col in range(0,N):
my_str="{0:2} ".format(x[row][col])
s=s+my_str+"|"
print "-"*(N*4+1)
print s,
print " "
the_valid_words=open("E:/asd/words.txt","r").readlines()
def looking_word_left_to_right(the_list):
for any_words in the_valid_words:
for every in x[0]:
the_first_index=x[0].index(every)
for every in range(the_first_index,(the_first_index)+7):
c=str(every)
the_join=" ".join(c)
if the_join==the_valid_words:
word.upper().replace(every,x[0].upper(every))
return x[0]
print looking_word_left_to_right(x)
every time i run the program, the looking_word_left_to_right doesn't print anything
P.S its similar to small crossword for beginners, Capitalizing the letters that make a word and removing every other letter without changing places, if someone could give like thoughts on how to proceed that would be great. i have certain valid words to look for.
and i'm a newbie so go easy on me :)
appreciate the help.
There seem to be a number of problems.
Why are you operating on x when you also pass it in as the_list" Just use the_list.
You're only looking at the first line of x and never moving beyond that.
It looks like you're putting a space between every character before you compare. If c = "abcdefg" then " ".join(c) will give you "a b c d e f g". If your the_valid_words doesn't have spaces in it, then if the_join==the_valid_words will always evaluate to false.
You're comparing to the_valid_words, which is your entire list. You should probably be comparing to EACH valid word using any_word... which you aren't using anywhere else.
You may also be running into a problem with iterating over x, while you're changing it (it will sometimes invalidate the iterator... but sometimes not). I.e. if you're iterating through x and then you change x before you're done iterating, then Python might not know where the iterator belongs in the new version of x. Since the_list is the same as x anyway, it might be better to do for every in the_list: and then change x to your heart's content.
It looks like you may not quite understand how for loops work in Python. Take a look at those, and that may help some.
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