sneekula 969 Nearly a Posting Maven

Normally you build a house from the bottom up. Try to understand the basics of Python first and put the windows in later.

sneekula 969 Nearly a Posting Maven

Try it this way:

''' favemovies.py

with iPython on Windows use:
run C:\Python27\Atest27\Bull\favemovies.py view
'''

import sys
import pickle
# for Python3 replace Tkinter with tkinter
import tkinter as tk

def view():
    favorite_movies = pickle.load( open("films.db", "rb"))
    favorite_movies_string = "\n".join(favorite_movies)
    label['text'] = favorite_movies_string


win = tk.Tk()

label = tk.Label(win, bg='yellow')
label.pack()
if len(sys.argv) > 1:
    if sys.argv[1] == "view":
        view()
else:
    label['text'] = " usage: python favemovies.py view "

win.mainloop()
sneekula 969 Nearly a Posting Maven

Then you have to change your code to:

def message():
    label['text'] = 'Good morning'

# for Python3 replace Tkinter with tkinter
import Tkinter as tk

win = tk.Tk()

label = tk.Label(win)
label.pack()
message()

win.mainloop()
sneekula 969 Nearly a Posting Maven

Try:

def message():
    print('Good morning')

from Tkinter import *
tk = Tk()
message()
tk.mainloop()
sneekula 969 Nearly a Posting Maven

Apply append() this way:

i = 0
pack = []
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
while i < 17:
    sublist = mylist[i : i + 3]
    pack.append(sublist)
    i += 1
print (pack)
sneekula 969 Nearly a Posting Maven

Avoid using Python function names like list for variable names.

if you use
list = [1, 2, 3]
and later
abc_list = list('abc')
it won't work!

sneekula 969 Nearly a Posting Maven

I would use with, it closes your files properly. Also use a protocol for larger files:

import pickle

fname = "films.db"
with open(fname, "wb") as fout:
    # default protocol is zero
    # -1 gives highest prototcol and smallest data file size
    pickle.dump(favorite_movies, fout, protocol=-1)

# pickle load the object back in (senses protocol)
with open(fname, "rb") as fin:
    favorite_movies = pickle.load(fin)
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

What operating system are you using?

marcelocent commented: win7 +0
sneekula 969 Nearly a Posting Maven

Note that overlapping subs won't work with text.count():

text = "assesses"
sub = "sses"

print(text.count(sub))  # --> 1 ???
sneekula 969 Nearly a Posting Maven

I took the liberty to time some of the approaches:

''' str_count_sub_timing_hperf.py
timing functions that count the number of sub_strings in a string
using high performance time.perf_counter() 
new in Python 3.3 and higher
'''

import time

def count_tony(text, sub):
    return sum(text[n:].startswith(sub)
           for n in range(len(text) - len(sub) + 1))

def count_snee(text, sub, start=0):
    count = 0
    while True:
        ix = text.find(sub, start)
        if ix < 0: break
        start = ix + 1
        count += 1
    return count

text = "this person assesses your performance"
sub = "sses"

# returned value is in fractional seconds
start = time.perf_counter()
result1 = count_tony(text, sub)
end = time.perf_counter()

elapsed = end - start
print("count_tony('{}', '{}') --> {}".format(text, sub, result1))
print("elapsed time = {:0.6f} micro_seconds".format(elapsed*1000000))

start2 = time.perf_counter()
result2 = count_snee(text, sub)
end2 = time.perf_counter()

elapsed2 = end2 - start2
print("count_snee('{}', '{}') --> {}".format(text, sub, result2))
print("elapsed time = {:0.6f} micro_seconds".format(elapsed2*1000000))

''' result (Python 3.4.1 64bit)-->
count_tony('this person assesses your performance', 'sses') --> 2
elapsed time = 38.228700 micro_seconds
count_snee('this person assesses your performance', 'sses') --> 2
elapsed time = 5.119915 micro_seconds
'''
Slavi commented: time well spent! :D +5
sneekula 969 Nearly a Posting Maven

Slowing down the Earth to a speed that would make it fall into the Sun within a few days time, would flatten it like a ripe tomato hitting a wall.

sneekula 969 Nearly a Posting Maven

What external force could slow down the Earth orbital speed?

sneekula 969 Nearly a Posting Maven

You have this execution/evaluation order:
1) if (i%3 == 0 && i%5 == 0)
2) else if (i%3 == 0)
3) else if (i%5 == 0)
4) else

Here 2) and 3) could be swapped

If 1) is true then the else conditions 2) 3) 4) will not be evaluated.
If 1) is false then 2) will be evaluated
If 2) is true 3) and 4) will be skipped
If 2) is false then 3) will be evaluated and so on

Let's say you had this evaluation order and i = 15:
1) if (i%3 == 0)
2) else if (i%3 == 0 && i%5 == 0)
3) else if (i%5 == 0)
4) else
then 1) would be true and you would never reach 2)

Doing pseudo code on a piece of paper really helps.

sneekula 969 Nearly a Posting Maven

Hmm:

''' str_find_sub_index.py
explore
s.find(sub[ ,start[,end]]) returns index or -1
'''

text = "trans panamanian bananas"
sub = "an"

start = 0
count = 0
while True:
    ix = text.find(sub, start)
    if ix < 0:
        break
    # move up start in function find()
    start = ix + 1
    count += 1
    #print(ix, count)  # test

print("'{}' appears {} times in '{}'".format(sub, count, text))

''' output -->
'an' appears 6 times in 'trans panamanian bananas'
'''
sneekula 969 Nearly a Posting Maven

@ivel
I looked at the code you have written and at NathanOliver's helpful suggestions. I came to the conclusion that you need beginner's help.

I took your code and corrected it, please study it:

/* modulus_exercise101.cpp
Write a program that counts the numbers from 3 to 117.
For multiples of three add 3 instead of 1
For the multiples of five add 5 instead of 1.
For numbers which are multiples of both three and five add 15
instead of 1.

Ex: If we are looking at numbers 5 to 15 (inclusive),
the program would output 39

compiled with mingw32-g++.exe on CodeBlocks IDE
*/

#include<iostream>

using namespace std;

int main()
{
    int x, y;
    int sum = 0;

    /*
    cout << "Choose starting number (from 3-117) " << endl;
    cin >> x;
    cout << "Choose ending number (from 3-117) " << endl;
    cin >> y;
    */
    // for testing only
    x = 5; y = 15;

    for (int i = x; i <= y; i++)
    {
        // do this conditional statement first
        if (i%3 == 0 && i%5 == 0)
        {
            sum += 15;
        }
        else if (i%3 == 0)
        {
            sum += 3;
        }
        else if (i%5 == 0)
        {
            sum += 5;
        }
        else
        {
            sum += 1;
        }
    }

    cout << "The total output between " <<x<< " and " <<y<< " is " << sum;

    return 0;
}

Your conditional if statements have to be in a certain order and you also have …

ddanbe commented: Nice +15
sneekula 969 Nearly a Posting Maven

@cambalinho
you are mixing char and int types, do the proper casts and your approach will work:

// str_Upper.cpp
// convert a string to all upper case

#include <iostream>
#include <string>

using namespace std;

string Upper(string text)
{
    string result;

    result.resize(text.size());
    for(int i = 0; i < text.size(); i++)
    {
        if ((int) text[i] > 96 && (int) text[i] < 123)
            result[i] = (char) ((int) text[i] - 32);
        else
            result[i] = text[i];
    }
    return result;
}

int main()
{
  string s = "A test this is 123";

  cout << s << endl;
  cout << Upper(s) << endl;

  return 0;
}

/* output -->
A test this is 123
A TEST THIS IS 123
*/
cambalinho commented: thanks +3
sneekula 969 Nearly a Posting Maven

Something like that:

// removes the third bit, simple way to create upper case char
char toupper(char ch)
{
  return ch & 0xDF;
}

Sorry doesn't handle numbers etc.

cambalinho commented: thanks +0
sneekula 969 Nearly a Posting Maven

Give us a short example of what your project data looks like.

sneekula 969 Nearly a Posting Maven
    Using the LXTerminal -->
    cd rpi_python
    python hello_arg2.py sayhi
    or -->
    python hello_arg2.py saybye
sneekula 969 Nearly a Posting Maven

On my Raspberry Pi computer I came up with this:

#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
Save this file as hello_arg2.py in folder
/home/pi/rpi_python

Note: line 1 has been changed to fit Debian/Rasbian Linux

Results in the Linux Python2 shell -->
>>> import sys
>>> sys.argv = ["hello_arg2.py", "sayhi"]
>>> execfile("/home/pi/rpi_python/hello_arg2.py")
Hello to you!
>>> sys.argv = ["hello_arg2.py", "saybye"]
>>> execfile("/home/pi/rpi_python/hello_arg2.py")
Hasta la vista!

note Python3 has removed execfile(), now use
>>> exec(open("/home/pi/rpi_python/hello_arg2.py").read())

"""

def sayhi():
    print("Hello to you!")

def saybye():
    print("Hasta la vista!")


if __name__ == '__main__':
    import sys
    # there is a commandline
    if len(sys.argv) > 1:
        # sys.argv[0] is the program filename
        if sys.argv[1] == "sayhi":
            sayhi()
        elif sys.argv[1] == "saybye":
            saybye()
    else:
        print("usage hello_arg2 sayhi  or  hello_arg2 saybye")
sneekula 969 Nearly a Posting Maven

I thought you want to do it from the Python shell?

sneekula 969 Nearly a Posting Maven

Or simpler:
>>> execfile("hello.py")

You might have to give it the full file path.

sneekula 969 Nearly a Posting Maven

Or simpler:
>>> execfile("hello.py")

sneekula 969 Nearly a Posting Maven

If you saved your file as hello.py somewhere Python looks for, do this from the shell:

>>> import hello
>>> hello.thefunc()
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

According to Einstein the Sun uses up more and more matter, its gravitational pull should lessen and the Earth should move further away.

sneekula 969 Nearly a Posting Maven

Looking at main.py this program is a nightmare of imports.

https://github.com/PicciMario/iPhone-Backup-Analyzer-2/blob/master/main.py

sneekula 969 Nearly a Posting Maven

Also take a look at the turtle demo files in
C:\Python34\Lib\turtledemo
for instance

sneekula 969 Nearly a Posting Maven

To keep the image from being garbage-collected within the function scope, put this line canv2.image = bg_fon2 right after line 22

sneekula 969 Nearly a Posting Maven

For example:

import itertools

s = "a1 a2 a3 a4 a5 a6"
seq = s.split()
print(seq)  # test

for e in itertools.permutations(seq):
    print(" ".join(e))
sneekula 969 Nearly a Posting Maven

The shebang line is of course very useful when you write cross-platform code or in case of
if __name__ == "__main__":
when you write a module and a test for it.

To throw in function main() is a leftover from the C days. C is looking for it to start, Python could care less.

sneekula 969 Nearly a Posting Maven

Generally:

# show prime numbers
# prime numbers are only divisible by unity and themselves
# (1 is not considered a prime number)

for n in range(2, 100):
    for x in range(2, n):
        if n % x == 0:
            # found a factor
            #print(n, 'equals', x, '*', n/x)  # optional
            break
    else:
        # note this else has to line up with second for, not the if
        # means loop fell through without finding a factor
        print(n, 'is a prime number')
sneekula 969 Nearly a Posting Maven

One possibility:

def translate(text, e_s_dict):
    swed = ""
    space = " "
    for word in text.split():
        swed += e_s_dict[word] + space
    return swed


# english:swedish dictionary
e_s_dict = {"merry":"god",
"christmas":"jul",
"and":"och",
"happy":"gott",
"new":"nytt",
"year":"ĂĄr"}

# english text
eng_text = "merry christmas"

# translate to swedish text
swed_text = translate(eng_text, e_s_dict)
print(swed_text)  # result --> god jul

Use meaningful variable names. It will help you understand what is going on.

sneekula 969 Nearly a Posting Maven

You can use a while loop (stops/breaks when n is zero):

def generate_n_chars(n, ch):
    s = ""  # start with an empty string
    while n:
        s += ch  # build up the string s
        n -= 1   # decrement n by 1
    return s

# test
ch = 'z'
n = 7
print(generate_n_chars(n, ch))  # result --> zzzzzzz

To see what's going on use a temporary test print():

def generate_n_chars(n, ch):
    s = ""  # start with an empty string
    while n:
        s += ch  # build up the string s
        n -= 1   # decrement n by 1
        print(n, s)  # temporary test print
    return s

# test
ch = 'z'
n = 7
print(generate_n_chars(n, ch))  # result --> zzzzzzz
sneekula 969 Nearly a Posting Maven

Hint:

mystring = "briyani"
for c in mystring:
    print(c)

# then this should give you the length
length = sum(1 for c in mystring)
print(length)
sneekula 969 Nearly a Posting Maven

If you use an IDE like Ninja, then you can switch beteeen different versions of Python by following the tabs:
Edit
Preferences
Execution
then simply edit the Python Path field.
If it shows
C:/Python32/python.exe
replace the 32 with 27

The Ninja IDE is free from:
http://www.ninja-ide.org/

sneekula 969 Nearly a Posting Maven

Write these two batch files and put a shortcut of each on your desk top:

rem save as idle27.bat
rem run the IDLE IDE with Python27
C:\Python27\pythonw.exe -u  C:\Python27\Lib\idlelib\idle.pyw

and

rem save as idle32.bat
rem run the IDLE IDE with Python32
C:\Python32\pythonw.exe -u  C:\Python32\Lib\idlelib\idle.pyw
sneekula 969 Nearly a Posting Maven

Looks like you use the Gregory–Leibniz series which converges rather slowly.
A much faster series is given in the Python manual under the decimal module recipes:

import decimal

def pi_decimal(prec):
    """
    compute Pi to the current precision
    """
    # increase precision for intermediate steps
    decimal.getcontext().prec = prec + 2
    D = decimal.Decimal
    # make starting assignments
    lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    # reset to original precision
    decimal.getcontext().prec -= 2
    # unary plus applies the reset precision
    return +s


precision = 60
print("pi calculated to a precision of {}".format(precision))
print(pi_decimal(precision))
print("compare with published pi")
print("3.14159265358979323846264338327950288419716939937510582097494")

'''result ...
pi calculated to a precision of 60
3.14159265358979323846264338327950288419716939937510582097494
compare with published pi
3.14159265358979323846264338327950288419716939937510582097494
'''
sneekula 969 Nearly a Posting Maven

Here is a nice C# tutorial:
http://zetcode.com/lang/csharp/

The Python tutorial:
http://zetcode.com/lang/python/

Might as well look at the Java tutorial too:
http://zetcode.com/lang/java/

ddanbe commented: Nice links! +15
sneekula 969 Nearly a Posting Maven

There is also IronPython that has the look of C# but the easier syntax of Python.
http://www.zetcode.com/tutorials/ironpythontutorial/

Free IronPython download from:
http://ironpython.codeplex.com/
There is a free studio like IDE at:
http://sharpdevelop.codeplex.com/
that can be used for C# and IronPython.

sneekula 969 Nearly a Posting Maven

C# has the best integrated/unified system. However, you will be married to Windows and the NET. Let's not forget that 90% of PCs and laptops in the world are Windows based. The best part is that it produces executable files (.exe).

Python has a hotch potch of IDE's, GUI toolkits, form builders and on top that two often conflicting versions. This can be very confusing to the beginner. Python should be easier to learn since it allows several programming styles and does not force you into OOP from day one, like C# and Java do.

sneekula 969 Nearly a Posting Maven

Here is an example to get you started:

''' random_sentences101.py

# use this template to add more data
adjectives.append('')
subjects.append('')
verbs.append('')
objects.append('')

'''

import random

# create lists
adjectives = []
subjects = []
verbs = []
objects = []

# add data to the lists
adjectives.append('A small')
subjects.append(' boy')
verbs.append(' walked')
objects.append(' the fence')

adjectives.append('The big')
subjects.append(' trucker')
verbs.append(' climbed')
objects.append(' a tree')

adjectives.append('A tiny')
subjects.append(' frog')
verbs.append(' jumped over')
objects.append(' a log')

adjectives.append('The tardy')
subjects.append(' teacher')
verbs.append(' fell under')
objects.append(' two tables')


# construct n random sentences
n = 5
for k in range(n):
    sentence = random.choice(adjectives)
    sentence += random.choice(subjects)
    sentence += random.choice(verbs)
    sentence += random.choice(objects)

    print(sentence)
sneekula 969 Nearly a Posting Maven

You can try:

pre = "21:20:01 T:5796  NOTICE:"
for item in programList:
    print("{} {}".format(pre, item))
sneekula 969 Nearly a Posting Maven

You can use input() for both versions of Python:

# Python2 uses raw_input() for strings
# Python3 uses input() for strings

# ----------------------------------------------
# add these few lines near the start of you code
import sys
# make string input work with Python2 or Python3
if sys.version_info[0] < 3:
    input = raw_input
# ----------------------------------------------

# test ...
# now you can avoid using raw_input()
name = input("Enter your name: ")
# if you expect float input, use float() instead of int()
age = int(input("Enter your age: "))
print("%s you are %d old" % (name, age))
sneekula 969 Nearly a Posting Maven

I like those small cubicles, you can decorate them to your likes.

sneekula 969 Nearly a Posting Maven

I could go for Rheinmetall Boxer.
Just waiting until the hybrid comes out.

sneekula 969 Nearly a Posting Maven

Try this:

''' wxBoxSizer101.py
button1 at upper right corner
button2 at lower right corner
'''

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.create_widgets()

    def create_widgets(self):
        self.button1 = wx.Button(self, wx.ID_ANY, label='Button1')
        self.button2 = wx.Button(self, wx.ID_ANY, label='Button2')
        # use a box sizer to lay out widgets
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        # Add(widget, proportion, flag, border)
        # border is to the left side
        sizer_v.Add(self.button1, 0, flag=wx.LEFT, border=200)
        # this adds a spacer (w, h)
        # here only the height is important
        sizer_v.Add((0, 200), proportion=0, flag=wx.EXPAND)
        sizer_v.Add(self.button2, 0, flag=wx.LEFT, border=200)

        self.SetSizer(sizer_v)


app = wx.App(0)
mytitle = "wx.BoxSizer Test101"
width = 300
height = 290
# create a MyFrame instance and show the frame
MyFrame(None, mytitle, (width, height)).Show()
app.MainLoop()
sneekula 969 Nearly a Posting Maven

Toyota gives a factory warranty of 8 years for the Prius nickel hydride battery pack. The replacement past this period will cost you about $3,000. So, watch out when you buy an old used Prius.

sneekula 969 Nearly a Posting Maven

Toyota had an awful lot of recalls lately. I almost got a used Prius until I read what a battery replacement would cost.