vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Scientists and deficit spenders like to use Python because it can handle very large numbers. I decided to give it a test with factorials. Factorials reach astronomical levels rather quickly. In case you can't quite remember, the factorial of 12 is !12 = 1*2*3*4*5*6*7*8*9*10*11*12 = 479001600, that is 479 million and some change! After that languages like C++ start to fizzle quickly! At !16 we get past the nations debt. Python can handle that and more! I stopped at !69 only because the display started to wrap the line. The result has 98 digits in it, I thought I made my point anyway.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple experiment with the ever so popular Mandelbrot fractal graphics, call it mathematical art, nice to look at. This set of experiments loops through a number of colors to make the whole thing more exciting.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

While the calculation of the total resistance of two resistors in parallel is simple, this code shows you how to trap a number of potential errors that come with the entry of the required data. All is wrapped easily into a colorful GUI program, due to the simplicity of the Tkinter module. The GUI contains two data entry boxes, two labels for user instructions, one label to show the calculated results, and a button to start the calculation defined in the function. This could easily be a GUI template for other calculations that need two data inputs. Remember that Tkinter works with Windows, Linux and the Mac OS-X.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Yes, you can let your computer read text to you. The task is relatively easy, if you have Windows on your machine. All you need is Microsoft's speech-API SAPI, the Python Text to Speech module pyTTS, and an updated version of win32com, all free downloads. Here are some experiments with the pyTTS module that literally talk to you.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python uses the Mersenne Twister as the core random generator. The module random contains a fair number of methods (or functions) that help you to do random things. Here are some examples ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The code shows a fast prime number generator using a sieve algorithm. It looks at only odd numbers. Technically 1 and 2 are prime numbers too, since they are only divisible by unity and themselves, exceptions are made for 1 and 2. Zero and negative numbers return an empty list.

Note:
The official definition for a prime number is any natural number [B]greater than 1[/B] that has the two divisors 1 and itself. So, we are leaving the 1 out!

This is not a generator object in the Python sense. It is a function that generates a list of prime numbers.

Note: see modified/corrected code at:
[url]http://www.daniweb.com/forums/post1254825.html#post1254825[/url]

For much improved speed see ...
https://www.daniweb.com/software-development/python/code/434136/fast-prime-list-functions

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Tkinter module comes with the normal Python installation. It allows you to create Python GUI programs for Windows, Linux or Unix on the Mac. In this snippet we put a GIF image (.gif) onto a form's canvas with just a few lines of code. Most of the lines are remarks to explain what is going on.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I was looking for a somewhat meaningful and interesting example to explain the Python class to beginners. A room full of multilingual students makes this phrase translator a good choice. You can experiment with it and add more languages and phrases.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Converting a decimal integer (denary, base 10) to a binary string (base 2) is amazingly simple. An exception is raised for negative numbers and zero is a special case. To test the result, the binary string is converted back to the decimal value, easily done with the int(bStr, 2) function.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A common way to represent an inventory is with a list of tuples. Each tuple represents the item name and the item count. You can sort this inventory list by item name or item count. Here is an example to pick a sort key. It's your summer job to run a fruit stand along the road. You also have to count the grapes twice a day, the boss doesn't want you to eat any!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple program to count the words, lines and sentences contained in a text file. The assumptions are made that words are separated by whitespaces, and sentences end with a period, question mark or exclamation mark.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The module datetime allows you to call several functions that can do computation with dates and times. How many days since my birth? How many days till Xmas? What's the date 77 days from now? The code snippet should give you a flavor, enough to explore on your own.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Many of the code samples on the internet are written in Turbo C. The clrscr() function litters these samples, and even to this day people want to wipe your screen. You can use system("CLS"), but that uses a DOS command. DOS commands are with us only at the whim of William the Mighty. Here is the Windows version of clearing the console screen with WinApi functions, in the hope that these functions will stay around a little longer.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Quick and dirty way to change your console program colors using DOS command "Color BackgroundForeground" where Background is hex 0 = black to F = white, dito for Foreground.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The wxPython library allows Python to create Windows GUI programs. Here is a look at the listbox component. Click a button to load the listbox with names, select the name by clicking on it on the list, and display it in the title bar of the window frame. Another button clears the listbox.

Gribouillis commented: Great example ! +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This program uses WinApi function SetPixel() to plot math functions y = sin(x) and y = cos(x) and y = sin(x)*cos(x) along a y-axis centered on the console screen. Make sure that gdi32.lib is included in the libraries to be linked.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The set is an unordered collection of unique hashable elements. All the elements/items in a set are treated as keys. There are several functions that compare two sets. Right now, I will just give you a taste ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We take a look at the various functions of module time, counting seconds and milliseconds, measuring the time a simple for-loop takes, inspect a list of time data and ways to display it in a useful manner. An attempt is made to find the day of the week, given a date a few years old. Like, what day of the week was your friend born. Hope he or she isn't too old, there is a limit to everything in life!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example how to plot the function y = sin(x) using the WinApi function SetPixel(). The plot is centered along a line at pixel y = 200. Add an x-axis and a couple of tickmarks and it could look impressive.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using wxPython and the Boa Constructor, a VB/Delphi like IDE and Visual Builder, this little calculator was a breeze to make. Boa did 90% of the code generation, and I simply added code to each button click event to make the calculations work. I wish every project would go that easy. Take a look at the commented code.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One more application of the Python Image Library (PIL). This short code creates thumbnails from all JPEG files in the current folder. The thumbnail image file is prefixed with a T_ and saved to the same directory. The program checks for existing files with this prefix, so we don't create T_T_ prefix files and so on.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python can use its COM support and the OCX of the WindowsMediaPlayer to play mp3 music files. Make sure that your Python installation has the win32com folder. Check http://starship.python.net/crew/mhammond/win32/Downloads.html for the latest win32com support.

This code relies on file WMPlayer.OCX which MS has removed on newer versions of Windows. See the note on using modules pygame or pyglet in the comment posts.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You may want to call Python's list the answer to other computer languages' arrays. Here we take a look at the things you can do with lists, create an empty list, list the attributes and methods, load, append, count, insert, join, pop, remove, remove duplicate items, reverse, search, sort, establish a list of files, the list goes on ...

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Simple DirectMedia Layer (SDL) library allows for manageable multimedia programming in console mode. Now you can mix graphics, animated or otherwise, with sound and make your game project more interesting. I am showing an example for Dev-C++ using math generated graphics, purloined from the NET, and give some instructions where to get SDL and how to install it properly.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A dictionary in Python is an unordered set of key:value pairs. I show you how to initialize, create, load, display, search, copy and otherwise manipulate this interesting container. Like the name says, it is the closest thing to a dictionary.

Tcll commented: very nice, mentions everything I've played with. =D +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The code is shamefully short, but here it is. Now you can listen to the many sound files in wave (.wav) format and boing, chirp, chime, bark, booh, laugh and mooh at the people around you.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The WinBGI package allows you to do some of the Borland BGI graphics in a specially created window form. So don't throw out the old Borland manuals, you can still use them to do some fancy graphing! Yes, you can gotoxy() again! This code was modified for Dev-C++, a real workhorse come to think of it. Thanks free_eagle for getting this started!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You have to mildly trick Windows, but it is possible to put a bitmap image on your console. Uses a flock of WinApi calls. Works well with the free PellesC compiler and Dev-C++. This is a Windows Console Application. Drop me a comment, if you have luck with another compiler.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Bud is convinced that programming keeps his brain sharp and keeps Alzheimer's away!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example how to line up your decimal points in a column like output of floating point numbers. Both C and C++ versions are shown. Thanks are given to Bud Tugly, my 77 year old senior student.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another application of the Python Image Library (PIL). This time we are loading an image and rotate it counterclockwise by a specified number of degrees. The image is shown rotated and then saved to the working folder. PIL handles a fair amount of image file formats easily.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Folks have asked numerous times for a code snippet of a binary search of an array. Here is heavily commented code with a few test printf() included to give you a picture of what is going on.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Take a look at a typical Windows GUI frame (form) with a menubar, statusbar, panel, label and buttons. Set the font and size of text, click the buttons to create some events. All of this and much more is in the free wxPython package.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are some pretty fancy things you can do with strings in Python. You can append, convert, justify, join, split, slice, and list selected files of a folder. I just give you a small sample here.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am using Python23 and the PythonWin IDE from
http://starship.python.net/crew/mhammond/win32/
all free downloads and simple to use.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is an application of the Python Image Library (PIL) and shows you how simple it is to do pixel math on an image.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This code gets the local time from your computer, formats the date and the time and displays the result. Does not include the bavarian time measurement of how many steins you have finished since you got up in the morning.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is a test to get the Python snippets going! For those of you who are scared of snakes, the language is named after the TV program, not the snake. Python is an interpreted language, but programs to compile/combine the code to an exe file are available (Py2Exe). The latest version of Python can be downloaded for free from the http://www.python.org site.
If you are just starting with the fun of Python coding, direct your eyes to: http://www.daniweb.com/techtalkforums/thread20774.html
If you really want to see what Python can do, take a look at: http://vpython.org/

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here we use the eval() function as the backbone of a simple calculator. One table is used for the display. A second table holds the buttons for the keypad. The whole thing forms an attractive looking calculator. To test it, simply paste the code into an editor like notepad and save it as Calculator.htm then run it in your browser.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I do that at the end of the snippet as another option.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nothing new, but something for the neophyte to ponder. Some of the functions (algorithms) used by STL containers can be applied to a normal array to do inane things like copying, displaying, finding max/min, reversing, replacing, searching, shuffling, sorting, summation. This can really simplify your code.

thekashyap commented: Decent collection of examples.. +8
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

With the help of BCX I managed to create some C++ code that will allow you to send text to your printer and specify the font and other things. Play around with the options to suit your own needs. I have to admire the genius behind BCX, even though it spits out more code than you want! NOTICE: Please experiment with this code, modify it, improve it, and claim it as yours!!!!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Short little sound files of chicken, horses, dogs, cars, trains and other annoying things is the realm of the wave file (.wav). These are easy to play and guaranteed to confuse grandpapa. Again, we are using Windows' sound workhorse winmm.lib file. Ze function this time is PlaySound(). Here is ze C++ console code.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can have fun and learn something too. Not too much fun though! Here we take a lighthearted look at C++ string, various ways to assign a string and substring, spell forward and reverse, find characters and substrings, append, insert, replace, remove characters, separate a sentence into words and more.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A real useful piece of code, hence I put it under Z. It does nothing but open and close the door of the CD-ROM player, and pushes the tray in and out. Should your coffee be too hot, you can put it on the moving tray and cool it off! Get the old computer out of the attic, we found a use for it! Seriously, just a quick look at the many things the mciSendString() function can do.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is an example of a singly linked list allowing you to enter a number of names and associated ages. The twist is that the names are inserted into the list in ascending order. When the list is displayed, it is already sorted by name.

Note:
This is not an exercise in safe data input. While precautions have been taken, any fool can stress the language easily.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Thanks keithr, for making the code work with VisualStudio.Net (2003). Looks like different compilers have somewhat different header requirements. Oh the joy of C++ headers!!!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Standard Template Library (STL) vector is tempting. The burden of dimensioning an array is removed, and there are many wonderful functions to explore. The learning curve is a little steep, it will make your head swell, but in the end it's all worthwhile. Take a look at some of the code that is supposed to make programming easier.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's expand the decimal to binary converter to include, amongst others, octal and hexadecimal conversions. Also shows how to exert some input control. Simple stuff!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's say you worked in the White House and had to keep two lists, one for the friends and one for the enemies. The boss came to you and said: "The Almighty talked to me out of a burning bush last night, telling me that I shall make my enemies my friends! Can you help me?"