Repl Talk
A friendly platform to share and discuss all things
Updates from the team about the product
✨✨Introduce Yourself! 👋 ✨✨
Hi everyone! Use this space to share anything you want to share with our community - your name, where you're from, what you program in, what brought you here... whatever you're comfortable with! Can't wait to get to know y'all. 💖 Katya
posted by katyadee (436) 6 days ago
⚡️DEVELOPER SPOTLIGHT #02:⚡️simontiger
### Welcome to another **Developer Spotlight**! Today we (virtually) sat down with 9-year-old Belgium-based [wunderkind]( [Simon Tiger]( and his mom, Sophia. ![virtualcafe]( Simon came to our attention after he shared a [repl]( of a neural network he’d built. Without further ado, here’s our interview: ![DSC_1714]( **@katyadee**: If you could sum yourself up in one sentence, how would you do it? **@simontiger**: This would sound a bit circular, but I would say: "To sum me up in one sentence: You can't sum me up in one sentence.” **@katyadee**: I think that actually says a lot! You’re really well spoken—are you really 9 years old? **@simontiger**: Turning 10 soon. **@katyadee**: Wow. So, are you in school? **@simontiger**: No, I’m homeschooled. We even had to move to Belgium to be able to homeschool, because school is mandatory in the Netherlands (where I'm from), and it didn't fit well with me. **@katyadee**: That’s really cool that you guys find a way to make it work. I really like your mom’s site. It says you’re a mathematician… I’m wondering, what does that mean to you? Are you doing research? **@simontiger**: Well, that's a difficult question. I see patterns in the world wherever I look. I just love doing math, I'm doing math loads of time every day. Like I'm writing a short book about knot theory and experimenting with knots. Or I want to use Penrose's Illumination Problem in my coding. And I make math videos. Ron Graham said he liked my video about the Graham Scan Algorithm!
 ![DSC_2176]( **@katyadee**: I’m blown away. [Ron Graham]( - that’s no joke! Speaking of coding, how’d you start? **@simontiger**: With Arduino and Sparkfun. And I discovered Arduino through [littleBits]( Arduino was how I discovered [Processing](, and how I discovered [Coding Train]( by Daniel Shiffman. He always watches my videos and has become my friend. And I participate in [Coding Train Live Sessions in Slack, too]( **@katyadee**: Wow! Where’d you go from there, after Arduino? What was your first language? **@SimonTiger**: Surprisingly, not English! It’s not my native language. I taught myself English by watching coding videos, mainly. My actual native languages are Dutch and Russian. **@katyadee**: Oh, I meant programming language! I’m sorry. **@SimonTiger**: After C, with Arduino, I started using all sorts of languages for a while but now I have settled on JS, Java, Python, and sometimes Haskell. And sometimes even the Wolfram language! ![DSC_2019]( **@katyadee**: What brought you to **@SimonTiger**: I was first just looking for an online Python editor, because my computer memory was (and still is!) almost full.  I first found, but then, after a while, my code disappeared! And then I started using And now I even no longer only use Python on, but also JS. I one time tried to use Haskell on, but that didn't really work for my purpose, because the browser runs on JS which is a strict language, and Haskell is a lazy language. **@katyadee**: What’s your favorite thing you’re building on **@SimonTiger**: Pretty much all of my repls are a work-in-progress. Here are two: [Raytracing A.I.]( [Sorting Algorithms]( **@katyadee**: One last question for ya. What are your plans for the future? Your present is pretty darn cool. **@SimonTiger**: Depends on what you mean. More coding, math, and physics—if that counts. ![IMG_20190510_131529](
posted by katyadee (436) 6 days ago
39 Mobile App MVP
**We did it!** [10 days ago]( I created a post asking if people were interested in a mobile app for The answer in general was yes, and I set out to build the best possible thing I could. And I just released the MVP of the app. Here are some supported features: - Creating and deleting repls and files 📂 - Both dark mode and light mode 🌚 - Integrated code editor with syntax highlighting 💻 - Rich editor preferences ⚙ - Works on both Android and iOS 📱 And I'm planning on adding much more, including Repl Talk support. I couldn't have done this without the help of all the amazing testers on our Discord server as well as support from team members. This was also a fun experience learning React Native. ![Screenshots]( **Q: Where can I download it?** A: You can download the Android app [here]( iOS is supported but I don't currently have a release. **Q: What about running repls?** A: Although you can view web repls, other types of repls are not currently supported. recently moved to an API based on [protocol buffers]( and due to several concerns of theirs we may have to wait until June. **Q: What the heck is an MVP?** A: MVP stands for "minimum viable product." According to [Wikipedia](, it is "a product with just enough features to satisfy early customers, and to provide feedback for future product development." **Q: What did you build it with?** A: I used [React Native]( as well as many other open-source projects including [React Native Paper]( I really appreciate all the work the maintainers of these projects put in that helped make Mobile so much better. If you're interested and want to learn more or get early access to features, make sure to [join the Discord community](! *Disclaimer: Mobile is currently a community-run project. You can view the source code [here](*
posted by Kognise (145) 14 days ago
16 Feature Roadmap
At the current time of writing, the team is 8 people, and we are often asked about what we're working on. We actually use our [Feedback boards](/feedback) as a roadmap, though it may not be clear. Posts can have statuses like `Planned` or `In Progress`. Let me explain what each one of those means: `In Progress` means that development or design for the feature has begun. It may have just started, or we may have released a semi-working version of the feature (like the [Shell](/site/blog/shell)), for example), and are looking for ways to expand its capabilities. Github integration is another example of such a feature, where we have [importing github repls](/github) but not the other way around - that will come soon. ![image]( `Planned` means that we're actively looking for avenues into a particular feature, but development has not yet begun on it - for example, we know for sure that we want to make a mobile app, but we currently don't have the bandwidth to support it right now. And then there are features that are not in progress or planned. If you've been eyeing a feature in this category, fear not! It does not mean that we don't want to implement it! If we put every feature we wanted to add under "planned", that word would lose all meaning as we would love to implement 99% of feature requests that come in. But as a team of 8, we can only do so much, and we ask for your patience as we build the perfect tool for everyone. [View features in progress]( [View planned features]( What you see on these pages are also not exhaustive. We're quite busy every day and we sometimes forget to give a post a particular status. If you're ever curious about any of them - just ask! We don't bite. :) Happy programming, Tim
posted by timmy_i_chen (869) 9 days ago
Kickstart your project using Templates!
At, we are all about propping you up to launch your next website, app, or game. To that end, we've created Templates, a page containing starter code for various projects you can build on ![templates-min]( Templates include: * an e-commerce landing page using Bootstrap * an interactive game using Phaser.js * a backend server running on Python's Flask * a virtual reality environment in your browser using A-Frame * And so much more! ![]( We're proud to showcase these templates, created by our community. You can access these templates at the [templates page](, or by finding the card in your dashboard's recent repls: ![image]( Want to add a template to the page? We're always looking for new templates. Submit your repl [here](! Please be sure to leave any feedback for us in this thread. Happy templating!
posted by timmy_i_chen (869) 17 days ago
See more posts
Ask coding questions
Guide to Asking Coding Questions
# **Guide to Asking Coding Questions** ## **Why?** Good questions help your question be solved faster, and people will want to answer your question Bad questions waste time, you will often not get answers that you asked for, and people will often ignore your questions ## **Quick Questions Guide** ### Do This - Always ask your questions in English - Explain what you want the code to do - Explain what the code does - Include error messages - Share the repl with the line numbers - When you figure out the answer, update your post - Put the repl link, instead of pasting code ### Don't Do This - Don't post homework questions - Don't use caps in the title - Don't use words like 'HELP' or 'PLEASE' in the title - Don't post questions that already have an answer (Search Box) - Don't post feedback or bugs on Talk, use []( for feedback, or []( for bugs ## **Steps For Better Questions** 1. Understand the code - Read your code and figure out what each line does - If a concept is unfamiliar, Google it - You can also use a debugger to help you 2. Describe the problem - Explain what you want the code to do - Explain what the code does (error messages) 3. Provide the code - Share a repl that has your code - Share the line number(s) of your code issue - Make sure that the code you shared has the issue 4. Format code consistently - Make sure your code is easy to read 5. Check for typos - Make sure the code does not have any typos that would cause the problem 6. Explain what you did to troubleshoot the problem - Make a list of what you think the problem is and try to fix your problem by going through the list 7. Make a guess on what you think the problem might be - Use the list from the previous step 8. Proofread the question - Make sure you provided everything - Clear all confusions that you think there might be 9. Update people on the question - If you figured out the answer, edit the post to tell people - When you get an answer, fully understand it - Be nice to people who answer your question - Remember that the people wanted to answer your question, but didn't have to 10. Things to NOT do - Don't post homework questions - Only post questions in English - Do not use caps in the title - Do not use "HELP" or "PLEASE" in the title - Don't post questions that have already been answered (Use search box) - Don't post feedback or bugs on Talk, use []( for feedback, or []( for bugs ## **Example:** ### **Question** We have some Python code with an error: [repl]( ```python rannumexe = int(input()) if rannumexe = 1: print('hi' + rannumexe) ``` ### Step 1 We show what each line does using comments. ```python rannumexe = int(input()) # Asks the user to input a rannumexe if rannumexe = 1: # If the rannumexe equals 1 print('hi' + rannumexe) # Print hi and the rannumexe ``` ### Step 2 We want the code to input a number, and if the number is one, print "hi" and the number. Our problem is that we have an invalid syntax error on line 2 in the file. ``` File "", line 2 if rannumexe = 1: ^ SyntaxError: invalid syntax ``` ### Step 3 Our repl with the issue is located [here]( We have an issue on line 2 ### Step 4 We can change "rannumexe" to "number" to clear confusion ```python number = int(input()) # Asks the user to input a number if number = 1: # If the number equals 1 print('hi' + number) # Print hi and the number ``` ### Step 5 We don't have any typos ### Step 6 Our problem could be that we improperly used the if statement ### Step 7 The problem could be about using the if statement incorrectly ### Step 8 Our final question: Title: Invalid syntax error about equal signs Content: I have an invalid syntax error on line 2 in the file of this [repl]( The program should take a number as an input, check if the number is equal to one, and if so, print "hi" and the number. The error point to the equal signs and I think this issue is with the incorrect syntax of the if statement. Help is appreciated :). ```python number = int(input()) # Asks the user to input a number if number = 1: # If the number equals 1 print('hi' + number) # Print hi and the number ``` ``` File "", line 2 if rannumexe = 1: ^ SyntaxError: invalid syntax ``` Steps based on Gordon Zhu's [post]( If you have any suggestions or feedback, post it in the comments below.
posted by Mosrod (235) 8 months ago
What is the language you recommend the most? Why do you recommend it??
Well, the title says the most. Just searching for a new one to learn. Mine is in fact, Python 3.7. I like Python 3.7, because it runs on like everything, even on my small raspi zero. Mh I should add that I, in this moment, I speak Python, R, in advanced 8/10 levels of skill, HTML in beginner level, as I do in CSS and C++. JS in mid levels of skill
posted by enigma_dev (35) 3 hours ago
What advice would you give to someone new to coding?
In the spirit of our new ask features... * What advice would you give to a newbie? * And what advice do you wish someone had given you? * What advice would you give me, personally?
posted by katyadee (436) 3 days ago
What's your favorite thing about What about your least favorite?
What's your favorite thing about IDEs in general? What about your least favorite? (Slash if you could add any feature, what would you add?)
posted by katyadee (436) 7 days ago
I cant find the error
I cant find the error in my code... It just says invalid syntax, but i cant find whats wrong....
posted by TheSpeakingLava (0) 6 hours ago
See more posts
Submissions have been closed. Stay tuned for results!
The Fishing Game
# The Fishing Game *Explore your way through the different regions by catching the rarest fish you can. Catch em all to fill up your fishedex!* Hi!! This my fishing game. Here's a bit of an explanation that you also get ingame: Welcome to my fishing game! The aim of the game is to reach level 100 as quickly as possible. Catch the rarest fish you can and level up! You can sell your fish in the shop. Rarer fish bring in more gold. You can use this gold to purchase bait, which is needed to catch fish, and rods, which make catching rarer fish easier. Careful, bait gets more expensive as you level up. New types of fish are unlocked as you level up, and at higher levels, it's easier to catch fish. You can also see information about all the fish you've come across in the 'fishedex' in the shop. Catch them all! You might also find some treasure when you're fishing! The game saves your progress at the end of each day, so you can just log in again and pick up where you left off. Good luck! Press enter to continue. Not gonna lie, it's pretty fun. *** ## Backstory I made this game last July. The reason I choose fishing was mainly because it makes plurals easier - the plural of most types of fish is the same as the singular ;) (This doesn't work for anchovies though... or mythical creatures. Oh well). To make it I did have to learn a little about using classes and objects - I find them really useful now though. My coding's definitely developed a bit since I made this (it's a mess), but I can't really be bothered to make the code any neater (I did a tiny bit). I have edited it a bit since I originally made it to make it ready for the game jam. Here are some of the additions (spoiler for past level 100!!) : * There are new "mythicals" which are extremely rare fantasy creatures, like mermaids. They can only be encountered after level 100. You can't sell them, though the game remembers which ones and how many you've seen. You need the special new moonstone rod. * The game's harder now, in that the XP needed to level up increases exponentially as you go up the levels. I really should have had that from the beginning, because levelling up was way too quick. * Some new types of fish! * Highscore board for how many days it takes to reach level 100. I'm not sure if this was in the original fishing game that I posted in July, but I don't think it was. It's empty currently because the new XP-level scale has made all the previous highscores made by me and my family during testing unfair. Let's see who get's the lowest! * Rarest fish stat. Within the rarity boundaries like common, uncommon, rare ect, there are varying rarities based on a number. If you catch a fish with the same rarity number as your rarest fish stat, it counts as rarer if it's unlocked at a higher level. Basically, higher level is used to decide rarity in a couple of cases. The point is, I wanted to add something that made the game more orientated to getting the rarest fish - kinda like pokemon. Anyone got the blue whale? * Changed the rod names from "default, alright, decent, good, great" ect. to "wooden, bamboo, copper, iron, steel" ect, just for added character. The only one that stayed the same was the awesome golden rod ;) *** ## In the Future... I've got a few ideas for what I want to add to the fishing game... * A little addition of telling you the current highscore when you sign up, or when you log in, or at the top each day in game. I just don't really know which one would be best. Let me know what you want! * More fish of course! I just don't want to bombard you with them. Maybe if some of you guys really like the game I'll put a personalised fish in for you ;) * More ideas post level 100. Maybe some cool non-mythical fish. * Having the option to change rods using ones you've already bought, because at the moment if you want to change your rod you have to repurchase any you've already bought and that's just dumb. * New rods with cool properties, like extra attempts per day, or unlocking specific types of fish, unlocked at certain levels. * Maybe, but probably not, lengths of fish - they'd be a mean length for each type, and the fish you caught would be around this. The price could depend on length. There could be a new stat with longest fish caught? I feel like this is just too complicated for my simple little fishing game though. * Music! I feel like it would really benefit from some tunes but I don't know how to implement that. I'd have to look in to it. * Your suggestion here. Seriously, I would really love it if you guys could tell me what you want to see, if you like the game of course. PLANS FOR THE FINAL DAY * *Quests/achievements?* * *Rainforest and/or ~~fire biome?~~* DONE fire, I think rainforest would be cool but too much * ~~*Settings page with options to reset account, see highscores, see game info/help, see current number of accounts on the game?*~~ DONE * ~~*Work on fish rarity colours and fishedex/treasuredex colouring.*~~ DONE * ~~*End biome highscores page?*~~ DONE and in settings * ~~*Mythicals for the other biomes !!!*~~ DONE * ~~*Better names than "normal biome" "ice biome" "desert biome"*~~ DONE but they were stolen from game of thrones... oops * ~~*Weathers with different fish for different weathers*~~ DONE *** Well that's it. I really hope you guys like it. If there's any bugs let me know, and if you want any improvements, let me know too! Thanks so much for trying it out! (also sorry that it doesn't fit the cash theme. I edited it to make it more appropriate to the cash theme, but it kinda sucked. I prefer the cutesy fishing element) On a final note, let me know if you encounter all the mythicals! That would be seriously cool! Edit: don't really care if you don't like that it's in all lower case. I think it looks nicer. *** ## Change Log since posting * Input validation for a, b, c at the start of the day, to avoid the "press enter and run up your days" error * Input validation for logging in or signing up * More input validation for selling some fish, plus added capability for selling multiple fish at a time (not all fish) and fixing a bug that would've prevented fish with spaces in their name - eg electric eel - to be sold. * Fixed the printing of high scores so that it's in actually in the correct order, plus accounting for ties. * Disallowed "-" characters in the username, which would've messed up the accounts file, had it been working anyway. * Lowered the power of the rods and raised the prices for a more difficult game ... sorry if the highscores are now unfair but I can't let it be the same game forever :( * More input validation in the shop... it never ends * Weirdly, more input validation in the shop, I thought I caught it all, but nope. thanks for catching that, TechGamer * Added the "fishedex"!! It's amazing! It's literally just a pokedex. Go to the shop to see it. If you do manage to catch em all then tell me if my code works and you get a congratulations. Hope you all like the fishedex, thanks to Hamloid for the idea! * Accounts and highscores saving error fixed! * You don't get as much info about a fish each time you catch one now, only the first time you do. I think it looks a lot nicer. * The code now has the grammar knowledge of a 6 year old and can appropriately use "a" or "an" now. * If you put in "log in" but you should've put in "sign up", you no longer need to refresh, the code will sort it out for you. * Fixed password security thanks to ebest! * Added treasures and treasuredex! * Fish are now coloured based on rarity, inspired by Runescape! * Different biomes with different fish, different treasures, harder xp gradients, and dangers [dangers are so cool]! Level resets to 1 in these biomes. You can travel between biomes by ships (your old levels stay the same, don't worry). Biomes are only unlocked past level 100. I only have the ice biome now, but more are coming (unlocked at ice level 100, ect.) * Biome specific rods! [only 1 per biome, but they're both great at getting rare fish, and allow mythicals (at the moment mythicals can only be caught in normal, but I'm going to add ice and desert mythicals) * Desert biome added!! I know, the names suck. I'm working on it. * Bait price increases as you level up. It's also more expensive as you go through the biomes. * Dangers added for normal. * "One use" items! These are pretty cool and last for 1-2 weeks, increasing your chance at either: catching a fish, catching a treasure or catching rarer fish, or keeping you safer. There's 2 "levels" of item for each, with the better being rarer. They can't be bought in the shop and are instead found when fishing. * Added weathers, which are specific to biomes. Most fish can only be caught in certain type(s) of weather. * Added settings page with options to reset account, see highscores, see total number of accounts signed up, see game info and see game help. Going to settings doesn't use up your day, unlike the shop. * Improved fish rarity colours suggested by Mavrick and each line in the fishedex is coloured according the what biome the fish is found in. * Fire biome, which is the last one! Highscores page for when you complete it. * Mythicals for different biomes. * Biomes are no longer called biomes and are now named after locations in game of thrones. * Massive bug exodus just before deadlines oops * Inputs except user and password are now not case sensitive * Slight edits to reaching level 100 & ship functions * cats_ur_cool77's awesome fishing game tribute can be found in settings! * credits when you reach endgame! *** ### New: Competition! Anyone who can reach level 100 in under 300 days can have a personalised mythical! Screenshot the highscore board once you reach 300 and tell about what you want your mythical to be. Maybe they'll have even more XP than normal mythicals. Good luck!! *** **Account bug FIXED! Finally! Thanks so much to leon332157 for their json store module - Your account information and highscores should always be saved now! (let me know if you find a bug though)** **Issue with account security is definitely improved now. Don't try too hard to hack it though aha Edit: account security is much better now!! thanks to ebest! ** **Don't forget to upvote if you enjoyed the game! Thanks so much to everyone who has done so, or commented, already!** *** ### Notes to judges * *Sorry that there are no screenshots of game play. I was planning to take some today but I have definitely ran out of time :(* * *Please don't mark me down because it's all in lowercase. It's inspired by a dark room, and it's super easy to change at the end of the day.* * *PLEASE play until you reach at least ~~the ice biome~~ Beyond the Wall because I worked so hard on the biomes!! And don't you want to log a highscore?* * *Sometimes, I worked on the file by forking it and editing the fork. I then copied and pasted it back into the original. I deleted some forks to make more room in my repl. I swear I used!* * *I used this file a lot to change the data that is held for the accounts. It was necessary when the new developments in the game required more data to be stored.* * *Of course I really hope you enjoy my game :)* * *I had to restore the latest backup because the storage got full and had to delete itself. I'm really sorry anyone lost their data. I should've written an exception for this but I didn't think about that before the deadline. Everything should be working now though. *I recommend playing in a new tab*
posted by AmeliaBlackwell (582) 2 months ago
Three Ways
Hello ! This is my three ways game. You can move the ball with k, l, and m or arrows. Press enter to play and retry. It's better to play in a new tab. I hope you will enjoy it. I'm still working on it, so it's not finished. I will add a system to change the size of the game on the screen, change the menu screen, and add a config to move with the arrows. You can tell me if you find bugs or things to improve. __If the screen is oversized, you can go to this link :__ You enjoyed the game ? Don't forget to upvote ! Now available : gold rush ! Go on the paddle to earn gold ! Have fun ! (Sorry for my bad English, this game comes from France ;)
posted by Equation (165) 2 months ago
Here is my entry for the Game Jam - Swing! (yes, you have to shout it) The gist is pretty simple - you swing around using a grappling hook and you must avoid dying. Don't touch the red blocks and don't get shot by a Turret (duh). Play through the Levels or enter the Arena and try to survive. The way the game relates to the theme of Cash is.. uh.. you get to keep your cash because this game is free! For the best experience, open this link in a new tab: Full DevLog: version 4.2 - current (17.04.2019) - added guided missiles - added rope block wrapping - added level 4 - added explosion recoil - changed turrets appearance - added idle turret animation - added arena menu display turret behaviour version 4.1 (13.04.2019) - added practice mode - altered arena to account for easy winning strategies version 4.0 (12.04.2019) - added explosions - added super predictive turrets - added arena survival mode - added level 3 - redesigned menus - got rid of title card animation - added bouncy bullets - added death animation version 3.0 (05.04.2019) - added a main menu - added buttons - changed appearance of predictive turrets - made level 2 final challenge easier - added peak text version 2.0 (30.03.2019) - added level 2 - added turrets - improved hook sticking mechanic - changed controls (again) - optimized forces (jump strength, friction, drag) - added predictive aiming - removed 3 challenges from level 1 version 1.2 (23.03.2019) - added title card - added safe area at beginning - added checkpoint text version 1.1 (23.03.2019) - added 3 more challenges (total now 13) - made controls more intuitive - added checkpoints
posted by MatthewStirling (100) 2 months ago
👮Cops And Robbers💰
# Welcome to Cops And Robbers! ![image]( This game was created as a last minute project for Game Jam, as the creator heard about it last minute. He is a Freshman, and has been using REPL since the 7th grade. ## What is it? It is a simplistic game in which you are maneuvering a single robber through a building, collecting coins, while dodging cops, lasers, and spikes. ## How do I use it? Simple. Use WASD or the arrow keys to maneuver the robber, P to pause and R to restart. (Restarting won't affect your score) Also, you can use Esc to exit, as well as the X on the window. Remember that before you can play, you have to sign up or login with a username or code to save your status. (The game window won't open until you do.) ## What's the story? The Robber is a man named Eric Lee who was fired from his job for speaking against his boss, who was illegally ripping off customers. Meanwhile, his daughter is in a critical condition at the hospital, and he cannot afford to buy medicine. So, against his conscience, he decides to rob his old company. ## Is it done? No! Again, this was last minute, so the developer had no time to add important things, like a story. Hopefully in the future, he will finish and submit it, maybe for a 2nd Game Jam. ## Best way to play? Using a normal Python 3 interpreter and Pygame. While the REPL online Pygame system is very good, this game has a slow frame rate on the browser. Also, on REPL, don't use the .run link. Pygame doesn't work there. Instead, drag the borders to make it bigger. ## Where to play? Right [Here](!
posted by Benny_3 (47) 1 month ago
Goblin Hunter
Hello! This is the game I created for the game jam: Goblin Hunter. There are 2 players, the idea is to hunt (touch) the goblins that appear on the map, first to 20 points win! Player 1 moves with the arrow keys, and the Player 2 with WASD. Feel free to give feedback, if you want, you can look at the source code, I added comments so it's easier to understand. I recommend playing in a new tab/window.
posted by Luisfetoga (116) 2 months ago
See more posts
Learn to Code via Tutorials on
LLC GOLANG: Web apps & structs (Videos 5+6)
## Hi everyone! This week, we'll focus on: * [Creating a simple web app]( * [Structs]( **Weekly Quiz:** Quiz yourself on last week's concepts [here]( ). This week's quiz is self-grading, so there's... 🥁🥁🥁 no due date! If you completed last week's quiz, you should have received your scores tonight, Tuesday, May 14th. **Next week's quiz** By Sunday, 5/19, please make sure you post your new quiz questions below. Please only include items covered in videos 1-6. 'Til next week, friends!
posted by katyadee (436) 8 days ago
🌚🕶 How to Enable Site-Wide Dark Theme 🕶🌚
# Site-Wide Dark Theme Do you like not being blinded while browsing Well me neither! ![Repl talk on dark theme]( *** First, you might not have the editor dark theme enabled, so make sure you enable that. 1. Click the settings button at the left of the editor screen. ![Settings Button]( 2. Find the theme dropdown, and select *dark* ![theme dark]( *** Now that you have the editor dark theme enabled, we will enable the site-wide dark theme. 1. Download Tampermonkey for [Chrome]( or [Firefox]( 2. Choose a theme from [the list of themes]( or [create your own]( 3. Click the `install` button. 4. Upvote and post a comment on this tutorial. 5. Profit!
posted by mat1 (2034) 18 days ago
# What is a bookmarklet? A bookmarklet is similar to an extension, but is used by clicking a bookmark. According to wikipedia: > A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. Bookmarklets are unobtrusive JavaScripts stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. Bookmarklets are usually JavaScript programs. Regardless of whether bookmarklet utilities are stored as bookmarks or hyperlinks, they add one-click functions to a browser or web page. When clicked, a bookmarklet performs one of a wide variety of operations, such as running a search query or extracting data from a table. For example, clicking on a bookmarklet after selecting text on a webpage could run an Internet search on the selected text and display a search engine results page. # Create a bookmarklet Creating a bookmarklet is easy. (If you do know how to create a bookmark. If not read [Creating A Bookmark]( ) Let's create a simple example: First, create a bookmark. As for the title of the bookmark, name it “Hello World”. Instead of keeping the url of the page as the bookmark type `javascript:alert(‘Hello World!’)`. There! Click save or whatever it is in your search engine. And click the bookmark. You should have an alert message saying “Hello World!” appear! To run js in a bookmark, you need to have the `javascript:` prefix before it. You can only type one line so make sure to use your semicolons! In addition, you **can not use double quotes**. The search engine saves the bookmark in code that looks something like this: ```html <a href="javascript:alert(‘Hello World!’)">Hello World</a> ``` If you use double quotes it looks like: ```html <a href="javascript:alert(“Hello World!”)”>Hello World</a> ``` And causes an error. If you have multiple lines, create an anonymous function: `javascript:(function(){ var x=prompt(‘Hi say something:’); alert(‘You said: ’ + x); })()` Notice there are NO double quotes. Let's go over some examples: Google Search: `javascript:(function(){''+prompt('Google Search:', '').split(' ').join('+'), '', 'width=800,height=500,left=10,top=10,scrollbar=yes');})();` The above example opens up a new window with a search query of your input! Feel free to copy any of these or the ones listed below. Calculator: `javascript:(function(){var evl,expr=prompt('Formula...','');with(Math)try{evl=parseFloat(eval(expr));if(isNaN(evl)){throw Error('Not a number!');}prompt('Result of '+expr+':',evl)}catch(evl){alert(evl);}})();` @JSer ‘s Rolling Sky: (Thanks for creating such an awesome game!) `'', '', 'top=15,left=15,scrollbar=yes,width=500,height=600')` **Thank you for reading! Please upvote and comment your own bookmarklets. I’ll add a community creations section! I hope i get a content creator tag for this 😀 **
posted by PYer (1851) 20 days ago
🚀 A Starter Guide to Pygame 📀
# 🚀 A Starter Guide to Pygame 📀 Pygame is an open-source library for making graphical applications with Python. Learn more about it on the official [website]( This tutorial is intended to help you setup a very basic Pygame interface. It's for Python beginners or people who want to quickly bootstrap a Pygame project. Find more about's GFX public beta announcement [here]( So let's get started! We're going to be building a simple screen saver. The final result will look like the following ![programProgress4]( ## Starting out When creating a new project, be sure to select "PyGame" when creating a project. ![image]( Now we're ready to start writing some code! ## Painting the Screen Red 🎨 First, we're importing Pygame and initializing all the imported pygame modules with [`pygame.init()`]( Second, we're declaring `width` and `height` variables that represent the size of the screen. Third, we're setting `backgroundColor` to a tuple of 3 elements that represent the RGB numbers. Fourth, `screen` is a display Surface, or an initialized window or screen for display with the [`set_mode()`]( method. Lastly, in the infinite loop, we're filling the screen to the `backGroundColor` and updatiang the display Surface to the screen. In other words [`pygame.display.flip()`]( "refreshes" the screen with changes you made to the grahpics. ```python import pygame pygame.init() width, height = 800, 600 backgroundColor = 255, 0, 0 screen = pygame.display.set_mode((width, height)) while True: screen.fill(backgroundColor) pygame.display.flip() ``` So, we get a red background! ![programProgress1]( ## Adding the DVD Right before you while loop, import an image of your DVD. Feel free to use the same image I used, in the repl below. ```python dvdLogo = pygame.image.load("dvd-logo-white.png") ``` Then, create a rectangle from the Surface, or from the image you just loaded with [`get_rect()`]( ```python dvdLogoRect = dvdLogo.get_rect() ``` Now, inside of the `while` loop (after filling the background color), "map" the imported image to the `dvdLogoRect` rectangle using the [`blit()`]( method. That way, the image stays inside of the invisible `dvdLogoRect` rectangle. ```python screen.blit(dvdLogo, dvdLogoRect) ``` Now, we get a DVD! ![programProgress2]( ## Moving the DVD Logo To move the DVD logo, simply use `move()` by a speed: ```python dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed) ``` Make sure you also declare and initialie dvdLogoSpeed at the top of the file. `dvdLogoSpeed[0]` represents the speed in the `x` direction. ```python dvdLogoSpeed = [1, 1] ``` Finally, I added a `time.sleep(10 / 1000)` so the logo moves slower. So my code ended up looking like ![programProgress3]( The DVD logo *will* move off the screen because there is no bouncing. To implement a check for bouncing, add the following: ```python if dvdLogoRect.left < 0 or dvdLogoRect.right > width: dvdLogoSpeed[0] = -dvdLogoSpeed[0] if < 0 or dvdLogoRect.bottom > height: dvdLogoSpeed[1] = -dvdLogoSpeed[1] ``` The `.left` and `.right` properties don't seem to be [documented](, but it's implied that `.left` measures the distance from the left part of the `dvdLogoRect` Rect (rectangle) to the left part of the `screen.` And so on and so fourth for `.right`, `.top`, and `.bottom`. Here is the final result ![programProgress4]( Now let me know when the logo hits the corner!
posted by eankeen (458) 2 months ago
(Python) Quine-McCluskey Algorithm
# (Python) Quine-McCluskey Algorithm ## What is it? The Quine-McCluskey Algorithm is an algorithm developed by Willard Quine in the late 1950s which was then improved upon by Edward McCluskey. The purpose of this algorithm is to take the results of a logical expression or a boolean algebraic expression and simplify it to it's simplest form. ## Examples * `(p ^ q ^ r) v (p ^ q ^ ~r) v (p ^ ~q ^ ~r)` simplifies to `p ^ (q v ~r)` * `a or (a and b)` simplifies to `a` ## Requirements * Basic Knowledge of Python * Power Sets * Recursion ___ ## Quine-McCluskey Algorithm Now first, in order to best explain the Quine-McCluskey Algorithm, we are going to set up an example of a modified truth table that will show you the values that will be used for this example. ### Grouping Let's say we have a logical expression that evaluates per the function *f(a, b, c, d) =* Σ *m(0, 4, 5, 7, 8, 11, 12, 15)* Now what this means is that whenever the binary equivalents of the variables make the decimal value equal to any of these values, the expression is evaluating to true: | a | b | c | d | bits | decimal | |:-:|:-:|:-:|:-:|:----:|:-------:| | 0 | 0 | 0 | 0 | `0000` | 0 | | 0 | 1 | 0 | 0 | `0100` | 4 | | 0 | 1 | 0 | 1 | `0101` | 5 | | 0 | 1 | 1 | 1 | `0111` | 7 | | 1 | 0 | 0 | 0 | `1000` | 8 | | 1 | 0 | 1 | 1 | `1011` | 11 | | 1 | 1 | 0 | 0 | `1100` | 12 | | 1 | 1 | 1 | 1 | `1111` | 15 | Now we group the bits by however many 1's there are in the binary value. Don't worry about the `used` column just yet. I will explain that a few steps down: | # of 1's | decimal | a | b | c | d | used | |:--------:|:-------:|:-:|:-:|:-:|:-:|:----:| | 0 | 0 | 0 | 0 | 0 | 0 | yes | | 1 | 4 | 0 | 1 | 0 | 0 | yes | | | 8 | 1 | 0 | 0 | 0 | yes | | 2 | 5 | 0 | 1 | 0 | 1 | yes | | | 12 | 1 | 1 | 0 | 0 | yes | | 3 | 7 | 0 | 1 | 1 | 1 | yes | | | 11 | 1 | 0 | 1 | 1 | yes | | 4 | 15 | 1 | 1 | 1 | 1 | yes | Now, each of these values becomes a minterm. What a minterm is is just something that holds information about where a decimal value, or values, evaluates to true and what binary value it holds. When we combine them, we only want to look for where there is a 1-bit difference in 2 minterms. The reason we do that is because we want to remove the bits that don't matter. For example, let's say we compare minterms 0 and 4. We see that there is only a 1-bit difference between them at the `b` variable. To put this into logical expression terms, this is really what we're doing: | Expression | Action | |:----------:|:------:| | `(~a ^ ~b ^ ~c ^ ~d) v (~a ^ b ^ ~c ^ ~d)` | Given | | `(~a ^ ~c ^ ~d) ^ (~b v b)` | Distributive Law | | `(~a ^ ~c ^ ~d) ^ t` | Identity Law | | `(~a ^ ~c ^ ~d)` | Tautology | Now, as you can see above, we were able to take out a common factor of `(~a ^ ~c ^ ~d)` and leave behind `(~b v b)`. In logic, `(~b v b)` will always be true no matter the value of `b`. This is the reason we want to compare minterms that have only a 1-bit difference. ### Comparing After we compare each term in adjacent groups with one another, we get another table that looks like the following table. There is an extra column to keep track of whether or not we used the minterm specified when we try combining the minterms. Since we used all of the minterms in the earlier table, we know that we don't have to remember to use any of them. If we don't use a minterm, then that minterm must be one of the prime implicants, which is what is used to generate the simplified logical expression: | groups | minterm | a | b | c | d | used | |:------:|:-------:|:-:|:-:|:-:|:-:|:----:| | 0-1 | m(0, 4) | 0 | - | 0 | 0 | yes | | | m(0, 8) | - | 0 | 0 | 0 | yes | | 1-2 | m(4, 5) | 0 | 1 | 0 | - | no | | | m(4, 12) | - | 1 | 0 | 0 | yes | | | m(8, 12) | 1 | - | 0 | 0 | yes | | 2-3 | m(5, 7) | 0 | 1 | - | 1 | no | | 3-4 | m(7, 15) | - | 1 | 1 | 1 | no | | | m(11, 15) | 1 | - | 1 | 1 | no | Now that we've compared every term in adjacent groups with one another, we can move onto doing the same step again which will get us with 2 values. ### Comparing (continued) | groups | minterm | a | b | c | d | used | |:------:|:-------:|:-:|:-:|:-:|:-:|:----:| | 0-1-1-2 | m(0, 4, 8, 12) | - | - | 0 | 0 | no | | | m(0, 8, 4, 12) | - | - | 0 | 0 | no | Now as you can see, these 2 minterms are actually the same exact minterm. Just because the order of the numbers is different doesn't make them any different in reality. Therefore, the order of the values in the minterms doesn't actually matter when combining them. However, we must make sure that minterms `m(0, 4)`, `m(0, 8)`, `m(4, 12)`, and `m(8, 12)` are used which helps us simplify the expression. ### Prime Implicant Table From the minterms that aren't used, we create a table with the variables on the left and the values from the function at the beginning on the right. When we go through the unused minterms, we put `X`'s in the columns that the minterm holds values for. For example `m(0, 4, 8, 12)` should have `X`'s in columns 0, 4, 8, and 12. That part is pretty self-explanatory. | a | b | c | d | 0 | 4 | 5 | 7 | 8 | 11 | 12 | 15 | |:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:--:|:--:|:--:| | | | ~c| ~d| X | X | | | X | | X | | | ~a| b | ~c| | | X | X | | | | | | | ~a| b | | d | | | X | X | | | | | | | b | c | d | | | | X | | | | X | | a | | c | d | | | | | | X | | X | Once we have this table setup, we want to look for what is known as the essential prime implicants which are prime implicants that need to exist in order for the expression to evaluate to true at the values specified earlier. To find these essential prime implicants, we look for the numbers who have only 1 `X` in the entire column. In our case, those columns are 0, 8, 11, and 12. Once we find those essential prime implicants, we go to the row that contains that `X` and add it to our final expression. When we cover an expression from a row, we then ignore all the `X`'s that exist in the rest of the column. For example, since we see that 0, 8, and 12 are essential values, we add `(~c ^ ~d)` to the final expression and cross out all the columns that minterm covers. The reason we have `(~c ^ ~d)` as the expression for this minterm is because the binary equivalent is `--00`. Wherever there is a hyphen (`-`), we do not put the variable that corresponds to it. Whenever there is a `0`, we put a NOT (`~`) operator in front of the variable that corresponds to it. Whenever there is a `1`, we just put the variable itself. Expression: `(~c ^ ~d)` | a | b | c | d | 0 | 4 | 5 | 7 | 8 | 11 | 12 | 15 | |:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:--:|:--:|:--:| | | | ~c| ~d| ~~X~~ | ~~X~~ | | | ~~X~~ | | ~~X~~ | | | ~a| b | ~c| | | ~~X~~ | X | | | | | | | ~a| b | | d | | | X | X | | | | | | | b | c | d | | | | X | | | | X | | a | | c | d | | | | | | X | | X | Now we have another essential value at column 11 so we need to add `(a ^ c ^ d)` to the final expression. Expression: `(~c ^ ~d) v (a ^ c ^ d)` | a | b | c | d | 0 | 4 | 5 | 7 | 8 | 11 | 12 | 15 | |:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:--:|:--:|:--:| | | | ~~~c~~| ~~~d~~| ~~X~~ | ~~X~~ | | | ~~X~~ | | ~~X~~ | | | ~a| b | ~c| | | ~~X~~ | X | | | | | | | ~a| b | | d | | | X | X | | | | | | | b | c | d | | | | X | | | | ~~X~~ | | ~~a~~ | | ~~c~~ | ~~d~~ | | | | | | ~~X~~ | | ~~X~~ | Since we do not have any more essential prime implicants, we want to find which implicant(s) will create the simplest expression and covers the most values. In this case, we can see that `m(5, 7)` will cover the other 2 remaining columns: Expression: `(~c ^ ~d) v (a ^ c ^ d) v (~a ^ b ^ d)` | a | b | c | d | 0 | 4 | 5 | 7 | 8 | 11 | 12 | 15 | |:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:--:|:--:|:--:| | | | ~~~c~~| ~~~d~~| ~~X~~ | ~~X~~ | | | ~~X~~ | | ~~X~~ | | | ~a| b | ~c| | | ~~X~~ | ~~X~~ | | | | | | | ~~~a~~| ~~b~~ | | ~~d~~ | | | ~~X~~ | ~~X~~ | | | | | | | b | c | d | | | | ~~X~~ | | | | ~~X~~ | | ~~a~~ | | ~~c~~ | ~~d~~ | | | | | | ~~X~~ | | ~~X~~ | ### Final Expression Now, since we have covered every value in the prime implicant chart, the final expression is `(~c ^ ~d) v (a ^ c ^ d) v (~a ^ b ^ d)`. To put that into perspective, the original expression was `(~a ^ ~b ^ ~c ^ ~d) v (~a ^ b ^ ~c ^ ~d) v (~a ^ b ^ ~c ^ d) v (~a ^ b ^ c ^ d) v (a ^ ~b ^ ~c ^ ~d) v (a ^ ~b ^ c ^ d) v (a ^ b ^ ~c ^ ~d) v (a ^ b ^ c ^ d)`. Now let's move onto the code that actually does all of this. ___ ## Quine-McCluskey Algorithm in Code For this algorithm, I've created only 2 classes that do all of the hard work: * The `Minterm` class, which holds the values and the binary value of the minterm * The `QuineMcCluskey` class which actually solves for the simplified form of an expression ### `Minterm` class The `Minterm` class is actually quite simple and doesn't hold much at all. First we have the basic built-in methods: ```py class Minterm: def __init__(self, values, value): self._values = values self._value = value self._used = False self._values.sort() def __str__(self): values = ", ".join([str(value) for value in self._values]) return f"m({values}) = {self._value}" def __eq__(self, minterm): if type(minterm) != Minterm: return False return ( self._value == minterm._value and self._values == minterm._values ) ``` The `__str__` method is there to print out a specific minterm nicely in the form of `m(0, 4, 8, 12) = --00` Next, we have some basic getters and setters that are used in the `QuineMcCluskey` portion of the code: ```py def get_values(self): """Returns all the implicants that this minterm covers. """ return self._values def get_value(self): """Returns the bit values ('-010', '1010', etc.) for this minterm. """ return self._value def use(self): """Keeps track of when this minterm is "used" in a comparison. """ self._used = True def used(self): """Returns whether or not this minterm was used. """ return self._used ``` These are all both documented and pretty self-explanatory so I don't think I need to really go over them much. This next (and last) portion of code for the `Minterm` class is used when we combine minterms in the algorithm: ```py def combine(self, minterm): """Combines this minterm with the specified minterm if possible. """ # Check if this minterm is the same as the one trying to be combined with if self._value == minterm._value or self._values == minterm._values: return None # Keep track of the amount of difference between the value of the minterm # and also keep track of the resulting string diff = 0 result = "" # Iterate through all the bit values for char in range(len(self._value)): # Check if this minterm and the combined minterm have a bit difference if self._value[char] != minterm._value[char]: diff += 1 result += "-" # There is no difference else: result += self._value[char] # The difference is greater than 1, these minterms cannot be combined if diff > 1: return None return Minterm(self._values + minterm._values, result) ``` Now as you can see, this code will return a new `Minterm` object if 2 minterms can be combined with one another. For example, what this does is take a minterm, say `m(0, 4) = 0-00`, and another minterm, say `m(8, 12) = 1-00`, and it will combine them together which then becomes `m(0, 4, 8, 12) = --00`. That is really all that needs to be done for the `Minterm` class. Now let's move on to the `QuineMcCluskey` class which has all the meat of the code. ## `QuineMcCluskey` class The `QuineMcCluskey` class has the majority of the functions that create an initial group, combine minterms from adjacent groups, solves the function, and then generates the function into a human-readable format. First, we need the basic constructor and a function that gets the binary equivalent of a decimal value: ```py class QM: """A class to handle processing the Quine-McCluskey Algorithm. """ def __init__(self, variables, values): self._variables = variables self._values = values def __get_bits(self, value): """Returns the binary digit for the specified value. """ # Pad the result with extra 0's at the beginning to match how many variables # there are being used return bin(value)[2:].rjust(len(self._variables), "0") ``` The reason we need the `__get_bits` function is to be able to get the binary equivalent of the values where the function evaluates to true. For example, 4 is `0100`, 5 is `0101`, and 7 is `0111` in our example. It's important to pad extra 0's to the beginning of the value to match that of the number of variables in the expression. #### The Initial Group Before beginning the process of getting a list of unused prime implicants, we need to create an initial group where each binary value is matched up with how many 1's the binary value has. ```py def __initial_group(self): """Creates the initial grouping for the bits from the values given to the Quine-McCluskey Algorithm """ # Keep track of groups by 2-dimensional list groups = [] for count in range(len(self._variables) + 1): groups.append([]) # Iterate through values for value in self._values: # Count number of 1's in value's bit equivalent count = self.__get_bits(value).count("1") # Add count to proper group groups[count].append(Minterm([value], self.__get_bits(value))) return groups ``` In essence, what this function does is create the groups of minterms based off of how many 1's there are in the binary values for the decimal values. In the case of our function from earlier, the list would look something like this: ```py groups = [ ['m(0) = 0000'], # 0 1's ['m(4) = 0100', 'm(8) = 1000'], # 1 1's ['m(5) = 0101', 'm(12) = 1100'], # 2 1's ['m(7) = 0111', 'm(11) = 1011'], # 3 1's ['m(15) = 1111'] # 4 1's ] ``` #### Prime Implicants The next step is to get all the prime implicants that could possibly cover the expression. Like [mentioned earlier](#comparing) in the explanation of the Quine-McCluskey Algorithm, to get the prime implicants, we must compare every term in one group with every term in an adjacent group. That is what the following code does: ```py def __get_prime_implicants(self, groups = None): """Recursively gets the prime implicants for the expression. """ # Get initial group if group is None if groups == None: groups = self.__initial_group() # If there is only 1 group, return all the minterms in it if len(groups) == 1: return groups[0] # Try comparing the rest else: unused = [] comparisons = range(len(groups) - 1) new_groups = [[] for c in comparisons] for compare in comparisons: group1 = groups[compare] group2 = groups[compare + 1] # Compare every term in group1 with every term in group2 for term1 in group1: for term2 in group2: # Try combining it term3 = term1.combine(term2) # Only add it to the new group if term3 is not None # term3 will only be None if term1 and term2 could not # be combined if term3 != None: term1.use() term2.use() if term3 not in new_groups[compare]: new_groups[compare].append(term3) # Get list of all unused minterms for group in groups: for term in group: if not term.used() and term not in unused: unused.append(term) # Add recursive call for term in self.__get_prime_implicants(new_groups): if not term.used() and term not in unused: unused.append(term) return unused ``` The first `if` statement is pretty simple to comprehend. All it's checking for is whether or not a parameter is given, which is used in the recursive call, and setting it to be the initial group if it is not given. The next `if` statement is the base case of this recursive function. If there is only one group left, then only the prime implicants in that function will cover the expression given. The `else` statement handles everything else about getting prime implicants. First, we set up which minterms are unused in the comparisons. Then we want to only compare groups that are adjacent to one another. So if there are 5 groups, we only want to compare group 0 and 1, 1 and 2, 2 and 3, and 3 and 4. That's only 4 comparisons. Finally, we want to keep track of these new groups once we compare minterms. When we loop through the comparisons, we only go from the first group to the second to last group or else we would have an `IndexError` when the `group2 = groups[compare + 1]` line of code came up. Once we loop through each minterm in each group, we try to combine the 2 minterms. If the 2 minterms cannot be combined, nothing will happen. However, if the 2 minterms *can* be combined, we want to keep track of using the minterm. Then, we make sure that the resulting minterm does not already exist in the new group that it belongs to. Once we finish with comparing minterms, we want to keep track of which minterms were not used, if there were any. Then we make the recursive call which uses the new list of groups to compare every minterm again. Each time the `__get_prime_implicants` function is run, it returns a list of unused minterms. At the end of the recursive call, we get a total list of all the minterms which become the prime implicants. #### Power Set A power set, for those who don't understand what it is, is just a set of combinations of an existing set. For example, let's take a set to be `{1, 2, 3}`. The power set would be, `{{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}`. The reason we need to understand what a power set is is because after the essential prime implicants are found (which will be explained right after this section), the power set function will determine which remaining implicants cover the remainder of the expression and which set has the fewest implicants. ```py def __power_set(self, values, prime_implicants): """Creates a power set of all valid prime implicants that covers the rest of an expression. This is used after the essential prime implicants have been found. """ # Get the power set of all the prime_implicants prime_implicants = list(prime_implicants) power_set = [] # Iterate through decimal values from 1 to 2 ** size - 1 for i in range(1, 2 ** len(prime_implicants)): current_set = [] # Get the binary value of the decimal value bin_value = bin(i)[2:].rjust(len(prime_implicants), "0") # Find which indexes have 1 in the bin_value string for index in range(len(bin_value)): if bin_value[index] == "1": current_set.append(prime_implicants[index]) power_set.append(current_set) # Remove all subsets that do not cover the rest of the implicants new_power_set = [] for subset in power_set: # Get all the values the set covers temp_values = [] for implicant in subset: for value in implicant.get_values(): if value not in temp_values and value in values: temp_values.append(value) temp_values.sort() # Check if this subset covers the rest of the values if temp_values == values: if len(subset) < len(minSet): minSet = subset return minSet ``` There are a few things that go on in this function. First, the initial power set is created from the prime implicants given through the parameter. After that is done, we then iterate over each set to determine if the set contains minterms that cover the rest of the expression. When the smallest subset is found, a variable, `minSet`, is updated to keep track of the smallest set so that at the end, the smallest set is returned which includes the final prime implicant, or implicants, that cover the rest of the expression. #### Solving Now let's get on to actually *solving* the expression. ```py def __solve(self): """Solves for the expression returning the minimal amount of prime implicants needed to cover the expression. """ # Get the prime implicants prime_implicants = self.__get_prime_implicants(self.__initial_group()) # Keep track of values with only 1 implicant # These are the essential prime implicants essential_prime_implicants = [] values_used = [False] * len(self._values) for i in range(len(self._values)): value = self._values[i] uses = 0 last = None for minterm in prime_implicants: if value in minterm.get_values(): uses += 1 last = minterm if uses == 1 and last not in essential_prime_implicants: for v in last.get_values(): values_used[self._values.index(v)] = True essential_prime_implicants.append(last) # Check if all values were used if values_used.count(False) == 0: return essential_prime_implicants # Keep track of prime implicants that cover as many values as possible # with as few variables as possible prime_implicants = [prime_implicant for prime_implicant in prime_implicants if prime_implicant not in essential_prime_implicants] # Check if there is only one implicant left (very rare but just in case) if len(prime_implicants) == 1: return essential_prime_implicants + prime_implicants # Create a power set from the remaining prime implicants and check which # combination of prime implicants gets the simplest form return essential_prime_implicants + self.__power_set([ self._values[index] for index in range(len(self._values)) if not values_used[index] ], prime_implicants) ``` The basic function of the `solve` function is to: 1. Get a list of prime implicants ```py # Get the prime implicants prime_implicants = self.__get_prime_implicants(self.__initial_group()) ``` 2. Find the essential prime implicants ```py # Keep track of values with only 1 implicant # These are the essential prime implicants essential_prime_implicants = [] values_used = [False] * len(self._values) for i in range(len(self._values)): value = self._values[i] uses = 0 last = None for minterm in prime_implicants: if value in minterm.get_values(): uses += 1 last = minterm if uses == 1 and last not in essential_prime_implicants: for v in last.get_values(): values_used[self._values.index(v)] = True essential_prime_implicants.append(last) # Check if all values were used if values_used.count(False) == 0: return essential_prime_implicants ``` The final `if` statement in this block of code will determine if all the essential prime implicants are the only prime implicants needed to cover the expression. 3. Use the `__power_set` function to find the final prime implicant(s) that cover the expression and return it along with the essential prime implicants ```py # Keep track of prime implicants that cover as many values as possible prime_implicants = [prime_implicant for prime_implicant in prime_implicants if prime_implicant not in essential_prime_implicants] # Check if there is only one implicant left (very rare, if not impossible, but just in case) if len(prime_implicants) == 1: return essential_prime_implicants + prime_implicants # Create a power set from the remaining prime implicants and check which # combination of prime implicants gets the simplest form return essential_prime_implicants + self.__power_set([ self._values[index] for index in range(len(self._values)) if not values_used[index] ], prime_implicants) ``` The purpose of reassigning the `prime_implicants` list is to remove all the prime implicants that are in that list that are *also* an essential prime implicant. #### Getting the Expression The final part of this algorithm is to actually return an expression that is readable to the human eye. ```py # Get the prime implicants and variables prime_implicants = self.__solve() # Check if there are no prime_implicants; Always False if len(prime_implicants) == 0: return "0" if len(prime_implicants) == 1: if prime_implicants[0].get_value().count("-") == len(self._variables): return "1" result = "" # Iterate through prime implicants for j in range(len(prime_implicants)): implicant = prime_implicants[j] # Iterate through all bits in the implicants value for i in range(len(implicant.get_value())): if implicant.get_value()[i] == "0": result += "NOT " if implicant.get_value()[i] != "-": result += self._variables[i] if implicant.get_value().count("-", i + 1) < len(implicant.get_value()) - i - 1 and implicant.get_value()[i] != "-": result += " AND " if j < len(prime_implicants) - 1: result += " OR " return result ``` The basis of the `get_function` function is to find the prime implicants from the `__solve` function, iterate through the prime implicants and their binary values, and then create proper variables (with/without a NOT operator). If there are no prime implicants received after the `__solve` function is called, then the expression is always false. Therefore, a `0` is returned. If there is only 1 prime implicant that has a binary value of all hyphens (`-`), then the expression will always be true no matter what. #### Conclusion To conclude this tutorial, I went over the basics of the Quine-McCluskey Algorithm, how to do it by hand, and how to adapt it to code. If you want to see the simplifier in action, you can go to I also wrote it in [Java]( and [Node.js]( If you have any suggestions or see any issues, please let me know that way I can fix it! If you find any bugs in adaptation of the Quine-McCluskey Algorithm, *definitely* let me know either by leaving a comment, pinging me in's Discord Server, or pinging me in my own [Discord Server](
posted by FellowHashbrown (37) 14 days ago
See more posts
Share your repls and programming experiences
Rules for Posting - Read me!
Some rules and guidelines to keep in mind as you share your great work on our boards: 1 - Be kind and courteous to others 2 - Make sure that any feedback you provide is constructive. 3 - Outside links are allowed, but you must provide the source. Ideally, things that you post will have been created on 4 - Avoid posting overly promotional material - the focus is, and always will be, a programming, learning, and collaborative community. :) 5 - Don't spam! Keep things SFW (Safe For Work). We may revoke your access to these boards if you are found to be in violation of any of these rules. Feel free to ask clarifying questions. Last updated 7/10/18 12:09 PST
posted by timmy_i_chen (869) 11 months ago
WebCraft - A Online Minecraft!
MINECRAFT! IN A WEB BROWSER! AWESOME!!! It's a fun, simple game that you can do many things in! Just try to explore!
posted by HENRYMARTIN4 (22) 2 days ago
The Best Way To Code (Joke)
How to write code in the most cursed way. Using C++, I've renamed every token and keyword necessary to print "Hello, World!\n" using different variations of the word "yeet".
posted by Edgod (28) 2 days ago
Send Nukes 1.2.1
New Version is out with a factory and a lab and some bugfixes are added to play now for free!
posted by Animator282 (20) 4 days ago
Conversation Simulator V1.0
A simple conversation simulator. Version 1. It has taken some time to code. Note me on errors please!
posted by Eyseedoubleyou (3) 22 hours ago
See more posts