vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python module turtle makes it simple to draw graphics art similar to art done by the Logo language.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Who is Fred?

<M/> commented: lol +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using Python module turtle to draw a Koch snow fractal.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python has its charming sides.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A little fun with Python's turtle module drawing a number of random stars in the dark sky.

ddanbe commented: Nice! +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sailing was my sport.

GrimJack commented: Yes! I got my captains license and sailed bathtubs +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe he was playing a game of "Marco and Polo"?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use the regular swap, it makes your code simpler to maintain by others.

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

Tuples, since they are immutable (can not be changed), are also useful for keys in a dictionary.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Development time with Python is much faster than with C++
The main supporter of Python is Google and they rather successfully use Python internally.

Python, being a high level language, complements the low level C++ language very well. So it is worthwhile knowing both.

Python, similar to Java, is portable across several Operating Systems.

nitin1 commented: so, according to you should i learn it like syntax and loops and all that things ? can you elaborate ? thanks. +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a long message to display in a large readable font, then this little Tkinter GUI toolkit code might help.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can give endswith() a tuple of choices, for instance
s.endswith(("ion", "ION"))

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You mean something like this ...

import time

def get_int(prompt="Enter an integer: "):
    """this function will loop until an integer is entered"""
    while True:
        try:
            # return breaks out of the endless while loop
            return int(input(prompt))
        except ValueError:
            print("Try again, value entered was not an integer.")

x = get_int ("Enter a number: ")
for i in range(1,13):
   print(x*i)
   time.sleep(1.2)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You are close. Just a reminder, don't use sum, min, max as variable names since they are functions in Python. I like to prefix with 'my'. Start with a high mymin value (let's say 100) and make it x if x is lower. With mymax you start low (zero) and make it x if x is higher.

Once you learn about lists then you can apply methods sum(), min() and max() and your life will be simpler. For example ...

n = int(raw_input("Enter the total number of scores: "))
mylist = []
sn = 1
for i in range(n):
    x = int(raw_input("Enter score " + str(sn) + " : " ))
    mylist.append(x)
    sn += 1

mysum = sum(mylist)
# mysum needs to be a float
# or you get integer division in Python2
average = 1.0*mysum / n

print "Total = " + str(mysum)
print "Average = " + str(average)
print "Minimum = " + str(min(mylist))
print "Maximum = " + str(max(mylist))

Once you get better with Python27, you will actually code this way ...

n = int(raw_input("Enter the total number of scores: "))
mylist = []
for ix, k in enumerate(range(n)):
    x = int(raw_input("Enter score {} :".format(ix+1)))
    mylist.append(x)

# mysum needs to be a float
# or you get integer division in Python2
mysum = float(sum(mylist))
average = mysum / n

print("Total = {}".format(mysum))
print("Average = {}".format(average))
print("Minimum = {}".format(min(mylist)))
print("Maximum = {}".format(max(mylist)))
ddanbe commented: He! Your answer also helped me! +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Look at this example, it should give you hints ...

''' input_integer1.py
loop until you get an integer input
'''

# make input() work with Python2 and Python3
try:
    input = raw_input
except:
    pass

def get_int():
    """this function will loop until an integer is entered"""
    while True:
        try:
            # return breaks out of the endless while loop
            return int(input("Enter an integer: "))
        except ValueError:
            print("Try again, value entered was not an integer.")

myinteger = get_int()
print("You entered %d" % myinteger)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We are already a "Planet of the Apes", only the apes still have human form.

Reverend Jim commented: We are amused. +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nice effort!
See if you can increase your knowledge of Python this way ...

import time

def main():
    nsec = int(input("Enter number of seconds: "))
    # range from nsec to zero backwards
    for x in range(nsec, -1, -1):
        time.sleep(1)
        print(formatTime(x))

def formatTime(x):
    minutes, seconds_rem = divmod(x, 60)
    # use string formatting with C type % specifiers
    # %02d means integer field of 2 left padded with zero if needed
    return "%02d:%02d" % (minutes, seconds_rem)

main()

If you are not comfortable with ranging backwards you could also use
for x in reversed(range(nsec+1)):

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To get a nice display you need to use a GUI toolkit like the one that comes with your Python installation. Here is an example, study it carefully ...

''' tk_counter_down101.py
count down seconds from a given minute value
using the Tkinter GUI toolkit that comes with Python
tested with Python27 and Python33
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
import time

def count_down():
    # start with 2 minutes --> 120 seconds
    for t in range(120, -1, -1):
        # format as 2 digit integers, fills with zero to the left
        # divmod() gives minutes, seconds
        sf = "{:02d}:{:02d}".format(*divmod(t, 60))
        #print(sf)  # test
        time_str.set(sf)
        root.update()
        # delay one second
        time.sleep(1)


# create root/main window
root = tk.Tk()

time_str = tk.StringVar()

# create the time display label, give it a large font
# label auto-adjusts to the font
label_font = ('helvetica', 40)
tk.Label(root, textvariable=time_str, font=label_font, bg='white', 
         fg='blue', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)

# create start and stop buttons
# pack() positions the buttons below the label
tk.Button(root, text='Count Start', command=count_down).pack()
# stop simply exits root window
tk.Button(root, text='Count Stop', command=root.destroy).pack()

# start the GUI event loop
root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another simplification ...

def askUser():
    checkAgain = raw_input("Would you like to check another credit card (yes, no, quit)? ").lower()
    if checkAgain[0] == 'y':
        main()
    elif checkAgain[0] == 'n' or checkAgain[0] == 'q': 
        return None
    else:
        askUser()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A nice effort!
You can simplify your first function ...

def getEveryOther(creditCardNum):
    mylist = []
    for x in creditCardNum:
        mylist.append(int(x))
    firstEveryOther = mylist[-2::-2]
    secondEveryOther = mylist[-1::-2]
    return firstEveryOther, secondEveryOther

... and call it with ...
firstEveryOther, secondEveryOther = getEveryOther(creditCardNum)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Also note that json (JavaScript Object Notation) expects your strings to be in double quotes.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Yes, you can learn to play the piano in less than one day. But, who wants to listen?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Find all the duplicate words in a text.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple way to find duplicate words in a text. In this case the text is preprocessed to eliminate punctuation marks and set all words to lower case.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Simply add the numbers in each list together with function sum() and divide by the number of items in the list.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A little IronPython code ...

''' ip_mouseclick_location1.py
download and install 
IronPython-2.7.4.msi 
or latest version from:
http://ironpython.codeplex.com/

Form designed with SharpDevelop 4.2.1

tested with IronPython 2.7.4
'''

import clr

clr.AddReference('System.Drawing')
clr.AddReference('System.Windows.Forms')

import System.Drawing
import System.Windows.Forms

from System.Drawing import *
from System.Windows.Forms import *

class Form1(Form):
    def __init__(self):
        self.InitializeComponent()

    def InitializeComponent(self):
        self.SuspendLayout()
        # 
        # Form1
        # 
        self.BackColor = System.Drawing.Color.Yellow
        self.ClientSize = System.Drawing.Size(350, 250)
        self.CenterToScreen()
        self.Name = "Form1"
        self.Text = "MyForm"
        self.MouseClick += self.Form1MouseClick
        self.ResumeLayout(False)


    def Form1MouseClick(self, sender, e):
        ''' position is within form borders '''
        sf = "mouse clicked at x={} y={}".format(e.X, e.Y)
        self.Text = sf


form = Form1()
Application.Run(form)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Using two Tkinter windows ...

''' tk_toplevel_window_hides_root1.py
hide the root window temporarily with a top level window
'''

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def create_top():
    top = tk.Toplevel(root, bg='red')
    top.title("top")
    # use width x height + x_offset + y_offset (no spaces!)
    # set top the same as root so it will hide it below
    top.geometry("%dx%d+%d+%d" % (200, 150, 100, 50))    
    tk.Button(top, text='Destroy Top Window', command=top.destroy).pack()

root = tk.Tk()
root['bg'] = 'yellow'
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (200, 150, 100, 50))
root.title("root")

tk.Button(root, text='Create Top Window', command=create_top).pack()

root.mainloop()

Another approach is lower and lift ...

''' tk_lower_lift_windows.py
lower and lift Tkinter windows
'''

from functools import partial
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

# create the root window
root = tk.Tk()
root['bg'] = 'yellow'
root.title("root")
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (200, 150, 100, 30))

# create a top level window
top = tk.Toplevel(root, bg='red')
top.title("top")
# use width x height + x_offset + y_offset (no spaces!)
top.geometry("%dx%d+%d+%d" % (200, 150, 170, 80))    

# widgets for root window
tk.Button(root, text='lower root window below top window', 
          command=partial(root.lower, top)).pack()
tk.Button(root, text='lift root window above top window', 
          command=partial(root.lift, top)).pack()

# widgets for top window
tk.Button(top, text='lower top window below root window', 
          command=partial(top.lower, root)).pack()
tk.Button(top, text='lift top window above root window', 
          command=partial(top.lift, root)).pack()

root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Applying the famous Gauss algorithm to determine the date of Easter for a given year.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I have a working algorithm, but it is in Python. You should be able to apply it to C++ code. Note: In Python // is an integer division.

See:
http://www.daniweb.com/software-development/python/threads/20774/starting-python/19#post2017691

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Very good!

Follow the Python style guide and your code will look rather polished.

I had to smile when I saw the long-worded camel style of C# show up in your Python code. My problem is that I am not that good of a typist.

The radius was a little trick question, it assumed the perimeter of a polygon being s * n and that with high n and short s being almost equal to a circle's circumference from which you could have calculated r

ddanbe commented: Helpful! +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a little fun with Python's named tuple, behaves like a class but is much leaner.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Calculate the area of a regular polygon given side_length s and number of sides n.

Also if you had
s = 0.01
n = 1000
which approaches a circle. What would the radius of that circle be?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The {} in the format string are called format fields where format(obj1, obj2, ...) puts the objects it contains. It was introduced starting with Python 3.0 and later adopted by Python 2.7. It replaces the older C type % specifiers.

Just a taste ...

# new and fancier Python output formatting ...
# string is default and does not have a type specifier
# {0} and {1} index the format fields
sf = 'the {0} jumped over the {1}!'
print(sf.format('mouse', 'moon'))
# no indexing needed if the objects in format() are in order
sf = 'the {} jumped over the {}!'
print(sf.format('mouse', 'moon'))
# or use keyword args
sf = 'the {ms} jumped over the {mn}!'
print(sf.format(ms='white mouse', mn='full moon'))

# allow 10 char spaces, left align (<) is default
print('the {0:10} jumped over the {1:10}!'.format('mouse', 'moon'))
# use right align (>)
print('the {0:>10} jumped over the {1:>10}!'.format('mouse', 'moon'))
# use fill (specify a single character)
print('the {0:{fill}>10} jumped over the {1:{fill}>10}!'.format(
'mouse', 'moon', fill='-'))

''' result ...
the mouse jumped over the moon!
the mouse jumped over the moon!
the white mouse jumped over the full moon!
the mouse      jumped over the moon      !
the      mouse jumped over the       moon!
the -----mouse jumped over the ------moon!
'''

Pretty powerful stuff ...

food_price_dict = {
'milk' : 3.67,
'butter' : 1.95,
'bread' : 1.67,
'cheese' : 4.67
}
# print all dictionary items in a table
for food, price in sorted(food_price_dict.items()):
    # food has 10 char field, …
Gribouillis commented: nice examples +14
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I would enter tip and tax in percent ...

def main():
    # this program calculates the total price of a meal after inputting
    # cost of food, percent tip and sales tax
    print ('Welcome to the Meal Calculator Program:')
    print()
    # get the cost of food using the input function
    food_cost = float(input("Please enter the price of your meal: "))
    # calculate tip
    tip = float(input("Tip percent used today is: "))
    # calulate sales tax
    tax = float(input("Tax percent used today is: "))

    #calculate total cost here, using inputted values
    total_cost = food_cost + food_cost*tip/100 + food_cost* tax/100

    format_str = """\
The total cost based on ${:.2f} food cost
{:.2f}% tip and {:.2f}% tax is ${:.2f}
    """
    print(format_str.format(food_cost, tip, tax, total_cost))


# calls main
main()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Run an external program from within Python code with
subprocess.call(["program-name", "arg1", "arg2"])
rather than os.system("program-name arg1 arg2")
since os.system() does not allow the Python program
to run in the background, whereas subprocess does.

Example ...

# play a midi file with a small external midiplayer:
# from http://www.kanatachoralsociety.ca/memberscorner/AKoffPlr.exe
# mplayer2.exe works too, but not wmplayer.exe
import subprocess
subprocess.call(["C:/Midi_stuff/AKoffPlr.exe", "DaarG.mid"])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Write a Python program that goes through a given text and gives the number of the longest words and the average length of all words.

farmwife commented: good motivation +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Get a listbox filled with a given directory's filenames, select a filename ...

''' ps_Listbox_filenames1.py
load a PySide listbox with filenames in a given directory
show the selected (clicked) filename in a label

PySide is the license free version of PyQT
for Python33 you can use the Windows self-extracting installer
PySide-1.1.2.win32-py3.3.exe
(PyQT483 equivalent) from:
http://qt-project.org/wiki/PySide
or:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

'''

from PySide.QtCore import *
from PySide.QtGui import *
import os
import glob

class MyForm(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 240, 380)

        self.label_dir = QLabel("Enter/Edit Directory:")
        # pick a directory you have as default
        #self.edit_dir = QLineEdit("C:/Temp/Zcrypt/Art123")
        self.edit_dir = QLineEdit("C:/Zz4/Sz1")

        self.button_load = QPushButton("Load Filenames")
        # bind the button click to a function reference
        # newer connect style used with PyQT 4.5 and higher
        self.button_load.clicked.connect(self.on_click)

        self.listbox = QListWidget()
        # new connect style, needs PyQt 4.5+
        self.listbox.clicked.connect(self.on_select)

        self.label_result = QLabel()        

        # layout the 2 widgets
        vbox = QVBoxLayout()
        vbox.addWidget(self.label_dir)
        vbox.addWidget(self.edit_dir)
        vbox.addWidget(self.button_load)
        vbox.addWidget(self.listbox)
        vbox.addWidget(self.label_result)
        self.setLayout(vbox)

    def on_select(self):
        """
        an item in the listbox has been clicked/selected
        """
        selected = self.listbox.currentItem().text()
        self.label_result.setText(selected)

    def on_click(self):
        directory = self.edit_dir.text()
        try:
            # make it the working directory
            os.chdir(directory)
        except FileNotFoundError:
            self.label_result.setText("No such directory")
            self.listbox.clear()
            return
        #print(os.getcwd())  # test
        # create a list of all .jpg files in a given directory
        self.list_fnames = []
        #mask = "*.jpg"  # .jpg files only
        mask = "*.*"    # all files
        for path in glob.glob(mask):
            dirname, filename = os.path.split(path)
            #print(filename)  # test
            self.list_fnames.append(filename)
        #print(list_jpg)  # test
        self.listbox.addItems(self.list_fnames)
        sf = "{} items loaded".format(len(self.list_fnames))
        self.setWindowTitle(sf)
        pass


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

The next approach looks more innocent. First you send a normal looking text and later you send a string of numbers, where each number is an index in the normal text that rebuilds your message ...

''' xmas_letter_crypt101.py
hide a message in a boring lengthy xmas letter
first you send the xmas letter, later you send an index
string where each indexed character in the xmas letter
matches a message character (all lower case)
'''

import pprint
import random

def create_index_dict(text):
    '''
    return a character:index_list dictionary of a given text
    replace newlines with '~~'
    '''
    text = text.lower()
    index_dict = {}
    for ix, letter in enumerate(text):
        index_dict.setdefault(letter, []).append(ix)
    return index_dict

def index_message(index_dict, my_message):
    '''
    create the index string you can send
    each index matches a message char in the xmas letter
    '''
    # convert to lower case
    my_message = my_message.lower()
    index_str = ""
    n = 1
    for ix, c in enumerate(my_message):
        index_list = index_dict[c]
        # shuffle the index_list
        # and pick the first element
        # adds some randomness to index_str
        random.shuffle(index_list)
        index = index_list[0]
        # add a newline char after 10 indices
        # else add a space
        if n % 10 == 0:
            index_str += str(index) + '\n'
        else:
            index_str += str(index) + ' '
        n += 1
    return index_str

my_message = "Meet me at four thirty PM at the dog park elm tree"

# a typical xmas letter you can receive if you are unlucky
# make sure it has all your potential message characters in it
xmas_letter …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something else to play around with is a decoyed message ...

''' decoy_crypt101.py
create decoy crypted data that matches typical
English text letter frequency then replace every nth character
with a character of your message
you send out the decoyed message text and "nth info" separately
'''

import random

random.seed()

def create_decoy(mydict, size=1):
    '''
    create random decoy string that has English text letter frequency
    '''
    decoy_str = ""
    for letter, count in mydict.items():
        decoy_str += letter*count*size
    # convert string to list
    decoy_list = list(decoy_str)
    # random shuffle the list elements
    random.shuffle(decoy_list)
    # replace every 72nd element with a newline
    new_list = []
    for ix, item in enumerate(decoy_list):
        if ix % 72 == 0:
            new_list.append('\n')
        else:
            new_list.append(item)
    # join list to form a string, eliminate leading newline
    return "".join(new_list)[1:]

def embed_message(decoy_str, my_message, terminator='*'):
    '''
    use a random decoy string to embed a message
    here you replace every 7th character
    '''
    my_message = my_message.lower() + terminator
    new_list = []
    n = 0
    for ix, letter in enumerate(list(decoy_str)):
        # replace every 7th character
        # do not replace newline
        if ix % 7 == 0 and ix != 0 and \
            letter != '\n' and n < len(my_message):
            new_list.append(my_message[n])
            n += 1
        else:
            new_list.append(letter)
    return "".join(new_list)

def extract_msg(decoyed_str, terminator='*'):
    '''
    use a decoyed string and extract the embedded message
    '''
    new_str = ""
    for ix, letter in enumerate(list(decoyed_str)):
        # the message is hidden in every 7th character
        # exclude newline
        if ix % 7 == 0 and ix != 0 and letter != …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This short snippet shows you how to preprocess a text to remove punctuation marks, then do a word frequency count
using Counter() from the Python module collections. Finally, two sorts are applied to display words with matching
frequency in alphabetical order.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

We are probably sitting on a couple of thousand cruise missiles that have a limited shelf life. So it's “usem or losem”. That should help the rebels win. The only thing is that many of the "rebels" are extreme Islamists and AQ. If the extremists take over, it will make Assad look like a Sundayschool teacher.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The code shows you how to create a persistent to file dictionary of data using the python module shelve.

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

Without module re ...

word = 'Cat'
result = ''.join('a' for c in word)
print(result)  # aaa
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a small mildly optimized function to check if an integer is a prime number. For very large numbers use the Miller-Rabin primality test.

There have been questions why I used not n & 1 to check for even integer n. The more tradionaln % 2 == 0 is about 30% slower. So I gained a tiny bit more speed.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a hint ...

bottle = "vial jug canteen urn"
transport = "car automobile airplane scooter"

mydict = {}
for word in bottle.split():
    mydict[word] = 'bottle'

for word in transport.split():
    mydict[word] = 'transport'

#print(mydict)  # test

text_old = "he carried a jug of water and a canteen of brandy in his car"
print(text_old)

text_new = ""
space = " "
for item in text_old.split():
    if item in mydict.keys():
        text_new += mydict[item] + space
    else:
        text_new += item + space

print(text_new)

'''
he carried a jug of water and a canteen of brandy in his car
he carried a bottle of water and a bottle of brandy in his transport 
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Starting with Python3 the print statement has been replaced with a much more useful print() function. There is still a lot of Python2 code around, so be aware. Enjoy Python!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python for fun and joy, and Java for the bread.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Indian narcotic cop arrests racially competent erotic recluse after triple escape

woolworth

iamthwee commented: that was actually pretty good +0
Reverend Jim commented: Inspired +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Engineers from India make up 60% of the special visa recipients in the USA.