Try to print frame * and diagonal in python

2024/10/9 13:22:22

I try to print '*' in frame and in diagonal .

This is what I did:

x=10
y=10
def print_frame(n, m, c):print c * mfor i in range(1, n - 1):print c ,' '*(n-2-i),c, ' '*i , c  , cprint c * mprint_frame(10, 10, '*')

This is the result:

**********
*         *   * *
*        *    * *
*       *     * *
*      *      * *
*     *       * *
*    *        * *
*   *         * *
*  *          * *
**********
Answer

As I specified in my comment, only square matrices have diagonals. But even for those, things are "a bit" more complex than they seem:

  • I could have done it in a single loop, but I think it's better to see all the "sections"
  • The (string) calculations could have been written in a more compact way, but I left them as they are for clarity
  • Also added the recursive variant. I prefer this one as it's clearer (although in general, recursion has limitations), especially since given the nature of the problem, the recursion doesn't go deep enough in order to generate StackOverflow, or to have a negative effect on performance
  • Instead of printing the string inside the function, I "return" them. That is an optimization technique: if they are needed in more than one place, the function only needs to be called once
  • The functions are generators (yield instead of return). That is also an optimization (and it's Pythonic)

code01.py:

#!/usr/bin/env python3import sysdef square_frame_iterative(side, char="*"):yield char * side  # Upper rowfor i in range(1, side - 1):edge_space = min(i - 1, side - 2 - i)mid_space = side - 2 * edge_space - 4mid_text = char if mid_space < 0 else char + " " * mid_space + charyield char + " " * edge_space + mid_text + " " * edge_space + charyield char * side  # Lower row# Recursion
def _square_frame_recursive(side, char, i):if i == side // 2 - 1:if side % 2 :yield char + " " * ((side - 3) // 2) + char + " " * ((side - 3) // 2) + char  # Mid rowelse:s = char + " " * i + char + " " * (side - 2 * i - 4) + char + " " * i + charyield syield from _square_frame_recursive(side, char, i + 1)yield sdef square_frame_recursive(side, char="*"):yield char * side  # Upper rowif side <= 1:returnyield from _square_frame_recursive(side, char, 0)yield char * side  # Lower row# Recursion enddef main(argv):dim = 10square_frame_func = square_frame_iterativeif argv:if argv[0].isdigit():dim = int(argv[0])if (len(argv) > 1) and argv[1].lower().startswith("rec"):square_frame_func = square_frame_recursiveframe_string = "\n".join(square_frame_func(dim))print(frame_string)if __name__ == "__main__":print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))main(sys.argv[1:])print("\nDone.")

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055342983]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code01.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32**********
**      **
* *    * *
*  *  *  *
*   **   *
*   **   *
*  *  *  *
* *    * *
**      **
**********Done.[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055342983]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code01.py 7 rec
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32*******
**   **
* * * *
*  *  *
* * * *
**   **
*******Done.
https://en.xdnf.cn/q/118579.html

Related Q&A

How do I have an object rebound off the canvas border?

I am using the canvas widget from tkinter to create an ellipse and have it move around in the canvas. However when the ellipse comes in contact with the border it gets stuck to wall instead of bouncing…

How to scrape data using next button with ellipsis using Scrapy

I need to continuously get the data on next button <1 2 3 ... 5> but theres no provided href link in the source also theres also elipsis. any idea please? heres my codedef start_requests(self):u…

Execution Code Tracking - How to know which code has been executed in project?

Let say that I have open source project from which I would like to borrow some functionality. Can I get some sort of report generated during execution and/or interaction of this project? Report should…

Python code to ignore errors

I have a code that stops running each time there is an error. Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?Below is the code:imp…

How to match background color of an image with background color of Pygame? [duplicate]

This question already has an answer here:How to convert the background color of image to match the color of Pygame window?(1 answer)Closed 3 years ago.I need to Make a class that draws the character a…

Sharepoint/SOAP - GetListItems ignoring query

Trying to talk from Python to Sharepoint through SOAP.One of the lists I am trying to query contains ID as primary key field.(Field){_RowOrdinal = "0"_FromBaseType = "TRUE"_DisplayN…

python mean between file

I create a list of more than a thousand file (Basically now I have a list with the name of the file) now in order to make the man I thought to do something like this (suppose asch file have 20 lines): …

Sort a dictionary with custom sorting function

I have some JSON data I read from a file using json.load(data_file){"unused_account":{"logins": 0,"date_added": 150},"unused_account2":{"logins": 0,&qu…

Turtle make triangle different color

Hi guys Im trying to replicate this image:Its almost done I just have one issue, where the triangle is supposed to be yellow it isnt seeming to work.Mine:Code:fill(True) fillcolor(green) width(3) forwa…

How to DataBricks read Delta tables based on incremental data

we have to read the data from delta table and then we are joining the all the tables based on our requirements, then we would have to call the our internal APIS to pass the each row data. this is our g…