We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
n, m = map(int,input().split())
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
The first is that each line has a set number of repetitions of '.|.', which are centered, and the rest is filled by '-'.
The second is that the flag is symmetrical, so if you have the top, you have the bottom by reversing it. You only need to work on n // 2 (n is odd and you need the integer div because the remaining line is the "WELCOME" line).
line 2: I generate 2\*i + 1'.|.', center it, and fill the rest with '-'. That's basically the top part of the output.
line 3: put things together. '\n'.join() should be straightforward. Then, the sequence of strings to join is the pattern described above, the middle 'WELCOME' line, and the pattern reversed.
When I used the list comp method shown above, my output resulted in a list of each line printed on a single line. How did you print out each element of the list comprehension on different lines?
dude, [: : -1], the last -1 values show the step size and being -1 this shows that this will work in reverse. As ursan eplained he did the job only for top half and repeated the same work for second half but in reverse
New to python, so why does the '\' character give you multiplication? Would it have been okay to write it as you did instead (e.g. 2*i + 1 rather than 2\i + 1)?
It's actually "2 * i + 1".
"\" is used as an escape character. Like for example "\n" is to be interpreted as linefeed and not just the character n. Here, the backslash is used to be safe; it's not necessary.
it is better you run the for loop as range(1,n,2).
a,b = map(int,(input().split()))
list = []
for i in range(1,a,2):
list.append(('.|.'*i).center(b,'-'))
print(*list,sep='\n')
print('WELCOME'.center(b,'-'))
print(*list[::-1],sep='\n')
very short but you need some serious python knowledge to grok it. for a beginner question I'd expect to see something a bit more readable. Nice work thou all the same.
I would only offer one alternative.
Instead of
pattern[::-1]
consider
list(reversed(pattern))
Yes it is more verbose, but the intent is clearer. Particularly for developers who have to refactor (or at least understand) that code who also have to work in many languages and don't always catch nuances of each one.
In data science, particular at companies that favor open source or very large companies with many "standard" products, a data scientist could be using a half dozen languages or more, so in that case "obvious" wins over "specialty".
That being said, I usually prefer shorter code, so I can easily appreciate arguments for staying with [::-1].
The above solution by @ursan is both witty and hard to read.
Although longer, this one below is easier to chew (if someone can make this cleaner by substituting the list comprehension with something else that generates the value on demand, that would be fantastic; I'm gonna look into it later):
defgetVals():height,width=map(int,input().split())asserth%2==1#makesurethenumbersareoddassertw==h*3#makesurethewidthis3timestheheightreturnheight,widthdefdesignMat(design,message):h,w=getVals()# Top pattern=[iforiinrange(1,h,2)]foriinpattern:yield'{}'.format(str(design*i)).center(w,'-')# Middleyield'{}'.format(message).center(w,'-')# Bottom pattern=list(reversed(pattern))foriinpattern:yield'{}'.format(str(design*i)).center(w,'-')forlineindesignMat('.|.','WELCOME'):print(line)
Just to add on top of the code to explain:
Logic:
for loop on the Half the Number of lines, and with Integer division(//)
Which makes the loop to crete top portion of the MAT
For each line we have ODD number of ".|." patterns, so the code (2*i + 1) to make the ".|." created for so many number of times
Then this pattern we will CENTER it with a MAX char width of m and filler char of "-", so the code center(m,"-")
Then for the Welcome line, we print WELCOME with "m" chars at center with fill_char
For the bottom part of the MAT, we reverse the pattern LIST created
finally we join all three LISTS and print with "\n" seprated
I have tried the same code but it is giving error:
Traceback (most recent call last):
File "solution.py", line 1, in
a=[int(i) for i in input().split(" ")]
File "", line 1
7 21
^
SyntaxError: unexpected EOF while parsing.
Why?
the format of input is such that both n and m are seperated by spaces and are in one line. When we use n=int(input()) it takes both the inputs say, "a b" as a string and then tries to convert it into integer.. which is invalid because u cannot have an integer as:- 3 4 .
Therefore we need to use split function so that the inputs in one line are treated as two different inputs seperated by space and then can be assigned to two variables n,m.
split function allows u to break a string into multiple strings based on the specified seperator. by default the seperator is space. now the result that comes after spliting is a list of items and to iterate through the list of items we use map function.
the format of input is such that both n and m are seperated by spaces and are in one line. When we use n=int(input()) it takes both the inputs say, "a b" as a string and then tries to convert it into integer.. which is invalid because u cannot have an integer as:- 3 4 .
Therefore we need to use split function so that the inputs in one line are treated as two different inputs seperated by space and then can be assigned to two variables n,m.
because of the input sequence
...... if u r giving input by press enter then ur formate is true but in this case hackerank giving its input by pressing space thats why
generally map() returns a map object, you can check it by type(map()) , but when map is used with tuple assignment(values on the left) it returns objects. main function of map is to map function with objects and they are being returned to n,m.
@ursan the third line amazed me, i was thinking how to generate the pattern incrementally odd number of times till max value and decrease it afterwards. you are awesome bro. keep going and thanks for sharing.
N, M = map(int,input().split())
for i in range(1,N,2):
print(('.|.'*i).center(M,'-'))
print('Welcome'.center(M,'-'))
for i in range(N-2,0,-2):
print(('.|.'*i).center(M,'-'))
Then I used list comprehension and my second solution was:
N, M = map(int,input().split())
pattern = [('.|.'*i).center(M,'-') for i in range(1,N,2)]
print('\n'.join(pattern),'\n'+'WELCOME'.center(M,'-'),'\n'+'\n'.join(pattern[::-1]))
Almost identical to your solution but the print was a mess. I saw your comment here and stole that print statement (I don't know why I didn't think of creating one big list then using join to print it effectively, but I have learnt now.)
However this is a typical example of why I do not like python coding and the now so called "pythonic" way
(strangely hackerrank does explicitly favor that kind of syntax though)
if you read that a year from now, or if someone else reads this without context you ll have a very hard time to understand even what it does, or how to modify it.
=> this is one time throw away kind of code that can t really be maintained
there is a difference between "short" and "understandable"
this code is "short" but not "understandable"
i have done the same thing which u have done but its showing error EOF while parsing
n, m = map(int,input().split())
this i have written to take input
can u suggest me how could i fix it
Traceback (most recent call last):
File "Solution.py", line 3, in
n, m = int,input().split("")
File "", line 1
7 21
^
SyntaxError: unexpected EOF while parsing
I hate how simple solutions can be. I way overthink these problems and end up with way too many lines. How do I train myself to see the solution like this
For those of you just learning Python ....if you become a professional don't write code like this. Yes, it is super short and...yes, it is very, very clever.
But...it is also incomprehensible and difficult to maintain if it were production code. Imagine you needed to modify this to draw a circle pattern instead of a diamond? I often have to scrap short, clever code written like this by another developer because it can't be easily modified, and 10 of 10 of your co-workers will appreciate code they can understand easily and quickly.
N, M = map(int, input().split(" "))
h='.|.'
for i in range(N//2):
print((h*i).rjust((M//2)-1,'-')+h+(h*i).ljust((M//2)-1,'-'))
p='WELCOME'
print(p.center(M,'-'))
for i in range((N//2)-1,-1,-1):
print((h*i).rjust((M//2)-1,'-')+h+(h*i).ljust((M//2)-1,'-'))
n, m = map(int,input().split())
pattern=[str(".|."*(i*2+1)).center(m,"-") for i in range(n)]
print(*pattern,sep="\n")
print("WELCOME".center(m,"-"))
pattern.reverse()
print(*pattern,sep="\n")
Designer Door Mat
You are viewing a single comment's thread. Return to all comments →
3 lines:
hey could you explain?
line 1: srtaightforward.
There are a couple things to notice.
The first is that each line has a set number of repetitions of '.|.', which are centered, and the rest is filled by '-'.
The second is that the flag is symmetrical, so if you have the top, you have the bottom by reversing it. You only need to work on n // 2 (n is odd and you need the integer div because the remaining line is the "WELCOME" line).
line 2: I generate
2\*i + 1
'.|.', center it, and fill the rest with '-'. That's basically the top part of the output.line 3: put things together.
'\n'.join()
should be straightforward. Then, the sequence of strings to join is the pattern described above, the middle 'WELCOME' line, and the pattern reversed.Hope that helps!
[ : :-1] how this works
str = 'abc'
print(str[::-1])
--> 'cba'
arr = ['a', 'b', 'c']
print(arr[::-1])
--> ['c', 'b', 'a']
here is solution of problem Designer door mat in python 2 and python 3 https://solution.programmingoneonone.com/2020/06/hackerrank-python-designer-door-mat-problem-solution.html
Beautifully explained.
Best easy to understand solution is here.
Hackerrank - Designer Door Mat Solution
When I used the list comp method shown above, my output resulted in a list of each line printed on a single line. How did you print out each element of the list comprehension on different lines?
That happens at "\n".join, where each line is joined with a newline added in between.
okay okay but your output is wrong acc to que but your logic is awesome :>)
clean explanation , thanks
It's Used for reversing the string
it produces the reversed list
This reverse the string
The slice statement means start at list length, end at position 0, move with the step -1 (or one step backward).
[::-1] is used for reversing a string or list
its been 3 years u may already know this answer. [::-1] will reverse any iterators such as strings, lists, tuples.
Iterate the pattern list backwards
That is used to reverse a list, so index 0 becomes index -1, 1 becomes -2, so on and so forth
Hi,
This notation means, a list is printed in reverse order.
So if we can store first half of the data to be printed in a list like:
then we can print the list in reverse order using that notation.
Hope it is clear now..
It's slice notation - tells Python to begin at end of string and move backward toward the beginning in steps of -1.
https://www.w3schools.com/python/python_howto_reverse_string.asp
it reverses the array
this will revers the elements of the list
-1 is the position of the last element.and :: stands for first or initial element.so ::-1 stands for starting from the last element to the first
its a short trick for reverseing a string
prints the list in backwards like a = [1,2,3,4] print(a[::-1]) will print [4,3,2,1]
it will return a reverse string starting from 0 to len(string)-1 and as per the 3rd argument -1 thats why its starts from backward
this will return the list in reverse order.
iterates backwards
A wonderfully elegant solution. Thanks for sharing.
why have you written pattern in square brackets than closed brackets?
List comprehension
dude, [: : -1], the last -1 values show the step size and being -1 this shows that this will work in reverse. As ursan eplained he did the job only for top half and repeated the same work for second half but in reverse
Pattern is a list
Here we want pattern to be a "list" so that we can use slicing (pattern[::-1]) afterwards. Hence, the square brackets.
i think that is list comprehension...
It's called indexing
['WELCOME'.center(m, '-')] this is a list 'WELCOME'.center(m, '-') this is a string
How does this work?
its just logic based, 2*i + 1 gives the pattern of 1,3,5,7 for the values of i(0,1,2,3)
New to python, so why does the '\' character give you multiplication? Would it have been okay to write it as you did instead (e.g. 2*i + 1 rather than 2\i + 1)?
It's actually "2 * i + 1". "\" is used as an escape character. Like for example "\n" is to be interpreted as linefeed and not just the character n. Here, the backslash is used to be safe; it's not necessary.
it is better you run the for loop as range(1,n,2).
a,b = map(int,(input().split())) list = [] for i in range(1,a,2): list.append(('.|.'*i).center(b,'-')) print(*list,sep='\n') print('WELCOME'.center(b,'-')) print(*list[::-1],sep='\n')
Thanks for the explanation
WOW. Boy, the brevity of the explanation is refreshing. Thanks bud.
why (2i + 1)
thanks for explaining .
What is 2*i+1? and how does it work?
awesome :)
Thanks a lot bro <3<3<3<3
thank you so much sir :)))
Best easy to understand solution is here.
Hackerrank - Designer Door Mat Solution
Thank you sir really great
nice biro
Thank you !
here is python problem solution https://programs.programmingoneonone.com/2021/01/hackerrank-designer-door-mat-solution-python.html
Updated solution is here
https://www.thecscience.com/2021/06/HackerRank-designer-door-mat-in-python-problem-solution.html
Easy solution -- https://codecracksol.blogspot.com/2022/03/designer-door-mat.html
That's too short, really amazing
Easy solution -- https://codecracksol.blogspot.com/2022/03/designer-door-mat.html
Best easy to understand solution is here. Hackerrank - Designer Door Mat Solution
your code code is my love!
n, m = map(int,input().split())
please explain
This is an astonishing code!
Monster :)))
utmost geniouslysnesslyfull. Hats off.
you are something,man..!! this piece of code is a real artwork!
smart with the pattern[::-1], lol
in (2*i + 1) .....how does 2 occur?
The first line has one '.|.' pattern. The second has 3 and so on.
It's the formula for odd number i.e (2*n+1). In each line odd number of ".|." patterns have been occuring.
good, very pythonic
very short but you need some serious python knowledge to grok it. for a beginner question I'd expect to see something a bit more readable. Nice work thou all the same.
absolutely agree, here is my beginner friendly solution
N,M = input().split() N = int(N) M = int(M) design1 = "-" design2 = ".|." design3 = "WELCOME" line = [] def print_sy(strt , range_, stp): for i in range(strt,range_,stp): line.append(((M-(2*i+1)*3)//2)*design1 + (2*i+1)*design2 + ((M-(2*i+1)*3)//2)*design1) print(line[i])
print_sy(0,(N-1)//2,1) print((M-7)//2 *design1 +design3 + (M-7)//2 *design1) print_sy((N-2)//2,-1,-1)
it dosen't work
fantastic Solution..!!! Well done buddy..!!!
Beautiful piece of code @ursan
nice
nice code,man!I like it.
what do you have to import in order to run that code in Python 2? do you know?
Beautifully simple and elegant!
ursan,
Dude, your code blew me away.
Cheers
nice
why we have not user raw_input here to take input for n and m
input is allowed in python
Python 2.x is
raw_input
, Python 3.x isinput
. They are the same command to accept "input."I tried some code its isnt working, althogh being right. Hemce i tried this one still 5 testcases are failed. Can you help?
Please post the code that is failing.
god damn! this is beautiful <3
I would only offer one alternative. Instead of pattern[::-1] consider list(reversed(pattern))
Yes it is more verbose, but the intent is clearer. Particularly for developers who have to refactor (or at least understand) that code who also have to work in many languages and don't always catch nuances of each one.
In data science, particular at companies that favor open source or very large companies with many "standard" products, a data scientist could be using a half dozen languages or more, so in that case "obvious" wins over "specialty".
That being said, I usually prefer shorter code, so I can easily appreciate arguments for staying with [::-1].
very good ty
nice code
this is my code which is printing wrong output . can u explain the difference between your code and mine?
you should try
2*i+1
g must vary as i increase.
n,m=map(int,(input().split()))
h=n//2
for i in range(h): print(('.|.'*(2*n+1)).center(m,'-'),"\n")
print("WELCOME".center(m,'-'),"\n")
for i in range(h,0,-1): print(('.|.'*(2*n+1)).center(m,'-'),"\n")
could you explain why this code would give wrong output?
@vidyaV i think you should use 2*i+1
n,m=map(int,(input().split()))
h=n//2
for i in range(h): print(('.|.'*(2*i+1)).center(m,'-'))
print("WELCOME".center(m,'-'))
for i in range(h,0,-1): print(('.|.'(2(i-1)+1)).center(m,'-'))
The above solution by @ursan is both witty and hard to read.
Although longer, this one below is easier to chew (if someone can make this cleaner by substituting the list comprehension with something else that generates the value on demand, that would be fantastic; I'm gonna look into it later):
Thank you! I can actually read this one...lol.
Just to add on top of the code to explain: Logic: for loop on the Half the Number of lines, and with Integer division(//) Which makes the loop to crete top portion of the MAT For each line we have ODD number of ".|." patterns, so the code (2*i + 1) to make the ".|." created for so many number of times Then this pattern we will CENTER it with a MAX char width of m and filler char of "-", so the code center(m,"-")
Then for the Welcome line, we print WELCOME with "m" chars at center with fill_char
For the bottom part of the MAT, we reverse the pattern LIST created
finally we join all three LISTS and print with "\n" seprated
I have tried the same code but it is giving error: Traceback (most recent call last): File "solution.py", line 1, in a=[int(i) for i in input().split(" ")] File "", line 1 7 21 ^ SyntaxError: unexpected EOF while parsing. Why?
I had the same error. We should use raw_input with python 2 and input with Python 3
because you made some typing error, like
coding at its best!!
Congratulations for the nice and clean (although not obvious at first) approach. A good pythonic solution for the problem.
Thank you...before haven't got the idea to read the list from last
beautifull!!
Fine piece of art as the akatsuki member deodara would say .
My Art Is an Explosion
I am mindblown.
Awesome!
can you exaplain me 2*i+1?
it calculated the times of pattern .|. to be printed, according to index number of line:
lets take n = 7, so n//2 = 3
range 3 will be 0,1,2
for index 0,1,2 you should print .|. 1,3,5 times accordingly
hence 2*i+1
how long did it take you to be this good?
Hlw dear,
Difference between:
the format of input is such that both n and m are seperated by spaces and are in one line. When we use n=int(input()) it takes both the inputs say, "a b" as a string and then tries to convert it into integer.. which is invalid because u cannot have an integer as:- 3 4 . Therefore we need to use split function so that the inputs in one line are treated as two different inputs seperated by space and then can be assigned to two variables n,m.
n, m = map(int,input().split())
why we use "map and split()"
split function allows u to break a string into multiple strings based on the specified seperator. by default the seperator is space. now the result that comes after spliting is a list of items and to iterate through the list of items we use map function.
the format of input is such that both n and m are seperated by spaces and are in one line. When we use n=int(input()) it takes both the inputs say, "a b" as a string and then tries to convert it into integer.. which is invalid because u cannot have an integer as:- 3 4 . Therefore we need to use split function so that the inputs in one line are treated as two different inputs seperated by space and then can be assigned to two variables n,m.
because of the input sequence ...... if u r giving input by press enter then ur formate is true but in this case hackerank giving its input by pressing space thats why
very nice code. Thank you
beautiful :-)
This message has been deleted
hahahaha
Simple and beautiful code
could u explain about the 1st line ie n, m = map(int,input().split()) what is the use of map function?
generally map() returns a map object, you can check it by type(map()) , but when map is used with tuple assignment(values on the left) it returns objects. main function of map is to map function with objects and they are being returned to n,m.
perfectly done, you are the real developer
Lovely solution, easy to understand and read.
jeez... Perfection
Learning Stage
Upper Part
t=1
Upper Half of Mat
for i in range(1,(N//2)+1,1): print((pipe_print*(t)).center(M,"-")) t=t+2
Welcome section
print(welcome_tag.center(M,"-"))
t=t-2
Bottom Half of Mat
for i in range((N//2)+1,1,-1): print((pipe_print*(t)).center(M,"-")) t=t-2
awesome
Congratulations
You're Awesome bro!!!!
awesome code
Great solution, thanks.
xx = input().split()
n = int(xx[0])
m = int(xx[1])
for i in range(n):
print("WELCOME".center(m,'-'))
for i in range(n-1,-1,-1):
May I ask how can you use "for i in range..." in this form? inside brackets, after a string.center() and without any colon?
I had tried to move the for to the beginning of the statement- it didnt work :)
cheers !
your solution is amazing
Beautiful
@ursan the third line amazed me, i was thinking how to generate the pattern incrementally odd number of times till max value and decrease it afterwards. you are awesome bro. keep going and thanks for sharing.
Brilliant logic
Fantastic code.
Elegant solution sir!!!!!
Just changing the pattern and using range with step:
great code!
First solution I submitted was:
Then I used list comprehension and my second solution was:
Almost identical to your solution but the print was a mess. I saw your comment here and stole that print statement (I don't know why I didn't think of creating one big list then using join to print it effectively, but I have learnt now.)
Nice Solution. using the iterator in reverse was "lit".
sexy ;)
always...
very smart!
However this is a typical example of why I do not like python coding and the now so called "pythonic" way (strangely hackerrank does explicitly favor that kind of syntax though)
if you read that a year from now, or if someone else reads this without context you ll have a very hard time to understand even what it does, or how to modify it.
=> this is one time throw away kind of code that can t really be maintained
there is a difference between "short" and "understandable" this code is "short" but not "understandable"
can anybody explain the working of second line ?
If you google "list comprehension", you're halfway there.
ohh man it took me hrs, but your 3 lines code ...is just perfect, great work.
lindo
mind blowing :)
while taking inpur it is still showing an error
i have done the same thing which u have done but its showing error EOF while parsing n, m = map(int,input().split()) this i have written to take input can u suggest me how could i fix it
Thanks bro.
if u can make it 3 lines or 4 lines compard to a few more i doesn't matter in fact this is more cramped and would take alot of time to debug
Amazing code dude!
My solution is 20 lines. I am still trying to get used to pyton. Nice job ursan!
¡Fantástico!
this is amazing!!!
Best Solution man,You are outstanding..!!
perfect
can you explain, what different for loop position? your for loop in one line
wonderfull pal, such a perfect solution.
I'm spellbound bruh
Awesome.
I hate how simple solutions can be. I way overthink these problems and end up with way too many lines. How do I train myself to see the solution like this
Thanks for sharing.
elegant solution!!
well written logic, thank you
Excellent solution! When I entered the discussion, I haven't been expecting to encounter a such thing!
Awesome bro.
very simple solution
yes
A genius. The best of Python world (including list comprehension in line #2) crammed into three lines of code :)
And I learned the string.center() method as well :D
Is it normal to get depressed after seeing these like codes?
amaizngly compact
This is great
very nice
For those of you just learning Python ....if you become a professional don't write code like this. Yes, it is super short and...yes, it is very, very clever.
But...it is also incomprehensible and difficult to maintain if it were production code. Imagine you needed to modify this to draw a circle pattern instead of a diamond? I often have to scrap short, clever code written like this by another developer because it can't be easily modified, and 10 of 10 of your co-workers will appreciate code they can understand easily and quickly.
Thank You!! It was very Helpful!!
N, M = map(int, input().split(" ")) h='.|.' for i in range(N//2): print((h*i).rjust((M//2)-1,'-')+h+(h*i).ljust((M//2)-1,'-')) p='WELCOME' print(p.center(M,'-')) for i in range((N//2)-1,-1,-1): print((h*i).rjust((M//2)-1,'-')+h+(h*i).ljust((M//2)-1,'-'))
i also used same approch my code is 10 line Haha!
This is such an amazing short code. Thank you for this.
It gives Runtime compilation syntax-error !!
This is just Awesome! amazing work man!!
smart
Thanks for sharing!
Beautifully done!
This feels beautiful
Ursan, good job!
I learned some very cool things from this. Thank you.
2 Lines:
excellent solution
n, m = map(int,input().split()) pattern=[str(".|."*(i*2+1)).center(m,"-") for i in range(n)] print(*pattern,sep="\n") print("WELCOME".center(m,"-")) pattern.reverse() print(*pattern,sep="\n")
the knowledge of a center function changes things!
Thank you bro!! you just teached me this awesome "center" function from list comprehensions, never hearded about it. beautiful code of yours!
Just simplified the multiplier index
Bro is the GOAT