vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Create a calculator using a dictionary ...

''' dict_calculator101.py
create a simple reverse polish calculator using a dictionary
'''

import math

def do_op(op, a=1, b=1):
    """use of a dictionary similar to C's switch/case"""
    return {
    '+': lambda: a + b,
    '-': lambda: a - b,
    '*': lambda: a * b,
    '/': lambda: a / b,
    '//': lambda: a // b,   # floor
    '**': lambda: a ** b,   # power
    'sin': lambda: math.sin(a),
    'cos': lambda: math.cos(a),
    'asin': lambda: math.asin(a),
    'acos': lambda: math.acos(a)
    }[op]()

# testing ...
# 355/113.0 pi approx.
print(do_op('/', 355, 113.0))  # 3.1415929203539825
# sqroot(25)
print(do_op('**', 25, 0.5))    # 5.0
# asin(sin(0.5))
print(do_op('asin', do_op('sin', 0.5)))  # 0.5

Your mission is to expand the dictionary.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Once you are on the internet, you have to come up with passwords. After a while it will be difficult to remember those passwords. You could write them down somewhere, but the wrong person could find them. Why not have Python help you to come up with a logical password whose logic of creation might help you to recall it.

''' password_create101.py
a simple program to create a password you can remember
'''

# use something you can remember
# like your first and last name and year of birth
first = "David"
last = "Herzig"
year = 1993

# first 3 letters of first name, last name and last 3 numbers of year
password = first[:3] + last[:3] + str(year)[-3:]
print(password)  # DavHer993

# or reverse order of the name
password = last[:3] + first[:3] + str(year)[-3:]
print(password)  # HerDav993

# throw in your special character and shorten the year
c = "*"
password = first[:3] + last[:3] + str(year)[-2:] + c
print(password)  # DavHer93*

# change position of c for different password
password = first[:3] + last[:3] + c + str(year)[-2:]
print(password)  # DavHer*93

If you have other coding ideas, please post them in this thread.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Two third party Python modules imageio and visvis make it easy to load and view images. The modules come with the pyzo scientific package or can be downloaded separately. Module imageio can read many image file formats as shown in
http://imageio.readthedocs.org/en/latest/formats.html

You could also replace your image file name directly with a URL containing an image, for example
image_file = "Lake2.jpg"
could be changed to
image_file = "http://i.imgur.com/3MnBqHh.jpg"
and your picture would simply come from the internet.

Gribouillis commented: interesting +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Your problem is in function gen(), the list comprehension should be ...

def gen(number, b=100000):
    return [random.randint(0, b) for x in xrange(number)]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a simple exploration of the goslate module (uses the Google Translate API) to translate some common languages. However, some IDE's create character problems.

Note: Your computer has to be connected to the Internet to access Google.

Slavi commented: Awesome +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Snow, deer and mountains make a Jeep 4x4 about the best thing to drive.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one way that I use frequently ...

""" tk_setup.py

Using cx_Freeze with Python33 to package a Tkinter GUI toolkit
program to an executable file (.exe in Windows OS).  Module
cx_Freeze also is available for Unix systems.

Put this setup program and your Tkinter program file into the same
directory.  Then run the setup script with the correct Python version.
You may have to change the filename in this setup script and also edit
name, version and description in setup() if you so desire.

A directory 'build' is created with a subdirectory 'exe.win32-3.3'
containing all the files needed for distribution including the
.exe file named after the Tkinter program file.

The total distribution has a size of about 14 MB

I used:
cx_Freeze-4.3.3.win32-py3.3.exe
from:
https://pypi.python.org/pypi?:action=display&name=cx_Freeze&version=4.3.3

tested with Python3.3.3
"""

import sys
from cx_Freeze import setup, Executable

# replaces commandline arg 'build'
sys.argv.append("build")  

# change the filename to your program file --->
filename = "tk_circle2.py"

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
    name = "Circle",
    version = "1.0",
    description = "cx_Freeze Tkinter script",
    executables = [Executable(filename, base=base)])

I used Windows 8.1

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A winter storm is closing in with 18 inches of snow expected above 7000 feet. Let's see how my new Jeep will do.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

“You only live once, but if you do it right, once is enough.”
... Mae West

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You need to create a random list for the bucket_sort argument lst ...

import time
import random

#BUCKET SORT (up to 30)

def bucket_sort(lst):
    bucket, bucket1, bucket2 = [], [], [] #The three empty buckets
    #Populating the buckets with the list elements
    for i in range(len(lst)):
        if lst[i] in range(11):
            bucket.append(lst[i])
        elif lst[i] in range(21):
            bucket1.append(lst[i])
        elif lst[i] in range(31):
            bucket2.append(lst[i])

#Prints the buckets and their contents

    print "Bucket:",bucket
    print "Bucket1:",bucket1
    print "Bucket2:",bucket2


#The actual sorting

    bucket.sort()
    bucket1.sort()
    bucket2.sort()
    final_lst = bucket + bucket1 + bucket2
    print "Sorted list:", final_lst

# create random list with 30 integers from 0 to 50
lst = random.sample(range(50), 30)
print lst  # test

# call bucket_sort and time it
t0 = time.clock()
bucket_sort(lst)
print time.clock() - t0, "seconds process time"

The print statements inside your bucket_sort will be the slowest part.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sorry, I don't have a Linux box at the moment. We have quite a few Linux users here, hopefully somebody can download the tarfile for Linux and look at it.

I think Anaconda is very similar and has some better installation instructions for Linux.
See:
http://continuum.io/downloads#34
and click on the Linux symbol.

Or see:
http://docs.continuum.io/anaconda/install.html#linux-install

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

On Windows you have three ways to code ...
IEP.exe
ipython_notebook.exe
ipython_qtconsole.exe
all in the folder
C:\pyzo2014a

There is also
idle.exe
in folder
C:\pyzo2014a\Scripts

There should be Linux counterparts to this.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Did you install it?

http://www.pyzo.org/downloads.html#installation-instructions

After installation click on the pyzo icon to start up their nicely made IDE.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

One of the ways would be to use slicing ...

''' matrix_slice101.py
slice a 5x5 matrix out of a 10x10 matrix
'''

# matrix 10x10
matrix10x10 = \
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]

matrix5x5 = []
# use slicing [:5] to get first 5 rows
for row in matrix10x10[:5]:
    # use slicing [:5] to get first 5 elements in each row
    matrix5x5.append(row[:5])

# check result
import pprint
pprint.pprint(matrix5x5)

'''result ...
[[10, 11, 12, 13, 14],
 [20, 21, 22, 23, 24],
 [30, 31, 32, 33, 34],
 [40, 41, 42, 43, 44],
 [50, 51, 52, 53, 54]]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe a module like xlrd might do it.

https://pypi.python.org/pypi/xlrd

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another number oddity ...

''' perfect_digit-to-digit_invariant.py
the Canouchi number is a natural number that is equal to the
sum of its digits each raised to a power equal to the digit

there are only two Canouchi numbers in the decimal system,
3435 and 438579088 

see ...
http://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant
'''

# number 3435 implies 3**3 + 4**4 + 3**3 + 5**5 = 3435
# test it ...
print(3**3 + 4**4 + 3**3 + 5**5)   # 3435
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I think Schol-R-LEA is correct.

Not sure if this helps ...

I used IDLEX installed on Python341 and it worked fine, could also read the resulting file. The chinese characters displayed properly.

Again, same code as above.

Same holds true for regular IDLE and Python33.

OS = Windows 8.1

You can get IDLEX from:
http://idlex.sourceforge.net/download.html

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another way is to use IronPython to create a .NET exe file.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This one is free, but only converts C# to Python. You could still use it to learn.
http://codeconverter.sharpdevelop.net/SnippetConverter.aspx

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You might want to check:
https://www.varycode.com/converter.html

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

China's Tianhe-2 supercomputer is the fastest in the world at 33.86 petaFLOPS, or 33.86 quadrillion floating point operations per second.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just the very basics on how to draw a rotated text using the Python GUI toolkit PySide (public PyQt). Please experiment and embellish.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

UK's wind farms generated more power than its nuclear power stations on October 20th 2014.

Read more:
http://www.bbc.co.uk/news/business-29715796

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Microsoft Board of Directos has given the new CEO Satya Nadella a pay package worth $84.3 million, making him one of the top earners in the tech industry.

News of the package comes less than a month after Mr Nadella advised women not to ask for a pay rise but to have "faith in the system".

see http://www.bbc.com/news/business-29705418

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Finding the lowest, highest, total, and average of the numbers in a list is easy as slate already mentioned. To develop a user friendly way to enter 20 numbers into a list is your challenge.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You might want to look at Python's deque object.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Printing i should not give you a string ...

mystr = "str is a function in Python and should not be used as a variable name"

for i in range(len(mystr)):
    print(i)

Also explore the string functions isalpha(), islower() and isupper().

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

With the advent of Python33 the module time has received a high resolution timer/counter. Here we use time.perf_counter() in a decorator to conveniently time two test functions.

Gribouillis commented: very nice +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

What are the natural disasters that you have to learn to live with in your area?

I just moved from the Las Vegas area where we had to live with drought, very high summer temperatures (up to 45 degree C) and the occasional smoke of a far away wildfire. The new area is further north in the mountains near Lake Tahoe. Now I have to learn to live with drought, forest fires that are closer, mountain passes that are closed due to snow, and an occasional mild earthquake.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

"Honey, I can't come to bed now, someone on the internet is wrong!"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sad news indeed, rest in peace Melvin!

Looking at his age, I should rename myself the "More Ancient Dragon"

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python has an easy syntax, the trick is to get to know and use its many modules.
A number of these modules are already written in higher speed C.

Concentrate on your algorithms, you can always optimize for speed later.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another option, insert one element at a time. Do it in reverse order if you want to keep the insert position constant ...

mylist1 = [1,2,3]
mylist2 = ['a','b','c']

for e in reversed(mylist2):
    # insert each element e at index 2 of mylist1
    mylist1.insert(2, e)

print(mylist1)  # [1, 2, 'a', 'b', 'c', 3]
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another way ...

# round floats
x = 355/113.0
print(x)
print(round(x, 2))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The more recent WinPython dowloads are now at ...
http://sourceforge.net/projects/stonebig.u/files/Winpython_2.7/
http://sourceforge.net/projects/stonebig.u/files/Winpython_3.3/
http://sourceforge.net/projects/stonebig.u/files/Winpython_3.4/

Whatever you download has a file named
IPython Notebook.exe
that runs the notebook on your default browser.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are a large number of Python programming videos on YouTube.
YouTube itself is written using Python.

Example ...
http://www.youtube.com/watch?v=4Mf0h3HphEA&feature=channel
or ...
https://www.youtube.com/watch?v=tKTZoB2Vjuk

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a general example that might help ...

''' distance_two_points.py
calculate the distance between two points given the coordinates
of the points (x1, y1) and (x2, y2) in a 2D system
'''

import math

def get_distance(x1, y1, x2, y2):
    '''
    returns distance between two points using the pythagorean theorem
    the function parameters are the 2D coordinates of the two points
    '''
    dx = x2 - x1
    dy = y2 - y1
    return math.sqrt(dx**2 + dy**2)

sf = "Distance between point({}, {}) and point({}, {}) is {}"

x1, y1 = 1, 3
x2, y2 = 4, 7
print(sf.format(x1, y1, x2, y2, get_distance(x1, y1, x2, y2)))

x1, y1 = 2, 5
x2, y2 = 11, 23
print(sf.format(x1, y1, x2, y2, get_distance(x1, y1, x2, y2)))

''' result ...
Distance between point(1, 3) and point(4, 7) is 5.0
Distance between point(2, 5) and point(11, 23) is 20.1246117975
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
python = 77777
if python:
    print("You picked a good language")
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just for kicks, here is the original and encoded image file used ...
1edb0bfc24e1afbcfa7d358659e147ecf690d29feeafb497cc3020c47bfead8d

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's say you want to send a short private message to your friend, but don't want grandma to snoop around and find it. One way is to use the Python Image Library (PIL) and hide the message in a picture file's pixels. Just looking at the picture you will barely detect any difference between the before and after picture. All your friend needs is the decode_image portion of this simple code to get the message back.

Slavi commented: Pretty damn cool +6
ddanbe commented: Great! +15
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This simple key logger shows any character/special key when pressed.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Pyside GUI toolkit (public PyQt) lets you bring up an interactive web page with its QWebView widget. Here is a simple example.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This class gives a specified Tkinter widget a tooltip that appears as the mouse is above the widget. You can improve the code by putting in a time delay.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Module pprint (PrettyPrint) has been improved in Python34 ...

''' pprint34.py
pprint.pprint(object, stream=None, indent=1, width=80,
    depth=None, *, compact=False)
compact=True will print as many sequence elements as will fit within
the given width (default is 80) on each line
parameter compact is new in Python34
'''

import pprint

mylist = list(range(1000, 1100))

pprint.pprint(mylist, compact=True)

''' result ...
[1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012,
 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025,
 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038,
 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051,
 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064,
 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077,
 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090,
 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099]
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Not used very often, but has possibilities ...

''' str_templating101.py
exploring Python module string
dns
'''

import string

def change_text(template, sub_dictionary):
    t = string.Template(template)
    return t.substitute(sub_dictionary)

# variables to be substituted begin with a $, use $$ to literalize $
template = 'The $animal says "$sound, my name is $name!"'

# create dictionaries for each animal
d_cow = dict(animal='cow', sound='mooh', name='Hilda')
d_dog = dict(animal='dog', sound='woof', name='Rover')
d_cat = dict(animal='cat', sound='meow', name='George')

for animal_dict in (d_cow, d_dog, d_cat):
    print(change_text(template, animal_dict))


''' result ...
The cow says "mooh, my name is Hilda!"
The dog says "woof, my name is Rover!"
The cat says "meow, my name is George!"
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Moon's mass is 0.0123 times the Earth's mass.
Its Density is 0.607 times the Earth's density.
The Moon's radius is 1737.5 km (1079.6 miles).
What is the Earth's radius?

Solve it with a Python program.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Python interpreter searches for module "serial" first in the working directory, then in its builtin modules in directory Lib, then in its packages.

When it finds a file serial.py in the working directory it will import your code file instead of the module. So please do not name any of your code files the same as a module file you want to import.

Just one of the nasty surprises Python has waiting for you!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Windows binaries are also still available at:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

Pyglet uses AVbin for sound, so you could check that:
http://avbin.github.io/AVbin/Home/Home.html

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An interesting possibility ...

''' secret_message101.py
explore secret messages with Python
'''

def make_length_even(text):
    '''
    if the text character count is an odd number,
    pad the text with a period to make it even
    '''
    if len(text) & 1:
        text = text + '.'
    return text

def split_odd_even(text):
    '''
    split a text string into a string that contains
    all the even indexed characters and a string
    that contains all the odd indexed characters
    '''
    even_str = ""
    odd_str = ""
    odd = 1
    even = 0
    for k in range(len(text)/2):
        even_str += text[even]
        odd_str += text[odd]
        odd += 2
        even += 2
    return even_str, odd_str

def combine_strings(even_str, odd_str):
    text = ""
    for c1, c2 in zip(even_str, odd_str):
        text += c1 + c2
    return text

text = "see you at seventeen hours in the park"

text = make_length_even(text)
print(text)  # test

even_str, odd_str = split_odd_even(text)

print(even_str)  # seyua eete or ntepr
print(odd_str)  # e o tsvnenhusi h ak

# now this would give you your original text back
text2 = combine_strings(even_str, odd_str)

print(text2)   # see you at seventeen hours in the park

# now comes the trick, combine the two string in reverse order
# and you get one secret string that you could send out
text_rev = combine_strings(odd_str, even_str)

print(text_rev)  # es eoy utas veneetneh uosri  nht eapkr


# reverse your process to get the original text back
# from the secret string ...
even_s, odd_s = split_odd_even(text_rev)
print(even_s)
print(odd_s)
# keep arguments in reverse order
text3 = combine_strings(odd_s, …