Collection of programming ideas and challenges - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: Collection of programming ideas and challenges (/thread-278.html) |
Collection of programming ideas and challenges - metulburr - Oct-04-2016 This is not all my ideas, i more or so collected them from time to time when i cant think of anything to code. Reading through them though will jog my memory of something i wanted to code at one time or another. Feel free to add to the list. IT would be cool to have a massive list of ideas when you have writer's block. links to ideas... Project Euler Python Challenge https://www.hackerrank.com/domains/pytho...troduction. https://www.reddit.com/r/dailyprogrammer/ <- Hundreds of reddit threads of ideas Python Projects 2020 General Ideas
Beginner 1) make a text-based menu system. An Inventory. Buy items from menu, increase inventory, decrease 'store' inventory. Sell items from menu, decrease inventory, increase 'store' inventory. 2) make a program to encrypt/decrypt a string 3) make a word-guess/number-guess game 4) find a web site and extract data from the HTML with the program to give you auto-updates 5) get the first 3 results of a google search based on user input, and display the title and link 6) create a program to search all subdirectories for a specific file extension and copy those files to a different directory. 7) create a program to check your public IP address 8) create a program to email yourself 9) create a program to download the newest file of something automatically 10) make a terminal progress bar 11) make a program to change terminal color for specific words 12) make a program to check your system information 13) make a program that saves input to a file, and automatically saves a time stamp for the time it was saved 14) create a tutorial for the language you are learning. It will help teach it to yourself. 15) make a notification program. For every month/week/day/hour/minute it notifies you of something 16) get html from cragislist,. parse, and post it on your facebook wall for updated info regarding the latest Intermediate 1) make a web browser 2) make a code snippet program (terminal or GUI) to collect snippets of code you come across while programming. From a database, save/load a key to save/get the snippet desired. 3) Make an IRC bot 4) build a search engine 5) build GPS Direction from point A to point B Specific Ideas
Numbers Find PI to the Nth Digit – Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. Fibonacci Sequence – Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. Prime Factorization – Have the user enter a number and find all Prime Factors (if there are any) and display them. Next Prime Number – Have the program find prime numbers until the user chooses to stop the asking for the next one. Find Cost of Tile to Cover W x H Floor – Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. Mortgage Calculator – Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan. Change Return Program – The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. Binary to Decimal and Back Converter – Converter to convert a decimal number to binary or a binary number to its decimal equivalent. Calculator – A simple calculator to do basic operators. Make it a scientific calculator for added complexity. Unit Converter (temp, currency, volume, mass and more) – Converts various units between one another. The user enters the type of unit being entered, the type of unit they want to convert to and then the value. The program will then make the conversion. Alarm Clock – A simple clock where it plays a sound after X number of minutes/seconds or at a particular time. Distance Between Two Cities – Calculates the distance between two cities and allows the user to specify a unit of distance. This program may require finding coordinates of the cities like latitude and longitude. Credit Card Validator – Takes in a credit card number of a common credit card vendor (Visa, MasterCard, American Express, Discoverer) and validates it to make sure that it is a valid number (look into how credit cards use a checksum). Tax Calculator – Asks the user to enter a cost and either a country or state tax. It then returns the tax plus the total cost with tax. Dijkstra’s Algorithm – Create a program that finds the shortest path through a graph using its edges. Text Reverse a String – Enter a string and the program will reverse it and print it out. Pig Latin – Pig Latin is a game of alterations played on the English language game. To form the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. Count Vowels – Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. Check if Palindrome – Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” Count Words in a String – Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary. Text Editor – Notepad style application that can open, edit, and save text documents. Add syntax highlighting and other features. RSS Feed Creator – A program which can read in text from other sources and put it in RSS or Atom news format for syndication. Post it Notes Program – A program where you can add text reminders and post them. You can have the program also add popup reminders. Quote Tracker (market symbols etc) – A program which can go out and check the current value of stocks for a list of symbols entered by the user. The user can set how often the stocks are checked and the program can show green up and red down arrows to show which direction the stock value has moved. Guestbook / Journal – A simple application that can be for online that can allow people to add comments or write journal entries. It can allow comments or not and timestamps all entries. Could also be made into a shout box. News Ticker and Game Scores – A program which sits on your desktop and aggregates news and game scores from various sources on the net and scrolls them across the screen on regular intervals. Fortune Teller (Horoscope) – A program that checks your horoscope on various astrology sites and puts them together for you each day. Vigenere / Vernam / Ceasar Ciphers – Functions for encrypting and decrypting data messages. Then send them to a friend. Random Gift Suggestions – Enter various gifts for certain people when you think of them and when its time to give them a gift (xmas, birthday, anniversary) it will randomly pick one and perhaps places you can get it. Text to HTML Generator – Converts text files into web HTML files and stylizes them. Great for making online documentation of standard text documentation. CD Key Generator – Generates a unique key for your applications to use based on some arbitrary algorithm that you can specify. Great for software developers looking to make shareware that can be activated. Regex Query Tool – A tool that allows the user to enter a text string and then in a separate control enter a regex pattern. It will then run the regular expression against the source text and return any matches or flag errors in the regular expression. Networking FTP Program – A file transfer program which can transfer files back and forth from a remote web sever. Get Atomic Time from Internet Clock – This program will get the true atomic time from an atomic time clock on the internet. There are various clocks across the world. Do a search for a list of them. Chat Application (IRC or MSN Style) – Create a chat application that can carry on simple chat rooms like on Internet Relay Chat or a more direct chatting style like MSN. For added complexity, create your own protocol to facilitate this chatting. Fetch Current Weather – Get the current weather for a given zip/postal code. P2P File Sharing App – Create a program like LimeWire, FrostWire, Bearshare, or a torrent style application. Port Scanner – Enter an IP address and a port range where the program will then attempt to find open ports on the given computer by connecting to each of them. On any successful connections mark the port as open. Mail Checker (POP3 / IMAP) – The user enters various account information include web server and IP, protocol type (POP3 or IMAP) and the application will check for email on several accounts at a given interval. Packet Sniffer – A utility program that will read packets coming in and out of the machine along with related information like destination and payload size. Country from IP Lookup – Enter an IP address and find the country that IP is registered in. Whois Search Tool – Enter an IP or host address and have it look it up through whois and return the results to you. Zip / Postal Code Lookup – Enter a zip or postal code and have it return which city/cities that are in that zip code. Remote Login – Create a remote desktop style application which can see and control the remote computer (given you have permissions). It may require the use of your own private network and a second computer to test with. Site Checker with Time Scheduling – An application that attempts to connect to a website or server every so many minutes or a given time and check if it is up. If it is down, it will notify you by email or by posting a notice on screen. Small Web Server – A simple web server that can serve HTML files that contain Javascript and other forms of non-code executing code. Added complexity would be to try and implement streaming video, create a server-side language, or serve up other stream types. Web Bot – An automated program which carries out tasks on the web including checking websites, page scraping, and summarization of data or web posting. Classes Product Inventory Project – Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an inventory class which keeps track of various products and can sum up the inventory value. Movie Store – Manage video rentals and controls when videos are checked out, due to return, overdue fees and for added complexity create a summary of those accounts which are overdue for contact. Airline / Hotel Reservation System – Create a reservation system which books airline seats or hotel rooms charging various rates for particular sections of the plane or hotel. Example, first class is going to cost more than coach. Hotel rooms have penthouse suites which cost more. Keep track of when rooms will be available and can be scheduled. Student Grade Book Application – Keep track of students (with a student class that has their name, average, and scores) in a class and their grades. Assign their scores on tests and assignments to the students and figure out their average and grade for the class. For added complexity put the students on a bell curve. Bank Account Manager - Create a class called “Account” which will be an abstract class for three other classes called “CheckingAccount”, “SavingsAccount” and “BusinessAccount”. Manage credits and debits from these accounts through an ATM style program. Library Catalog – Create a book class with a title, page count, ISBN and whether or not it is checked out or not. Manage a collection of various books and allow the user to check out books or return books. For added complexity generate a report of those books overdue and any fees. Also allow users to put books on reserve. Patient / Doctor Scheduler – Create a patient class and a doctor class. Have a doctor that can handle multiple patients and setup a scheduling program where a doctor can only handle 16 patients during an 8 hr work day. Recipe Creator and Manager – Create a recipe class with ingredients and a put them in a recipe manager program that organizes them into categories like deserts, main courses or by ingredients like chicken, beef, soups, pies etc. Image Gallery – Create an image abstract class and then a class that inherits from it for each image type. Put them in a program which displays them in a gallery style format for viewing. Class to Handle Large Numbers – We know that the basic data types like integer, long, double, and floats only go so far. Create a class that can manage extremely large numbers like those used in space exploration. Chart Making Class / API – Create a class, or a set of classes, that generates bar charts, pie charts, histograms, and scatter plot charts. For added complexity, make this a service where people can connect to a web server, supply information and it returns a chart image for them in gif or jpg format. Shape Area and Perimeter Classes – Create an abstract class called “Shape” and then inherit from it other shapes like diamond, rectangle, circle, triangle etc. Then have each class override the area and perimeter functionality to handle each shape type. Matrix Class – A class to manage matrices. Add, subtract and multiple matrices. Flower Shop Ordering To Go – Create a flower shop application which deals in flower objects and use those flower objects in a bouquet object which can then be sold. Keep track of the number of objects and when you may need to order more. Vending Machine – Create an application which takes money and dispenses various types of candy or other item. The user enters a number and letter sequence, like D9, and have it return an instance of “Item” which of the proper type. Example when they press D9 it will return a type of candy bar which is an instance of Mr GoodBar. Josephus Problem – Create a program which links together various node objects and then every Nth object is removed until you have one object left. This last object is the sole survivor. Look it up on Google under “Josephus Algorithm” Family Tree Creator – Create a class called “Person” which will have a name, when they were born and when (and if) they died. Allow the user to create these Person classes and put them into a family tree structure. Print out the tree to the screen. Threading Create Progress Bar of Download – Create a progress bar for applications that can keep track of a download in progress. The progress bar will be on a separate thread and will communicate with the main thread using delegates. Download Manager – Allow your program to download various files and each one is downloading in the background on a separate thread. The main thread will keep track of the other thread’s progress and notify the user when downloads are completed. Chat Application (remoting style) – Create a chat application which allows you to connect directly to another computer by their IP through the use of remoting and allow your “server” application handle multiple incoming connections. Bulk Thumbnail Creator – Picture processing can take a bit of time for some transformations. Especially if the image is large. Create an image program which can take hundreds of images and convert them to a specified size in the background thread while you do other things. For added complexity, have one thread handling resizing, have another bulk renaming of thumbnails etc. Web WYSIWG (What you see is what you get) Editor – Create an editor online which allows people to move around elements, create tables, write text, set colors etc for web pages without having to know HTML. Think Dreamweaver or FrontPage but for online sites. If you need an example check out the DIC page used to create a post. Web Browser with Tabs – Create a small web browser that allows you to navigate the web and contains tabs which can be used to navigate to multiple web pages at once. For simplicity don’t worry about executing Javascript or other client side code. Page Scraper – Create an application which connects to a site and pulls out all links or images and saves them to a list. For added complexity, organize the indexed content and don’t allow duplicates. Have it put the results into an easily searchable index file. File Downloader – An application which can download various objects on a page including video streams or all files on a page. Great for pages with a lot of download links. Telnet Application – Create an application which can telnet into servers across the internet and run basic commands. Online White Board – Create an application which allows you and friends to collaborate on a white board online. Draw pictures, write notes and use various colors to flesh out ideas for projects. For added complexity try building in picture tubes. Bandwidth Monitor – A small utility program that tracks how much data you have uploaded and downloaded from the net during the course of your current online session. See if you can find out what periods of the day you use more and less and generate a report or graph that shows it. Bookmark Collector and Sorter – An application that you can put online for people to upload bookmarks to, have it sort them, remove duplicates and export the entire list as a Firefox/IE/Safari bookmark file. For added complexity see if you can group the bookmark items into various folders. Password Safe – A program which keeps track of passwords for sites or applications and encrypts them with a key so that no one can read them. Media Player Widget for iGoogle – Create an iGoogle gadget which can play various song lists from your computer as well as share one song daily. Perhaps let people look up which songs you have listened to lately. Text Based Game Like Utopia – Create a simple text based RPG like Utopia where you can create a civilization, gather resources, forge alliances, cast spells and more on a turn based system. See if you can dominate the kingdom. Scheduled Auto Login and Action – Make an application which logs into a given site on a schedule and invokes a certain action and then logs out. This can be useful for checking web mail, posting regular content, or getting info for other applications and saving it to your computer. E-Card Generator – Make a site that allows people to generate their own little e-cards and send them to other people. Can use flash or not. Use a picture library and perhaps insightful mottos or quotes. Content Management System – Create a content management system (CMS) like Joomla, Drupal, PHP Nuke etc. Start small and allow for the addition of modules/addons later. Template Maker – Make a site or application which allows the user to enter in various color codes, elements, dimensions and constructs a template file for a particular application like PHPBB, Invision Board, MySpace, Bebo, etc. CAPTCHA Maker – Ever see those images with letters a numbers when you signup for a service and then asks you to enter what you see? It keeps web bots from automatically signing up and spamming. Try creating one yourself for online forms. If you use PHP, take a look at the image functions of GD. Files Quiz Maker – Make an application which takes various questions form a file, picked randomly, and puts together a quiz for students. Each quiz can be different and then reads a key to grade the quizzes. Quick Launcher – A utility program that allows the user to assign various programs to icons on a toolbar. Then by clicking the buttons they can quickly launch the programs with parameters etc. Much like Windows quick launch. File Explorer – Create your own windows explorer program but with added features, better searching, new icons and other views. Sort File Records Utility – Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. Add Transactions In File and Find Averages – Read in a file of financial transactions, group them into accounts, add up fields or find averages or apply credits and debits to each account. Create Zip File Maker – The user enters various files from different directories and maybe even another computer on the network and the program transfers them and zips them up into a zip file. For added complexity, apply actual compression to the files. PDF Generator – An application which can read in a text file, html file or some other file and generates a PDF file out of it. Great for a web based service where the user uploads the file and the program returns a PDF of the file. Bulk Renamer and Organizer – This program will take a series of files and renames them with a specific filename filter entered by the user. For instance if the user enters myimage###.jpg it will rename all files with a “minimum” of three numbers like “myimage001.jpg”, “myimage145.jpg” or even “myimage1987.jpg” since 1987 has at least three numbers. Mp3 Tagger – Modify and add ID3v1 tags to MP3 files. See if you can also add in the album art into the MP3 file’s header as well as other ID3v2 tags. Log File Maker – Make an application which logs various statistics in response to given events. This can be something that logs what an application does, what the system is doing, when something like a file changes etc. Excel Spreadsheet Exporter – Create an online application which can read in a file and create an Excel Spreadsheet to export back. This can be through CVS or other file formats. For added complexity, see if you can create formula fields as well. RPG Character Stat Creator – Make a program which will randomly create a character’s stats based on several rules set forth by the user. Have it generate a class, gender, strength/magic/dexterity points, and extra abilities or trades. Have it save it to a file which can then be printed out by a dungeon master. Image Map Generator – Image maps are those images on the web that have multiple hover points that link to different pages. Such images may include maps or splash pages. See if you can make one where the user specifies an image, clicks hotspots in the image and specify links. It will then generate the HTML code to a file that the user can then copy and paste into their website to make the image map. File Copy Utility – Create a utility that can do bulk file copying and backups of other files. Code Snippet Manager – Another utility program that allows coders to put in functions, classes or other tidbits to save for use later. Organized by the type of snippet or language the coder can quickly look up code. For extra practice try adding syntax highlighting based on the language. Versioning Manager – Create your own versioning system for code files. Users are forced to check out items and lock items during reading and writing so that a group of programmers are not accidentally overwriting code files on one another. Databases SQL Query Analyzer – A utility application which a user can enter a query and have it run against a local database and look for ways to make it more efficient. Remote SQL Tool – A utility that can execute queries on remote servers from your local computer across the Internet. It should take in a remote host, user name and password, run the query and return the results. Baseball / Other Card Collector – Create an online application for keeping track of a collection of cards. Let the user enter all cards in a set, check off which ones they have, which ones they need and generate lists of cards they are looking for. For extra complexity, have it sum up sets and generate reports on how close they are of completing sets or the current value of a set. Report Generator – Create a utility that generates a report based on some tables in a database. Generates a sales reports based on the order/order details tables or sums up the days current database activity. Database Backup Script Maker – A program which reads a database’s objects, relationships, records and stored procedures and creates a .sql file which can then be imported into another database or kept as a backup file to rebuild the database with. Event Scheduler and Calendar – Make an application which allows the user to enter a date and time of an event, event notes and then schedule those events on a calendar. The user can then browse the calendar or search the calendar for specific events. For added complexity, allow the application to create reoccurrence events that reoccur every day, week, month, year etc. Budget Tracker – Write an application that keeps track of a household’s budget. The user can add expenses, income, and recurring costs to find out how much they are saving or losing over a period of time. For added complexity allow the user to specify a date range and see the net flow of money in and out of the house budget for that time period. Address Book – Keep track of various contacts, their numbers, emails and little notes about them like a rolodex in the database. For extra complexity, allow the user to connect to a website publish their address book based on specific options the user has set. TV Show Tracker – Got a favorite show you don’t want to miss? Don’t have a PVR or want to be able to find the show to then PVR it later? Make an application which can search various online TV Guide sites, locate the shows/times/channels and add them to a database application. The database/website then can send you email reminders that a show is about to start and which channel it will be on. Travel Planner System – Make a system that allows users to put together their own little travel itinerary and keep track of the airline / hotel arrangements, points of interest, budget and schedule. Entity Relationship Diagram (ERD) Creator – A program that allows the user to put together ERD diagram and save it or have it generate some basic SQL syntax to give them a jumpstart. Database Translation (MySQL <-> SQL Server) – A simple utility that reads in from one database and constructs SQL compliant with another database. Then saves that to another database. One popular transition would be to and from MySQL server for databases like SQL Server and Oracle. Web Board (Forum) – Create a forum for you and your buddies to post, administer and share thoughts and ideas. Graphics and Multimedia Slide Show – Make an application that shows various pictures in a slide show format. For extra complexity try adding various effects like fade in/out, star wipe and window blinds transitions. Mind Mapper – Allow the user to put down ideas and quickly brainstorm how they are related into a mind map. The goal here is speed so let the user quickly write in an idea and drag it around in a visual map to show relationships. Import Picture and Save as Grayscale – A utility that sucks the color right out of an image and saves it. You could add more including adjusting contrast, colorizing and more for added complexity. Stream Video from Online – Try to create your own online streaming video player. Mp3 Player (and Other Formats) – A simple program for playing your favorite music files. For extra complexity see if you can add in playlists and an equalizer. Bulk Picture Manipulator – This program will take in a directory of pictures and apply a certain effect to them whether it be reducing color count, changing its format, or alter file attributes. For something extra try to see if you can also create a system to tag them. CD Burning App – Create a utility that simply burns data to a CD. YouTube Downloader – A program which can download videos to your hard drive from youtube.com. Save the files in various formats including FLV and AVI. Wallpaper Manager – Make a program which keeps track of your favorite wallpapers, changes them regularly automatically and maybe even resizes them for your resolution (aka tiles one and stretches another) Screen Capture Program – Make a utility that will simply capture a frame from your web cam. For added complexity see if you can also build in emailing functionality. Image Browser – This application is used to view various image files on your computer from PNG, GIF, JPG to BMP, TIFF etc. Traffic Light Application – See if you can make your own street light application and then put it into an intersection scenario. Don’t let any cars run the lights and crash into one another! MP3 to Wav Converter – MP3 is essentially compressed wav format. See if you can translate it back into wav so that some other sound editing programs can work with the wav file itself. Keep in mind that 1 MB of MP3 is relative 10MB wav. Signature Maker – Ever seen those web board posts where someone has a generated signature made up? See if you can make a program that allows the user to specify a background, text, colors and alignment to make their own signatures or userbars. Screen Saver – Make a screensaver program that will run while your computer sits idle. To make a simple one use some standard pictures and then for added complexity try a 3D object that spins around the screen and bounces off the sides. Watermarking Application – Have some pictures you want copyright protected? Add your own logo or text lightly across the background so that no one can simply steal your graphics off your site. Make a program that will add this watermark to the picture. Turtle Graphics – This is a common project where you create a floor of 20 x 20 squares and using various commands you tell a turtle to draw a line on the floor. You have move forward, left or right, lift or drop pen etc. For added complexity, allow the program to read in the list of commands from a file. Do a search online for “Turtle Graphics” for more information. Games Chess and Checkers – Simply put a game of chess or checkers. Try to make it playable online and if you can use a graphical user interface that can also undo or redo a step as well as keep a history of moves for replay. Hangman – Randomly select a word from a file, have the user guess characters in the word. For each character they guess that is not in the word, have it draw another part of a man hanging in a noose. If the picture is completed before they guess all the characters, they lose. Crossword Puzzle – Create a crossword puzzle which links words together on common letters. Provide a list of clues for each word and let the user enter fill in the words until the entire crossword is filled in. Frogger – Get your frog across the river and lanes of traffic by either jumping on logs and lily pads rushing by at different speeds or avoid the automobiles which are also moving at various speeds. Based on the old arcade game. Pac Man – Another arcade classic, move Pac man around a maze gobbling up pellets and trying to avoid a group of ghosts. Power pellets allow Pac man to eat the ghosts for a limited time. Find Way Out of Maze – Develop an algorithm that allows a mouse to navigate through any maze given enough time. Guitar Hero Clone – Create your own version of guitar hero where you can incorporate your own music and allow the user to press keys for the various colored notes. Judge their accuracy. Breakout – A classic arcade game breakout involves a series of blocks at the top of the screen and using a paddle bounces a steel ball against the blocks to destroy them. Just don’t miss the ball or else you will lose. Pin Ball – I think we all know how pin ball works. Make a game where the user controls to mini paddles and keeps a ball in play, bouncing off various items and navigating through the course for various points. For added complexity, create a high score list. High / Low Number Guessing – Randomly choose a number in a range of numbers and have the user guess. If their guess is too low, tell them “too low” and if their guess is too high tell them “too high”. Let them continue to guess until they get the right answer. Keep track of the number of guesses they made before getting it right. Poker (plus online component) – Create a poker game where you can have 2 – 5 players be it real or computer controlled. Allow each player is given two cards face down which they must match against 5 community cards. The flop, the turn and the river to create the best hand possible. Each round they bet or fold. Tic Tac Toe with Friend Online – A simple game of tic tac toe. For added complexity allow the application to be played over the internet where another player can against you. Magic Eight Ball – Create a file full of random sayings and answers. Then have the magic eight ball pick one at random in response to a user’s question. Allow the user to enter the question and then show them the randomly picked answer. Game of Memory – Make a game where you have 8, 16, 32 or 64 cards which are to be matched in pairs. The user enters which two cards to turn over to see if they are a pair. Show the user the cards they turned over, if they match remove them from the game. If they do not match, flip them back over. For added complexity, impose a time limit or a turn limit. Black Jack – Also known as 21 make a game where the goal is to get as close to 21 without going over using a standard 52 card deck. The user plays against a dealer who has to sit on any value 17 or under. Battleship – Create two game boards and let each player place a number of war ships. Each player can’t see the other person’s board. They then take turns firing at one another by guessing one of the board squares. If the square they guess contains part of a ship, it is a hit. Otherwise it is a miss. They sink a ship when all squares containing that particular ship have been uncovered. The player wins when all their opponents’ ships have been sunk. Snake Game – Create a board where you start out with a small snake. The goal is to eat as much food that appears on the board as possible without it running into its own body. Each time it eats food the snake grows longer. How long can you make your snake? Slot Machine – Make a slot machine where the user can enter how many coins they are willing to bet and pull the handle. Have one of three wheels land on a random picture. Certain combinations of pictures yield coins. Others might be wild cards. For added complexity, allow the user to play not only the top, center and bottom row but also diagonals. Ice and Dice – Have the user roll three dice. Each face that has a dot in the middle is said to have a hole in the ice. Each dot not in the center is said to be a polar bear. Have the user enter the number of holes and polar bears in a given time period. So for example if you have the side with 1 dot (in the middle) it is 1 hole and no polar bears. The number 2 has no dot in the middle but two dots in the corners so it has no holes and 2 polar bears. The number 3 has one dot in the middle and two dots in the corners so it has 1 hole and 2 polar bears. The number 4 has no holes and 4 polar bears. Five has 1 hole and 4 polar bears etc. very specific challenges Grading Program Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) Write a program that allows the user to enter the grade scored in a programming class (0-100). If the user scored a 100 then notify the user that they got a perfect score. *Modify the program so that if the user scored a 90-100 it informs the user that they scored an A **Modify the program so that it will notify the user of their letter grade 0-59 F 60-69 D 70-79 C 80-89 B 90-100 A Cola Machine Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) Write a program that presents the user w/ a choice of your 5 favorite beverages (Coke, Water, Sprite, ... , Whatever). Then allow the user to choose a beverage by entering a number 1-5. Output which beverage they chose. *If you program uses if statements instead of a switch statement, modify it to use a switch statement. If instead your program uses a switch statement, modify it to use if/else-if statements. ** Modify the program so that if the user enters a choice other than 1-5 then it will output "Error. choice was not valid, here is your money back." While( user == gullible ) Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) Write a program that ccontinues to asks the user to enter any number other than 5 until the user enters the number 5. Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program. *Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit. **Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.) Pancake Glutton Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10) Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast. *Modify the program so that it also outputs which person ate the least number of pancakes for breakfast. ****Modify the program so that it outputs a list in order of number of pancakes eaten of all 10 people. i.e. Person 4: ate 10 pancakes Person 3: ate 7 pancakes Person 8: ate 4 pancakes ... Person 5: ate 0 pancakes Bracketing Search Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) psudo random numbers Write a program that calculates a random number 1 through 100. The program then asks the user to guess the number. If the user guesses too high or too low then the program should output "too high" or "too low" accordingly. The program must let the user continue to guess until the user correctly guesses the number. *Modify the program to output how many guesses it took the user to correctly guess the right number. **Modify the program so that instead of the user guessing a number the computer came up with, the computer guesses the number that the user has secretely decided. The user must tell the computer whether it guesed too high or too low. ****Modify the program so that no matter what number the user thinks of (1-100) the computer can guess it in 7 or less guesses. Tic Tac Toe Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays Make a two player tic tac toe game. * Modify the program so that it will announce when a player has won the game (and which player won, x or o) ** Modify the program so that it is a one player game against the computer (with the computer making its moves randomly) **** Modify the program so that anytime the player is about to win (aka, they have 2 of 3 x's in a row, the computer will block w/ an o) Dungeon Crawl Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays Make a program that outputs a simple grid based gameboard to the screen using either numbers or characters. i.e. . . . . . . . . . . . G . . . . . . . . . . . . . . T . . . . . . . . . . . . . . . . . T . . . . . . . . . . . T . . . . . . . . . . . . X or 0 0 0 0 0 0 0 0 0 0 0 5 0 0 6 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 0 0 0 0 0 0 0 4 Allow the user (marked by G in the example) to move either up, down, left, or right each turn. If the player steps on a trap then they lose. If the make it to the treasure 'X' then they win. ** Add enemies that move randomly in any direction once per turn. (enemies just like traps cause the player to lose if touched) HINT: Don't let the player move off the gameboard! You program will crash if they move off the top or bottom of the board! (the same holds true for enemies) Fun with Functions Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) functions Write a function titled say_hello() that outputs to the screen "Hello" * Modify the function so that it takes an integer argument and says hello a number of times equal to the value passed to it. ** Make another function that takes two integers arguments and then returns an integer that is the product of the two integers. (i.e., integer1: 4, Integer2: 5 returns: 20) *** Make a function called half() that takes an integer argument. The function must print the number it received to the screen, then the program should divide that number by two to make a new number. If the new number is greater than zero the function then calls the function half() passing it the new number as its argument. If the number is zero or less than the function exits Call the function half() with an argument of 100, the screen output should be 100 50 25 ... ... 1. Strings are your friends, until they betray you. Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) functions strings & string functions Write a program that asks for a user first name and last name separately. The program must then store the users full name inside a single string and out put it to the string. i.e. Input: John Smith Output: John Smith * Modify the program so that it then replaces every a, e, i , o, u w/ the letter z. i.e. John Smith -> Jzhn Smzth ** Modify the Program so that it reverses the users name i.e. John Smith -> htimS nhoJ Graduation: Requires: variables, data types, and numerical operators basic input/output logic (if statements, switch statements) loops (for, while, do-while) arrays pseudo random number generation strings & string functions functions structures/classes enumerated data file input/output pointers sorting linked lists advanced classes Write a program that creates a linked list of bunny objects. Each bunny object must have Sex: Male, Female (random at creation 50/50) color: white, brown, black, spotted age : 0-10 (years old) Name : randomly chosen at creation from a list of bunny names. radioactive_mutant_vampire_bunny: true/false (decided at time of bunny creation 2% chance of true) At program initialization 5 bunnies must be created and given random colors. Each turn afterwards the bunnies age 1 year. So long as there is at least one male age 2 or older, for each female bunny in the list age 2 or older; a new bunny is created each turn. (i.e. if there was 1 adult male and 3 adult female bunnies, three new bunnies would be born each turn) New bunnies born should be the same color as their mother. If a bunny becomes older than 10 years old, it dies. If a radioactive mutant vampire bunny is born then each turn it will change exactly one non radioactive bunny into a radioactive vampire bunny. (if there are two radioactive mutant vampire bunnies two bunnies will be changed each turn and so on...) Radioactive vampire bunnies are excluded from regular breeding and do not count as adult bunnies. Radioactive vampire bunnies do not die until they reach age 50. The program should print a list of all the bunnies in the colony each turn along w/ all the bunnies details, sorted by age. The program should also output each turns events such as "Bunny Thumper was born! Bunny Fufu was born! Radioactive Mutant Vampire Bunny Darth Maul was born! Bunny Julius Caesar died! The program should write all screen output to a file. When all the bunnies have died the program terminates. If the bunny population exceeds 1000 a food shortage must occur killing exactly half of the bunnies (randomly chosen) * Modify the program to run in real time, with each turn lasting 2 seconds, and a one second pause between each announement. ** Allow the user to hit the 'k' key to initiate a mass rabit cull! which causes half of all the rabits to be killed (randomly chosen). **** Modify the program to place the rabits in an 80x80 grid. Have the rabits move one space each turn randomly. Mark juvenile males with m, adult males w/ M, juvenile females w/ f, adult femails w/ F radioactive mutant vampire bunnies with X Modify the program so that radioactive mutant vampire bunnies only convert bunnies that end a turn on an adjacent square. Modify the program so that new babies are born in an empty random adjacent square next to the mother bunny. (if no empty square exits then the baby bunny isn't born) ***** Modify the program so that it saves each turn to a file and can play back at accelearted speed all subsequent turns.
Games
http://videogameideas.wikia.com and select random page http://inventwithpython.com/blog/2012/02/20/i-need-practice-programming-49-ideas-for-game-clones-to-code/ RE: Collection of programming ideas - metulburr - Oct-04-2016 https://github.com/zhiwehu/Python-programming-exercises 100+ Python challenging programming exercises 1. Level description Level Description Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks. Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks. Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. 2. Problem template #----------------------------------------# Question Hints Solution 3. Questions #----------------------------------------# Question 1 Level 1 Question: Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: Consider use range(#begin, #end) method Solution: l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) #----------------------------------------# #----------------------------------------# Question 2 Level 1 Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print fact(x) #----------------------------------------# #----------------------------------------# Question 3 Level 1 Question: With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() Solution: n=int(raw_input()) d=dict() for i in range(1,n+1): d[i]=i*i print d #----------------------------------------# #----------------------------------------# Question 4 Level 1 Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple Solution: values=raw_input() l=values.split(",") t=tuple(l) print l print t #----------------------------------------# #----------------------------------------# Question 5 Level 1 Question: Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Hints: Use __init__ method to construct some parameters Solution: class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = raw_input() def printString(self): print self.s.upper() strObj = InputOutString() strObj.getString() strObj.printString() #----------------------------------------# #----------------------------------------# Question 6 Level 2 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) In case of input data being supplied to the question, it should be assumed to be a console input. Solution: #!/usr/bin/env python import math c=50 h=30 value = [] items=[x for x in raw_input().split(',')] for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print ','.join(value) #----------------------------------------# #----------------------------------------# Question 7 Level 2 Question: Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i=0,1.., X-1; j=0,1,¡Y-1. Example Suppose the following inputs are given to the program: 3,5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] Hints: Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. Solution: input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] colNum=dimensions[1] multilist = [[0 for col in range(colNum)] for row in range(rowNum)] for row in range(rowNum): for col in range(colNum): multilist[row][col]= row*col print multilist #----------------------------------------# #----------------------------------------# Question 8 Level 2 Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) #----------------------------------------# #----------------------------------------# Question 9 Level 2 Question£º Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence #----------------------------------------# #----------------------------------------# Question 10 Level 2 Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use set container to remove duplicated data automatically and then use sorted() to sort the data. Solution: s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) #----------------------------------------# #----------------------------------------# Question 11 Level 2 Question: Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output should be: 1010 Notes: Assume the data is input by console. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: value = [] items=[x for x in raw_input().split(',')] for p in items: intp = int(p, 2) if not intp%5: value.append(p) print ','.join(value) #----------------------------------------# #----------------------------------------# Question 12 Level 2 Question: Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values) #----------------------------------------# #----------------------------------------# Question 13 Level 2 Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+=1 elif c.isalpha(): d["LETTERS"]+=1 else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] #----------------------------------------# #----------------------------------------# Question 14 Level 2 Question: Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. Suppose the following input is supplied to the program: Hello world! Then, the output should be: UPPER CASE 1 LOWER CASE 9 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: if c.isupper(): d["UPPER CASE"]+=1 elif c.islower(): d["LOWER CASE"]+=1 else: pass print "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"] #----------------------------------------# #----------------------------------------# Question 15 Level 2 Question: Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print n1+n2+n3+n4 #----------------------------------------# #----------------------------------------# Question 16 Level 2 Question: Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,3,5,7,9 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) #----------------------------------------# Question 17 Level 2 Question: Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should be: 500 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: netAmount = 0 while True: s = raw_input() if not s: break values = s.split(" ") operation = values[0] amount = int(values[1]) if operation=="D": netAmount+=amount elif operation=="W": netAmount-=amount else: pass print netAmount #----------------------------------------# #----------------------------------------# Question 18 Level 3 Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 letter between [A-Z] 3. At least 1 character from [$#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. Example If the following passwords are given as input to the program: ABd1234@1,a F1#,2w3E*,2We3345 Then, the output of the program should be: ABd1234@1 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solutions: import re value = [] items=[x for x in raw_input().split(',')] for p in items: if len(p)<6 or len(p)>12: continue else: pass if not re.search("[a-z]",p): continue elif not re.search("[0-9]",p): continue elif not re.search("[A-Z]",p): continue elif not re.search("[$#@]",p): continue elif re.search("\s",p): continue else: pass value.append(p) print ",".join(value) #----------------------------------------# #----------------------------------------# Question 19 Level 3 Question: You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. The priority is that name > age > score. If the following tuples are given as input to the program: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85 Then, the output of the program should be: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. Solutions: from operator import itemgetter, attrgetter l = [] while True: s = raw_input() if not s: break l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) #----------------------------------------# #----------------------------------------# Question 20 Level 3 Question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. Hints: Consider use yield Solution: def putNumbers(n): i = 0 while i<n: j=i i=i+1 if j%7==0: yield j for i in reverse(100): print i #----------------------------------------# #----------------------------------------# Question 21 Level 3 Question£º A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 ¡ The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: import math pos = [0,0] while True: s = raw_input() if not s: break movement = s.split(" ") direction = movement[0] steps = int(movement[1]) if direction=="UP": pos[0]+=steps elif direction=="DOWN": pos[0]-=steps elif direction=="LEFT": pos[1]-=steps elif direction=="RIGHT": pos[1]+=steps else: pass print int(round(math.sqrt(pos[1]**2+pos[0]**2))) #----------------------------------------# #----------------------------------------# Question 22 Level 3 Question: Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1 Hints In case of input data being supplied to the question, it should be assumed to be a console input. Solution: freq = {} # frequency of words in text line = raw_input() for word in line.split(): freq[word] = freq.get(word,0)+1 words = freq.keys() words.sort() for w in words: print "%s:%d" % (w,freq[w]) #----------------------------------------# #----------------------------------------# Question 23 level 1 Question: Write a method which can calculate square value of number Hints: Using the ** operator Solution: def square(num): return num ** 2 print square(2) print square(3) #----------------------------------------# #----------------------------------------# Question 24 Level 1 Question: Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions. Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function Hints: The built-in document method is __doc__ Solution: print abs.__doc__ print int.__doc__ print raw_input.__doc__ def square(num): '''Return the square value of the input number. The input number must be integer. ''' return num ** 2 print square(2) print square.__doc__ #----------------------------------------# #----------------------------------------# Question 25 Level 1 Question: Define a class, which have a class parameter and have a same instance parameter. Hints: Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later Solution: class Person: # Define the class parameter "name" name = "Person" def __init__(self, name = None): # self.name is the instance parameter self.name = name jeffrey = Person("Jeffrey") print "%s name is %s" % (Person.name, jeffrey.name) nico = Person() nico.name = "Nico" print "%s name is %s" % (Person.name, nico.name) #----------------------------------------# #----------------------------------------# Question: Define a function which can compute the sum of two numbers. Hints: Define a function with two numbers as arguments. You can compute the sum in the function and return the value. Solution def SumFunction(number1, number2): return number1+number2 print SumFunction(1,2) #----------------------------------------# Question: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. Solution def printValue(n): print str(n) printValue(3) #----------------------------------------# Question: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. Solution def printValue(n): print str(n) printValue(3) #----------------------------------------# 2.10 Question: Define a function that can receive two integral numbers in string form and compute their sum and then print it in console. Hints: Use int() to convert a string to integer. Solution def printValue(s1,s2): print int(s1)+int(s2) printValue("3","4") #7 #----------------------------------------# 2.10 Question: Define a function that can accept two strings as input and concatenate them and then print it in console. Hints: Use + to concatenate the strings Solution def printValue(s1,s2): print s1+s2 printValue("3","4") #34 #----------------------------------------# 2.10 Question: Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line. Hints: Use len() function to get the length of a string Solution def printValue(s1,s2): len1 = len(s1) len2 = len(s2) if len1>len2: print s1 elif len2>len1: print s2 else: print s1 print s2 printValue("one","three") #----------------------------------------# 2.10 Question: Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". Hints: Use % operator to check if a number is even or odd. Solution def checkValue(n): if n%2 == 0: print "It is an even number" else: print "It is an odd number" checkValue(7) #----------------------------------------# 2.10 Question: Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Solution def printDict(): d=dict() d[1]=1 d[2]=2**2 d[3]=3**2 print d printDict() #----------------------------------------# 2.10 Question: Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 print d printDict() #----------------------------------------# 2.10 Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for (k,v) in d.items(): print v printDict() #----------------------------------------# 2.10 Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i**2 for k in d.keys(): print k printDict() #----------------------------------------# 2.10 Question: Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[:5] printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[-5:] printList() #----------------------------------------# 2.10 Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[5:] printList() #----------------------------------------# 2.10 Question: Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use tuple() to get a tuple from a list. Solution def printTuple(): li=list() for i in range(1,21): li.append(i**2) print tuple(li) printTuple() #----------------------------------------# 2.10 Question: With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. Hints: Use [n1:n2] notation to get a slice from a tuple. Solution tp=(1,2,3,4,5,6,7,8,9,10) tp1=tp[:5] tp2=tp[5:] print tp1 print tp2 #----------------------------------------# 2.10 Question: Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). Hints: Use "for" to iterate the tuple Use tuple() to generate a tuple from a list. Solution tp=(1,2,3,4,5,6,7,8,9,10) li=list() for i in tp: if tp[i]%2==0: li.append(tp[i]) tp2=tuple(li) print tp2 #----------------------------------------# 2.14 Question: Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". Hints: Use if statement to judge condition. Solution s= raw_input() if s=="yes" or s=="YES" or s=="Yes": print "Yes" else: print "No" #----------------------------------------# 3.4 Question: Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. Hints: Use filter() to filter some elements in a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers #----------------------------------------# 3.4 Question: Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] squaredNumbers = map(lambda x: x**2, li) print squaredNumbers #----------------------------------------# 3.5 Question: Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) print evenNumbers #----------------------------------------# 3.5 Question: Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution evenNumbers = filter(lambda x: x%2==0, range(1,21)) print evenNumbers #----------------------------------------# 3.5 Question: Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution squaredNumbers = map(lambda x: x**2, range(1,21)) print squaredNumbers #----------------------------------------# 7.2 Question: Define a class named American which has a static method called printNationality. Hints: Use @staticmethod decorator to define class static method. Solution class American(object): @staticmethod def printNationality(): print "America" anAmerican = American() anAmerican.printNationality() American.printNationality() #----------------------------------------# 7.2 Question: Define a class named American and its subclass NewYorker. Hints: Use class Subclass(ParentClass) to define a subclass. Solution: class American(object): pass class NewYorker(American): pass anAmerican = American() aNewYorker = NewYorker() print anAmerican print aNewYorker #----------------------------------------# 7.2 Question: Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. Hints: Use def methodName(self) to define a method. Solution: class Circle(object): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 aCircle = Circle(2) print aCircle.area() #----------------------------------------# 7.2 Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. Hints: Use def methodName(self) to define a method. Solution: class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width aRectangle = Rectangle(2,10) print aRectangle.area() #----------------------------------------# 7.2 Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. Hints: To override a method in super class, we can define a method with the same name in the super class. Solution: class Shape(object): def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, l): Shape.__init__(self) self.length = l def area(self): return self.length*self.length aSquare= Square(3) print aSquare.area() #----------------------------------------# Please raise a RuntimeError exception. Hints: Use raise() to raise an exception. Solution: raise RuntimeError('something wrong') #----------------------------------------# Write a function to compute 5/0 and use try/except to catch the exceptions. Hints: Use try/except to catch exceptions. Solution: def throws(): return 5/0 try: throws() except ZeroDivisionError: print "division by zero!" except Exception, err: print 'Caught an exception' finally: print 'In finally block for cleanup' #----------------------------------------# Define a custom exception class which takes a string message as attribute. Hints: To define a custom exception, we need to define a class inherited from Exception. Solution: class MyError(Exception): """My own exception class Attributes: msg -- explanation of the error """ def __init__(self, msg): self.msg = msg error = MyError("something wrong") #----------------------------------------# Question: Assuming that we have some email addresses in the "[email protected]" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: [email protected] Then, the output of the program should be: john In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. Solution: import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) #----------------------------------------# Question: Assuming that we have some email addresses in the "[email protected]" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: [email protected] Then, the output of the program should be: In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. Solution: import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" r2 = re.match(pat2,emailAddress) print r2.group(2) #----------------------------------------# Question: Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. Example: If the following words is given as input to the program: 2 cats and 3 dogs. Then, the output of the program should be: ['2', '3'] In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use re.findall() to find all substring using regex. Solution: import re s = raw_input() print re.findall("\d+",s) #----------------------------------------# Question: Print a unicode string "hello world". Hints: Use u'strings' format to define unicode string. Solution: unicodeString = u"hello world!" print unicodeString #----------------------------------------# Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. Hints: Use unicode() function to convert. Solution: s = raw_input() u = unicode( s ,"utf-8") print u #----------------------------------------# Question: Write a special comment to indicate a Python source code file is in unicode. Hints: Solution: # -*- coding: utf-8 -*- #----------------------------------------# Question: Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 3.55 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use float() to convert an integer to a float Solution: n=int(raw_input()) sum=0.0 for i in range(1,n+1): sum += float(float(i)/(i+1)) print sum #----------------------------------------# Question: Write a program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 with a given n input by console (n>0). Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 500 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: We can define recursive function in Python. Solution: def f(n): if n==0: return 0 else: return f(n-1)+100 n=int(raw_input()) print f(n) #----------------------------------------# Question: The Fibonacci Sequence is computed based on the following formula: f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1 Please write a program to compute the value of f(n) with a given n input by console. Example: If the following n is given as input to the program: 7 Then, the output of the program should be: 13 In case of input data being supplied to the question, it should be assumed to be a console input. Hints: We can define recursive function in Python. Solution: def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) print f(n) #----------------------------------------# #----------------------------------------# Question: The Fibonacci Sequence is computed based on the following formula: f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1 Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. Example: If the following n is given as input to the program: 7 Then, the output of the program should be: 0,1,1,2,3,5,8,13 Hints: We can define recursive function in Python. Use list comprehension to generate a list from an existing list. Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(raw_input()) values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) #----------------------------------------# Question: Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 10 Then, the output of the program should be: 0,2,4,6,8,10 Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def EvenGenerator(n): i=0 while i<=n: if i%2==0: yield i i+=1 n=int(raw_input()) values = [] for i in EvenGenerator(n): values.append(str(i)) print ",".join(values) #----------------------------------------# Question: Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. Example: If the following n is given as input to the program: 100 Then, the output of the program should be: 0,35,70 Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input. Solution: def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: yield i n=int(raw_input()) values = [] for i in NumGenerator(n): values.append(str(i)) print ",".join(values) #----------------------------------------# Question: Please write assert statements to verify that every number in the list [2,4,6,8] is even. Hints: Use "assert expression" to make assertion. Solution: li = [2,4,6,8] for i in li: assert i%2==0 #----------------------------------------# Question: Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: If the following string is given as input to the program: 35+3 Then, the output of the program should be: 38 Hints: Use eval() to evaluate an expression. Solution: expression = raw_input() print eval(expression) #----------------------------------------# Question: Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. Hints: Use if/elif to deal with conditions. Solution: import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) #----------------------------------------# Question: Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. Hints: Use if/elif to deal with conditions. Solution: import math def bin_search(li, element): bottom = 0 top = len(li)-1 index = -1 while top>=bottom and index==-1: mid = int(math.floor((top+bottom)/2.0)) if li[mid]==element: index = mid elif li[mid]>element: top = mid-1 else: bottom = mid+1 return index li=[2,5,7,9,11,17,222] print bin_search(li,11) print bin_search(li,12) #----------------------------------------# Question: Please generate a random float where the value is between 10 and 100 using Python math module. Hints: Use random.random() to generate a random float in [0,1]. Solution: import random print random.random()*100 #----------------------------------------# Question: Please generate a random float where the value is between 5 and 95 using Python math module. Hints: Use random.random() to generate a random float in [0,1]. Solution: import random print random.random()*100-5 #----------------------------------------# Question: Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. Hints: Use random.choice() to a random element from a list. Solution: import random print random.choice([i for i in range(11) if i%2==0]) #----------------------------------------# Question: Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. Hints: Use random.choice() to a random element from a list. Solution: import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) #----------------------------------------# Question: Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample(range(100), 5) #----------------------------------------# Question: Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample([i for i in range(100,201) if i%2==0], 5) #----------------------------------------# Question: Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. Hints: Use random.sample() to generate a list of random values. Solution: import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) #----------------------------------------# Question: Please write a program to randomly print a integer number between 7 and 15 inclusive. Hints: Use random.randrange() to a random integer in a given range. Solution: import random print random.randrange(7,16) #----------------------------------------# Question: Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". Hints: Use zlib.compress() and zlib.decompress() to compress and decompress a string. Solution: import zlib s = 'hello world!hello world!hello world!hello world!' t = zlib.compress(s) print t print zlib.decompress(t) #----------------------------------------# Question: Please write a program to print the running time of execution of "1+1" for 100 times. Hints: Use timeit() function to measure the running time. Solution: from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() #----------------------------------------# Question: Please write a program to shuffle and print the list [3,6,7,8]. Hints: Use shuffle() function to shuffle a list. Solution: from random import shuffle li = [3,6,7,8] shuffle(li) print li #----------------------------------------# Question: Please write a program to shuffle and print the list [3,6,7,8]. Hints: Use shuffle() function to shuffle a list. Solution: from random import shuffle li = [3,6,7,8] shuffle(li) print li #----------------------------------------# Question: Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. Hints: Use list[index] notation to get a element from a list. Solution: subjects=["I", "You"] verbs=["Play", "Love"] objects=["Hockey","Football"] for i in range(len(subjects)): for j in range(len(verbs)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print sentence #----------------------------------------# Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. Hints: Use list comprehension to delete a bunch of element from a list. Solution: li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Solution: li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. Solution: li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li #----------------------------------------# Question: By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. Hints: Use list comprehension to make an array. Solution: array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. Solution: li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] print li #----------------------------------------# Question: By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. Hints: Use list's remove method to delete a value. Solution: li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li #----------------------------------------# Question: With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. Hints: Use set() and "&=" to do set intersection operation. Solution: set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print li #----------------------------------------# With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. Hints: Use set() to store a number of values without duplicate. Solution: def removeDuplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) #----------------------------------------# Question: Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. Hints: Use Subclass(Parentclass) to define a child class. Solution: class Person(object): def getGender( self ): return "Unknown" class Male( Person ): def getGender( self ): return "Male" class Female( Person ): def getGender( self ): return "Female" aMale = Male() aFemale= Female() print aMale.getGender() print aFemale.getGender() #----------------------------------------# Question: Please write a program which count and print the numbers of each character in a string input by console. Example: If the following string is given as input to the program: abcdefgabc Then, the output of the program should be: a,2 c,2 b,2 e,1 d,1 g,1 f,1 Hints: Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. Solution: dic = {} s=raw_input() for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) #----------------------------------------# Question: Please write a program which accepts a string from console and print it in reverse order. Example: If the following string is given as input to the program: rise to vote sir Then, the output of the program should be: ris etov ot esir Hints: Use list[::-1] to iterate a list in a reverse order. Solution: s=raw_input() s = s[::-1] print s #----------------------------------------# Question: Please write a program which accepts a string from console and print the characters that have even indexes. Example: If the following string is given as input to the program: H1e2l3l4o5w6o7r8l9d Then, the output of the program should be: Helloworld Hints: Use list[::2] to iterate a list by step 2. Solution: s=raw_input() s = s[::2] print s #----------------------------------------# Question: Please write a program which prints all permutations of [1,2,3] Hints: Use itertools.permutations() to get permutations of list. Solution: import itertools print list(itertools.permutations([1,2,3])) #----------------------------------------# Question: Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? Hint: Use for loop to iterate all possible solutions. Solution: def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): j=numheads-i if 2*i+4*j==numlegs: return i,j return ns,ns numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions #----------------------------------------# RE: Collection of programming ideas - Skaperen - Oct-04-2016 i'd like to see a web based tax form that is formatted to look like a real tax form, where you can enter your own numbers and it calculates the parts of the form that has all the info it needs, with an "I am Donald J. Trump" button that fills in his loss amounts. RE: Collection of programming ideas - ichabod801 - Oct-04-2016 Note that the fourth link (game prerequisites) is broken. The hacker rank link goes to a blank page on hacker rank. The Python page might be better: https://www.hackerrank.com/domains/python/py-introduction. I would also suggest adding r/dailyprogrammer: https://www.reddit.com/r/dailyprogrammer/. advanced coding challenges: find/sort ip addresses - Skaperen - Nov-12-2016 challenge #0 your function is given a string with an IP address possibly in there somewhere. if there is no IP address, then just return None or raise an exception. if there is an IP address, return a tuple with: #0: where the first IP address starts in the string #1: where the first IP address ends in the string these 2 numbers are suitable for slicing the string to split the parts. bonus: support multiple IP addresses (what should be returned?) bonus: support IPv6 (what should be returned?) challenge #1 write a program/script to sort the lines of a file by IP address as found by the function in the above challenge. be sure that 10.9.9.9 comes before 172.16.8.8 bonus: accept an argument/option to specify the index of which IP address is to be the sort key bonus: support IPv6 (how will you collate IPv4-in-IPv6 relative to IPv4?) RE: Collection of programming ideas and challenges - Ofnuts - Nov-12-2016 Challenge #1: this is the -V, --version-sort options of the 'sort' command :) (which, the way it works, applies to IP address just as well as to program versions). RE: Collection of programming ideas and challenges - Larz60+ - Feb-06-2017 GIS Programming Ideas - A list of research locations, and data sources for learning and programming GIS (Geographic Information System) Change detection. I collected these, but may never do anything with them. This could be a good starting list for career or business. GIS - Change Detection - Can be used for many purposes, examples include defense, finding weeds and pests on Farms, locating emegring volcanoes, vegitation change over time, rate of increase in city size, new construction, to mention just a few. This data is mostly for the United States - Please add information that you know of for you're country. Change Detection - Measure changes in a particular area or feature over time. Research: Remote Sensing:
Data Remote Sensing:
Searching for data - Mostly for those new to searching, but you just might find something useful: Just a quick note about searching. Google is a great place to start when you have a specific topic in mind. Here are a few things you can do to enhance your searches: For example, I will use the following link (from Manatoba Map Projections): http://www.edu.gov.mb.ca/k12/cur/socstud/frame_found_sr2/tns/tn-6.pdf
According to http://gisgeography.com/free-gis-programming-tutorials/ Python is the number one language used for GIS Project Idea for Semi_Beginners - Zombie_Programming - Jun-27-2018 Program Idea for Semi-Beginners This project assumes that you have a decent background knowledge is classes, file I/O and many other things. The idea is a Bank Database. Essentially each bank account owner will have a PRE-GENERATED account ID(12-digits long, all numerical) and a PIN they create them self. They can use this pin to make a deposit, make a withdrawal, and look at their transaction log. If the user doesn't have a bank account, let them register one using some basic information you would have to provide if you were to set up a real bank account. (Name, DOB, SSN, create a PIN, generate account number). You want to make sure that the information the user gives is VALID. Information Restrictions
In short, here is a list of things you need to do for this project:
I know as a beginner, it's hard to find something that is big enough to tackle, but not something overwhelming. This is a project that I came up with to really teach me about File I/O and moving data around different files, and it really helped. It also helps with learning OOP. Hopefully, this didn't seem to scattered around, I just wanted to get this out there! ~ Zombie Programming. RE: Collection of programming ideas and challenges - metulburr - Oct-20-2018 (Oct-20-2018, 02:49 PM)AIClaire Wrote: It has taken a while to build up my knowledge of programming in python so that I understand it but there have been quite a few programming examples I've found on the way that helped. |