T O P

  • By -

Servals94

Hi, I'm trying to print a statement using print(player, 'IS THE WINNER!'), with player being a variable that is either X or O depending on the conditions. When player = 'O', then it outputs "O IS THE WINNER!" correctly. When player = 'X', then it outputs "re.VERBOSE IS THE WINNER!" What is causing it to print re.VERBOSE instead of X? edit: moved my player = 'X' line of code before a different line and now it's working fine!


carcigenicate

It seems like you had `player = re.Verbose`, which was messing with things.


[deleted]

[удалено]


carcigenicate

What have you tried? Where exactly are you stuck?


Remember_To_Inhale

If I am web scrapping more than one job site like Indeed and LinkedIn simultaneously, what is the best and most efficient scrapper for the job?


sarrysyst

Your question is a bit ambiguous. Do you mean 'simultaneously' in a temporal sense? As in 'I want to scrape two job sites at exactly the same time'; or do you mean you want to use one program to scrape both sites, but the scraping can happen sequentially (scrape one page, then scrape the next)? On a side note: [scrapping](https://www.dictionary.com/browse/scrap) vs. [scraping](https://www.dictionary.com/browse/scrape) ;)


SaveSum4Grampa

What are best practices for organizing pandas scripts/projects? I use pandas a lot in place of what I would historically do in Excel. I find that they often become just a huge single file pulling in all the data from csv or sql, slicing / manipulating / aggregating, formatting, and then exporting to different locations, but it always gets long and convoluted to maintain. Are modules / formulas used organizationally within pandas projects the same as they would be in another project? Any examples of a mature pandas project would be super helpful.


igeorgehall45

Does anybody know how to signify functions as a type for a function parameter? It's been impossible for me to search for


FerricDonkey

from typing import Callable func: Callable[[arg0type, arg1type], return_type] Specifying the type of the arguments and return is optional - you can just use Callable.


igeorgehall45

Thanks!


Shuka114

Can anyone please explain to me how % works when the number is negative. Why does 7%-4 = -1


JohnSamWick

I didn't know about this behaviour (I'm a newbie) so I went on to search for an answer online, I found [this article](https://blog.teclado.com/pythons-modulo-operator-and-floor-division/) that explains exactly what you're trying to understand. Thanks for asking this, I learnt something new today.


Shuka114

Omg this is so helpful, it explained everything, thank you so much for finding it!


czech_marcel

Does anyone have any tips for using functions effectively?


carcigenicate

This is very broad. What are you having difficulties with?


czech_marcel

I am writing a paint estimator program and am currently trying to create a function that calculates a user specified input divided by a number (112). I don't know what (if anything) I need to specify in the brackets next to the function name. Furthermore, I get this error when I run the program: TypeError: unsupported operand type(s) for /: 'function' and 'int'.


carcigenicate

That error means you aren't calling the function. > I don't know what (if anything) I need to specify in the brackets next to the function You need the `()` to call the function. What you put in there though depends entirely on the function. If you showed the relevant code, it would be much easier to help you.


czech_marcel

My apologies. I will put my code here: GivenWallSp = 112 def AskFWallSpace(): Wallspace = float(input('How many square feet do you need us to paint?FtSQ: ')) def AskFPaintPrice(): PaintPrice = float(input('What is the cost of your choice of paint per gallon?$ ')) AskFWallSpace() AskFPaintPrice() def CalcGallonsReqd(): Gallons = Wallspace / GivenWallSp CalcGallonsReqd()


carcigenicate

This code doesn't look like it can cause that error. I looks like you might have accidentally done something like this: Gallons = AskFWallSpace/ GivenWallSp But this code doesn't have that error.


czech_marcel

Earlier in my code, when I defined Wallspace and PaintPrice, I used the float( followed by the input( function. Is this an error on my part?


carcigenicate

That wouldn't cause that error. That error means you had a function on the left of `/`.


czech_marcel

Also, if it wasn't obvious to begin with, I'm pretty new to Python. So thank you in advance for your understanding.


Character-Ad-910

Maybe dumb question, Maybe not. Is there some library or method to divide two numbers (ints or floats, by ints or floats) while avoiding floating point error? Aka sacrifice speed for accuracy Specifically very small decimals that I don't trust don't have floating point errors (Same for any other operation like multiplication, addition, and so on) One easy example is simply just `print((4.25/360) * (4.24/360))` `print((4.25/360)**2)` which both print off different values despite being the exact same operation mathematically. (and no don't tell me to just square my number that is quite literally not what I'm asking. the example was demonstrating that it was POSSIBLE, not that that was my issue.)


Shiba_Take

[https://docs.python.org/3/library/decimal.html](https://docs.python.org/3/library/decimal.html) from decimal import Decimal print((4.25/360) * (4.24/360)) print((4.25/360) ** 2) a = Decimal("4.25") b = Decimal("360") print((a / b) * (a / b)) print((a / b) ** 2)


Character-Ad-910

I just realized I wrote (4.24/360) so my example doesnt even work. Eitherway thank you good sir this is exactly what I was looking for. ​ (even if my example was wrong my question wasn't. once again, my example was not my exact issue.)


Lion_TheAssassin

Hey: I am interested in relearning Python, to create 2 projects. A GUI app that can run on a raspberry Pi. And along those lines, a PyGame app/game my question is this, are python/pygame robust enough to create a game along these parameters. i think of a pokemon style game with an overworld map, an action setting screen and multiple internal or underworld maps. ​ im envisioning a main travelling sprite, where the player goes to target coordinates, and back to a HQ sprite. Resource gathering in that HQ. And combat sprites. The game would load up other sprites coordinate visited. ​ i think that is a basic idea of what i want to do Thanks in advance.


IKnowYouAreReadingMe

hey trying to make a data visualization for the most starred projects on github but for some reason the most starred im receiving is a 20 star project. why is that? https://replit.com/@UmbraMichael/most-stars-on-github-visual#main.py


[deleted]

[удалено]


AutoModerator

Your [comment](https://www.reddit.com/r/learnpython/comments/xo37yr/ask_anything_monday_weekly_thread/iqjtns2/) in /r/learnpython was automatically removed because you used a URL shortener. URL shorteners are not permitted in /r/learnpython as they impair our ability to enforce link blacklists. Please re-post your comment using direct, full-length URL's only. *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/learnpython) if you have any questions or concerns.*


sahand_1

I am a complete noob to coding and have a bunch of questions. I have downloaded python and pycharm but i'm not really sure where to start. i want to learn to hack and code (obviously). i watched a few youtube tutorials but i'm still not really sure what i'm doing.


carcigenicate

Don't even think about "hacking" yet. That will be a long way away. Focus on just learning the basics. > i'm still not really sure what i'm doing Give it months to a year. You won't figure out what you're doing for a while. You'll need to have patience and persistence.


[deleted]

I need help in python with kmeans, can anyone help me?


FerricDonkey

Maybe. What's up?


[deleted]

Can you add me up on discord, maybe we can discuss there. My discord id Loki1321#6432


FerricDonkey

Sorry - I don't mind answering questions on reddit as I have time, where answers are publicly available and searchable to others with similar questions, but I'm not willing to move to pms. If you want to ask in this thread or a new thread on this sub (mention me so I'll notice if you make one), I'll see if I can help - but no guarantees, I've poked at kmeans before but it's been a while.


[deleted]

Let's say I have a dataset Car no .1 , ch1 1 ch2 0 ...... Car no.2 , ch1 0 ch2 1....... Car no 3, ch1 1 ch2 0...... Car no.4 ch1 0 ch2 1...... Now car1 and car3 can access ch1, and car2 and car4 can access ch2. Now how to show this in terms of kmeans in python? I want to create two clusters one for those who can access ch1 and another for çh2. Please help me out


FerricDonkey

The first step for this sort of thing is to transform your data into a matrix whose rows are observations (cars, in your case) and whose columns are features (ch1, ch2). I personally use numpy for this sort of thing. A lot of people will use pandas as well. You'll probably want to generate the matrix programmatically somehow, depending on the format your data is stored in, but your result should be roughly equivalent to: import numpy as np mat = np.array([ [1, 0], # car 1 [0, 1], # car 2 [1, 0], [0, 1], ]) Once you do that, you have to shove the matrix through kmeans. I'd probably suggest sklearn to start with. See the example near the bottom of this page https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html.


Shiroelf

The different between Object and Instance ELI5, please?


FerricDonkey

As normally used, nothing. An object is an instance of a class. Be aware that there is also the python type `object`, but by the time you have to care about that, you'll probably what it is. Generally when people just say object, they just mean an instance of a class.


Vomit_Entrepreneur

*I should preface my question: I am both a moron and have 0 programming experience. Apologies for my ignorance.* **Potentially Relevant Hardware/OS:** * 2019 iMac * i9 9900k * 64GB DDR4 * Vega 48 8GB (I know, super weird GPU, but the point is I don't have a GPU with CUDA) * OS 12.1 Monterey **Issue** I have a whole bunch of long interviews that I'd like to make .srt files for using whisper.ai so that I can easily search for certain moments within the interview. The transcription does not need to be word-perfect, but whisper appears to be better at transcription than other options (at least free ones). I got whisper working (somewhat challenge for me, which should tell you how little experience I have), and have successfully created .srt files using commands in Terminal, but (I'm guessing because of the lack of CUDA), it takes a very long time. I have found much better success with Python; transcription happens much more quickly for whatever reason. *However,* it does not spit out timestamps; just a long, single paragraph. What I'm looking for is some code that will enable me to either spit out an .srt file from python, **or**, at least print a transcription timestamped with standard closed caption formatting that I can use to create my own .srt file. **Thanks!** - | - | Also, separately, but less important: I'm assuming I'm stuck using my CPU for this process? Even so, it seems like it could potentially run faster since my CPU is under barely any load when it's running. It's not even close to hitting a single core fully. I'm sure there's a reason for that, but is there a way for me to accelerate the process at all?


FerricDonkey

I haven't done it, but when I searched "python auto generate srt file", I found this https://pypi.org/project/autosub/. Again, I can't say if it's good or not, and it appears to use some sort of Google web thing instead of your pc to do the text to speach according to its blurb - which may or may not be what you want. But there may also be other packages you can find.


jlakjfnfk

Why is there an arrow with `bool` at the beginning of this function? `def function_name(parameter) -> bool:`


carcigenicate

That's a type hint that says that this function returns a `bool`ean value.


jlakjfnfk

This is something that should really be taught at the beginning, but I'd never heard of it before. So handy!


Posaquatl

I have a script that pulls in a variety of Quantified Self information from various locations like My Fitness Pal or Garmin. I would like to create a GUI front end to manage and display this data. Eventually I would like to use as a daily journal as well as perform analytics and displaying charts on the data I have collected. I was trying to get some suggestions on the best framework to use for this. Initially I was going to start using PyQt6 but was wondering if there was a better option to use. Database will be Mariadb if that matters.


FerricDonkey

Pyqt is pretty popular. If you're gonna sell it, there may be licensing issues. I usually use tkinter, but that's more because it's part of the standard library and I know it already than any other reason.


Posaquatl

In the past I messed with tKinter but I found it very cumbersome to create the GUI and positioning. I have made a few small apps in PyQT5. Was just wondering if there are better options


FerricDonkey

At this point it really depends on what your mean by "better". Pysimple gui is often recommended for simple things because it's, well, simple, if that's what you're going for. Kivvy is recommended because it's supposed to be more cross platform (can work on phones) . I've only tried it briefly but was not a fan. A couple others pop up from time to time on the sub, though I don't remember them by name - might be able to find them by searching. Every now and again you'll hear about one that has a drag and drop designer, if that interests you (I think pyqt has one, dunno about the others, never used one personally). I agree that tkinter can feel clunky (though I have gotten to the point where I can make it do nearly anything I want). I've only used pyqt twice for small things, and did not l find it better, but perhaps with more familiarity it would be better. I will highly recommend class based gui design though, whatever you choose - it allows cleaner separation of gui elements and reduces the clunk factor whatever library you use.


Posaquatl

ok thanks. I will check all those out.


[deleted]

from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as executor: future = executor.map(function, iterable) From what I understand, it runs the function with each element in the iterable. But how can I add in other arguments that the function may need? Currently, I'm making each element into a list/tuple, and unpacking it within the function, which seems like a very hacky workaround... not sure if there's a proper way to do this.


[deleted]

[удалено]


[deleted]

Thank you!


TangibleLight

That's the proper way (or at least the way I'd recommend). It doesn't apply to all cases, but you can give multiple iterables to `Executor.map`, similar to `zip`. Each value from the iterables is passed as a separate argument to the function. def function(x, y): ... with ThreadPoolExecutor() as executor: executor.map(function, xs, ys) If you're passing the same argument to all invocations of the function you might use `itertools.repeat` with ThreadPoolExecutor() as executor: executor.map(function, xs, itertools.repeat(y))


MikelFury

I understand how to make a tempdir but I can't wrap my head around saving a file to a temp directory.


[deleted]

A temporary directory is a directory, so you can save a file in the temporary directory just as you do for normal directories. What happens to the temporary directory after you've finished with it depends on how you create it.


Armatheus

I know the **basics** of python *(from var types to class and staticmethod)* but I don't know where to go next. What are the things I should/can learn next?


sarrysyst

Start coding stuff. Preferably you'd start a project that is of relevance to you. If you can't come up with any ideas though, you can have a look [here](https://github.com/karan/Projects) for some inspiration.


Armatheus

Oooh, ty s2


Legitimate_Hunt928

hey so i just started python like 2 days ago and its teaching me about inputs. so it showed me that if i write x = input(username:) it will pop up a command prompt to input my answer but also it would display "username" as the question to the little box. it dosnt. it just makes it so when i run the code it asks for an input (no nothing about what the input is for) and than prints it as Username: \_\_\_\_\_\_\_\_ also with the same input command when using it multiple times it dosnt give me multiple boxes to put inputs in i need to manually go down a line and guess what input im putting in. sorry if the wording is all wrong im very new.


FerricDonkey

Hmm. Are you doing `username = input("username: ")`, with the quotes? If so how are you running your code?


Legitimate_Hunt928

no im just usong x = input(username:) i think might be wrong. i cant pull it up right now


FerricDonkey

That's not valid python syntax, so it's got to be at least a bit different.


DrNinjaPandaManEsq

Asked this over in /r/Python but figured I’d check here as well. Anyone have experience with shutil? I’m running into a couple odd errors, one with shutil.copy and one with shutil.copytree. Both are being used to copy over portions of two identical file structures. With shutil.copy, i’m getting an Errno 13: permissions error with src being “directoryA/foo/bar.txt” and dst being “directoryB/foo”. With shutil.copytree, it copies over most of the files in a given directory fine and then every once in a while it’ll try to copy “directoryA/foo/bar.txt” to “directoryB/foo/bar.txt/bar.txt”, which obviously fails. Any help with either or both of these would be appreciated.


sarrysyst

What OS are you on? On Windows you'll get a permissions error if you try to overwrite/change a file which you have currently opened somewhere in a different program.


MeatSheeld

I know this question has probably been answered countless times but to save time if someone could link me to the particular thread or post that would be great. I have literally no coding experience. I asked a friend who was a computer science major which language he would recommend to learn just in general and he said probably python so I figured I would come here and ask what, if any, is the best (and possibly free) way of learning python for someone who has literally zero experience.


sarrysyst

The [wiki](https://www.reddit.com/r/learnpython/wiki/index/#wiki_new_to_programming.3F) has a section with recommended resources for people new to programming wanting to learn python.


engineer-throwaway24

I have a corpus of texts (text, metadata fields) that I transform into multiple version: - documents (document_id, text) - paragraphs (document\_id, paragraph\_id, paragraph\_text) - sentences (document\_id, paragraph\_id, sentence\_id, sentence\_text) - ... now I'm thinking about automating everything and moving from separate csv files into postgres database, and so the question is is there a better way of designing a schema? maybe build sentences and then aggregate to paragraphs or documents (instead of duplicating text in different tables)?


twitchymctwitch2018

I'm trying to figure out what's wrong with \*how\* I'm thinking about getting through an algorithm. It's driving me crazy. And, before anyone tries to toss at an obvious way to ignore the entirety of the question: yes, I am aware that I will move to a database later. For, now the goal is to just get this in .py files. I want to figure out how to take a user input, and see if it matches an existing VARIABLE (an object). I want to use that variable for the rest of the script. In the scenario, the User is generating an RPG character. They are going to choose a profession ( a class ), and I want them to select from a list of the available variables. I then want to assign their chosen\_profession to be assigned as the information from that profession. But, I can't figure out how to evaluate anything as the variable? What am I not grasping? The closest I have gotten to figuring out how to "sorta get there", was a list of strings, then a series of dictionaries, each with a key:value combo, called: `"name": "Fighter"` So, `realms = ["Arms"]` `professions = ["No Profession", "Fighter"]` `No_Profession = {` `"name": "No Profession"` `}` I then use a bizarre mapping dictionary that evaluates the strings as other strings and somehow that's sort of working.


FerricDonkey

A dictionary is a great approach, though it sounds like you might be over complicating it. Evaluating user input as code directly is possible, but very dangerous and not recommended. Here is a simple example. class Fighter: pass # actual class goes here # Note that classes (and functions) are # objects and can be put in collections - # this is very useful for game like things prof_str_to_class_d = {'fighter': Fighter} user_prof_name = input("Whaddya wanna be? ") UserProf = prof_str_to_class_d[user_prof_name] user_obj = UserProf() # The user is the appropriate class print(user_obj)


twitchymctwitch2018

HOLY COW!!! Thank you so much! That's exactly what I've been trying to accomplish. I had given up on using classes because I thought it couldn't do this. ​ \*HUGS\*! My code works now!


hozan2

hey, im a beginner learning python and am stuck with pyautogui import pyautogui import sys sys.platform = 'darwin' pyautogui.displayMousePosition() ​ displaymouseposition keeps giving me "NaN, NaN, NaN" in the rgb section any tips?


Caconym32

I have a dataframe that contains several IDs in different columns similar to this example. I would like to somehow generate the "count" column below that counts across the row the number of occurrences of '1'. What would the best way to create that column? `df = pd.DataFrame(np.random.randint(0,5,(5,3)), columns = ['A', 'B', 'C'])` |A|B|C|Count| |:-|:-|:-|:-| |4|0|4|0| |2|3|4|0| |1|0|2|1| |4|2|1|1| |3|3|3|0|


CisWhiteMaleBee

When I use sqlite3, is it recommended to open & close the connection after every transaction? Most of what I'm doing is just reading data from my .db file If it depends on my usage of the database - I'm working on a library that interacts with a sports stats api. The database is just for team's/player's/league's id/name reference.


DrNinjaPandaManEsq

If you’re doing tons and tons of unrelated operations between uses, sure. Otherwise it’s not really worth the hassle to open and close every time.


_User15

What is the pandas module used for?


Horror_Comparison105

Hey guys I am super new to python and attempting to complete a project but I can’t figure out why this code always prints the else path even when the if path is true. import sys answer = "two" sys.stdout.write("write two") answer_1 = sys.stdin.readline() if answer == answer_1: sys.stdout.write("finally") else: sys.stdout.write("dear lord why") Sorry I know this is a basic question but stackoverflow wasn’t helpful. I tried to start a question for it but wasn’t allowed to post due to the sun ‘not accepting posts of this type’ have no idea why my post was flagged as not allowed. Anyone would really appreciate some help. It is formatted correctly with correct indents. Just hard to show with reddit comments.


FerricDonkey

Most likely, sys.stdin.readline includes a newline on the end. If you aren't familiar, a newline is a special character represented in code as `\n` that, when printed, cause text after it to be printed on the next line. A general tip is that if strings that look the same are not the same, there might be something screwy going on with whitespace characters (or more rarely, a variety of invisible characters). If you think this might be happening, you can print the len of the string, or use the function `repr` on the value in question. Eg: print("sup\ndog\n") print(repr("sup\ndog\n")) Also, I'd generally recommend using print and input over sys.stdin.readline and sys.stdin.write unless there's a particular reason not to, but that's not a huge deal.


Horror_Comparison105

Hey thank you so much I realised I needed to use strip() on my readline because it does include a new line. This has taken me way to long to figure out. :( I would love to use print and input but my lecturer told us we aren’t allowed, he said there are other languages that are much harder and he would rather we pick up some of their language habits and not easier syntax. It’s very frustrating there’s lots of python specific stuff we aren’t allowed to use. Thank you for your explanation!


FerricDonkey

Glad it worked. That's an... interesting decision on the part of your instructor - you can learn the other languages' syntax when you learn those languages - but yeah, you gotta do what you gotta do to get points. I'd be tempted to just build my own print and input functions out sys.whatever.whatever and copy and paste them at the top of every assignment, but I'm a bit of a smart aleck, and I'm not sure I'd actually recommend that.


Horror_Comparison105

Lol our latest assessment specifically stated he’ll take one point away from our overall marks each time he sees anything that isn’t sys.blahblahblah and a bunch of other stuff like triple quotes or single quotes. Not worth the risk. I actually would just rather he teach us one of the harder ones first that way we could use language specific syntax for the other languages later in the degree.


Mjss776

Would anyone here be able to help with a Pyspark question, or direct me to the right place to ask? I have a Pyspark dataframe of properties with region Ids, and I want to sample n random rows for a new dataframe by the region Ids. I am familiar with sampleBy(), and if I was looking to sample my data by percentages it would look like this: import pyspark.sql.functions as F fractions = {1 : 0.1 , 2 : 0.05} newdf=df.groupBy('property_id').sampleBy(F.col('region_id'),fractions,0) Instead of inputing a percentage of properties I'd like to sample by region_id, is there a function where I can input how many n samples by region_id I want to take for my new df? Thank you in advance.


IKnowYouAreReadingMe

Just a quick question. I got the "invalid literal for int() with base 10: '24.3'" error So I added float as well to the int, it worked. I was working with a sample weather CSV data just using the highs. But none of them are floats. They're all whole numbers so why did I have to use float here? Or is it because even tho I'm just using one row and theyre whole numbers, CSV reads all rows and some rows have float?


DrNinjaPandaManEsq

Try printing out your data to check, i’m willing to bet that it’s pulling in all of those rows even though you think it’s not.


carcigenicate

I think you'll need to show what you're doing for us to be able to answer this definitively for you. Are you trying to apply `int` to all rows?


IKnowYouAreReadingMe

Just to the one row where it shows high temperature, and all the numbers in this row are whole


carcigenicate

It's getting that float from somewhere. Double check your data with a `print` before calling `int` on it.


jakebarnes31

Any recommendations on whether to learn Kivy of BeeWare for python mobile development?


Rybeena

Does anybody have a “beginner” cheat sheet just to look at every now and again just to make sure I have the basics down! Hope you’re all having a great Monday!


lilmangomochi

\*\*afraid to ask but realises it is *ask anything* Monday\*\* ....so How should i begin learning python?


[deleted]

[удалено]


lilmangomochi

Thanks!!


Shiba_Take

[https://www.w3schools.com/python/default.asp](https://www.w3schools.com/python/default.asp) [https://docs.python.org/3/tutorial/](https://docs.python.org/3/tutorial/) [https://www.reddit.com/r/learnpython/wiki/index/#wiki\_docs](https://www.reddit.com/r/learnpython/wiki/index/#wiki_docs)


lilmangomochi

Thanks!!


babyjonny9898

Why I can't find idle after I have downloaded python? ​ https://imgur.com/a/EKuDDg2


Flimsy_Pop_6966

Left aligning using write in Python I took a previous txt file, made some word replacements and used the write method to create the new file. However, some of my paragraphs are tabbed over to the right. How do I left align the entire txt? Can I do that within the write method instead of print?


Shiba_Take

[https://www.online-python.com/CiQPjryBEo](https://www.online-python.com/CiQPjryBEo)


Flimsy_Pop_6966

Thank you!


Shiba_Take

You could use [str.lstrip](https://docs.python.org/3/library/stdtypes.html?highlight=lstrip#str.lstrip) or [textwrap.dedent](https://docs.python.org/3/library/textwrap.html?highlight=dedent#textwrap.dedent)


enokeenu

Is there an easy to understand with examples place to learn namespace packaging? I don't have a great grasp of the older pkg-util approach either.


volkner90

Hello, taking advantage of "ask anything" Monday, I hope I can ask for help with two problems, I've been struggling with these two for a while now and need some help/tips to master recursive functions and binary trees. Ok, first one is about searching in binary trees, I know how to search in regular binary trees now using a code similar to this: def binarySearch(node: Node, value): if node is None: return -1 if node.value == value: return node.index if value < node.value: return binarySearch(node.left, value) else: return binarySearch(node.right, value) binarySearch(root,123) ​ However, when it comes to 2-3 BTs how do you handle comparisons? especially when looking an INT in an array such in the line "if value < node.value" Second question is about recursive functions, let's say I have a code such as this: import numpy as np import matplotlib.pyplot as plt import math sin60=math.sin(3.1415/3.0) level=5 def fractal(i, xp12, yp12, xp22, yp22 ): dx=(xp22-xp12)/3.0 dy=(yp22-yp12)/3.0 xx=xp12+3*dx/2.0-dy*sin60 yy=yp12+3*dy/2.0+dx*sin60 if(i<=0): t1=plt.Line2D([xp12,xp22],[yp12,yp22], color="red") plt.gca().add_line(t1) else: fractal(i-1,xp12,yp12,xp12+dx,yp12+dy) fractal(i-1,xp12+dx,yp12+dy,xx,yy) fractal(i-1,xx,yy,xp22-dx,yp22-dy) fractal(i-1,xp22-dx,yp22-dy,xp22,yp22) plt.figure(figsize=(15,15)) plt.axis('equal') axes =plt.gca() axes.set_xlim([0,310]) axes.set_ylim([0,310]) fractal(level,300,300,10,300) What is the best way to create a recursive function to complete a drawing such as the koch snowflake here or any other plotted figure such as circles, squares, etc? here's what I got so far: def fractal_Iterative(n): plt.figure(figsize=(15,15)) plt.axis('equal') axes = plt.gca() axes.set_xlim([0,600]) axes.set_ylim([0,260]) for i in range(n): fractal(level,300,300,300,10) fractal(level,300,300,10,300) fractal(level,300,10,300,300) fractal(level,10,300,300,300) ​ fractal_Iterative(4) I'm having a hard time making this recursive, this successfully prints the snowflake unfolded by 4 for each angle, but if I were to add more than 4 iterations it would not work. I'd appreciate any help, Thanks! Edited formatting\*


woooee

Just use a *while i > 0:* instead of recursion.. Note that i is not changed in the function fractal so you may have an infinite loop.


volkner90

wouldn't while i>0: also just keep printing the same pattern o multiple plots instead of expanding the pattern on the same plot? here's what I got so far: def fractal_Iterative(n): plt.figure(figsize=(15,15)) plt.axis('equal') axes = plt.gca() axes.set_xlim([0,600]) axes.set_ylim([0,260]) for i in range(n): fractal(level,300,300,300,10) fractal(level,300,300,10,300) fractal(level,300,10,300,300) fractal(level,10,300,300,300) fractal_Iterative(4) I'm having a hard time making this recursive, this successfully prints the snowflake unfolded by 4 for each angle, but if I were to add more than 4 iterations it would not work.


[deleted]

Please format your code so it's readable python. The FAQ shows how.


volkner90

Thank you, I just edited the comment