sneekula 969 Nearly a Posting Maven

There might be a Persian version of Python.

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
Computer languages Worldwide, Jan 2015
Meassured by the number of inquiries on Google
(a mixture of "I am interested" and "I am lost")
----------------------------------------------------
Rank   Language     Share(%)  Trend(% vs a year ago)
----------------------------------------------------
1      Java            24.7      -0.4
2      PHP             11.7      -1.2
3      Python          10.6      +0.9
4      C#               8.9      -0.3
5      C++              8.2      -0.5
6      C                7.8      +0.1
7      Javascript       7.2      -0.3
8      Objective-C      6.1      -0.2
9      Matlab           3.0      -0.2
10     R                2.7      +0.6
11     Ruby             2.5      +0.0
12     Swift            2.5      +2.9
13     Visual Basic     2.3      -0.7
14     Perl             1.3      -0.3
15     lua              0.5      -0.1
----------------------------------------------------
source = http://pypl.github.io/PYPL.html
sneekula 969 Nearly a Posting Maven

Update:
PriceLess has so far stayed away from my Chrome Web Browser extensions. However I can still find references to it, for instance if I save a file without extension then the file manager lists "PriceLess" as the file type. Like I claimed before frigging Windows7 is like Swiss cheese, and has too many places to infect!

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

After the Swiss Federal Bank floated the Swiss Franc against the Euro, the Franc shot up so much that many Swiss take the short trip to Germany to literally buy things at half price.

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

A simple timing example:

import time

def print_timing(func):
    """
    a decorator function to time another function
    time.clock() works on Windows systems only
    you can use time.time() instead, but it gets updated less
    frequently and can give 0.0 results on faster functions
    """
    def inner(*arg):
        """*arg are the arguments of function func"""
        t1 = time.clock()
        res = func(*arg)
        t2 = time.clock()
        # time is in milliseconds
        print('%s took %0.3f ms' % (func.__name__, (t2-t1)*1000.0))
        return res
    return inner

@print_timing
def isprime(x):
     for i in range(2, x):
        if x%i == 0:
           return False
        elif x%i != 0 and i == x-1:
           return True

@print_timing
def isprime5(n):
    if n == 2 or n == 3: return True
    if n < 2 or n%2 == 0: return False
    if n < 9: return True
    if n%3 == 0: return False
    sqr = int(n**0.5)
    f = 5
    while f <= sqr:
        if n%f == 0: return False
        if n%(f+2) == 0: return False
        # loop every 6th integer
        f += 6
    return True


isprime(13999979)  # isprime took 404.684 ms

isprime5(13999979) # isprime5 took 0.022 ms

isprime5(135999979) # isprime5 took 0.610 ms

isprime(135999979)  # MemoryError
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

The elegant thing about the while True loop is that you can break at a given point between statements.

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

You can modernize this a little:

// str_toupper.cpp
// convert a string to all upper case
// compiled with mingw32-g++.exe

#include <algorithm>  // transform()
#include <cctype>     // toupper()
#include <iostream>
#include <string>

using namespace std;

char upper_case(char ch)
{
  return toupper(ch);
}

int main()
{
  string s = "this is a Test 123";

  transform( s.begin(), s.end(), s.begin(), upper_case );
  cout << s << endl;

  return 0;
}

/* result:
THIS IS A TEST 123
*/
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

If you go to:
http://en.wikipedia.org/wiki/List_of_countries_by_inflation_rate
you can extract the 10 countries with the highest inflatuion rate.

You end up with this tab delimited data string:

data = '''\
Uruguay 8.11    2014 November
Turkey  8.9 2014 November
Egypt   10.61   2014 June
Argentina   24.2    2014 November
Ukraine 13  2014 December
Syria   13.6    2014 February
Iran    14.6    2014 June
Belarus 32.8    2014 December
Sudan   46.8    2014 July
Venezuela   60.9    2014 May'''

Now write a Python program to produce this string/text:

Country          Inflation (%)
Venezuela        60.9
Sudan            46.8
Belarus          32.8
Argentina        24.2
Iran             14.6
Syria            13.6
Ukraine          13.0
Egypt            10.61
Turkey           8.9
Uruguay          8.11
sneekula 969 Nearly a Posting Maven

10 countries with with the highest mid 2014 inflation rate:

Country Inflation (%)
Venezuela 60.9
Sudan 46.8
Belarus 32.8
Argentina 24.2
Iran 14.6
Syria 13.6
Ukraine 13.0
Egypt 10.61
Turkey 8.9
Uruguay 8.11

Source:
http://en.wikipedia.org/wiki/List_of_countries_by_inflation_rate

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

Write a Python program that checks a given directory for any file changes over a given period.

sneekula 969 Nearly a Posting Maven

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

sneekula 969 Nearly a Posting Maven

I have a Toshiba Satellite notebook with Windows7 OS.
How would I go about it to replace Windows7 with Kubuntu?

sneekula 969 Nearly a Posting Maven

Actually, after removing the contaminated MS installed Wildtangent games, the MS "application virtualization client" complains about not being able to reload a program. It doesn't tell which program it is, but my bet is that it is "PriceLess". So far it has stayed away!

Folks tell me that Linux is not bothered by hackers as much, since it has only a very small user number. I do enjoy Linux on my tiny Raspberry Pi computer.

sneekula 969 Nearly a Posting Maven

Thank you! Just a little MS game of hide and seek?

sneekula 969 Nearly a Posting Maven

I wish Hollywood could come up something better than endless sequels.

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

I average about 2 hours a day.

sneekula 969 Nearly a Posting Maven

Here you go:

s = "happy Hello World!"

print(s)
print(s.capitalize())
print(" ".join(w.capitalize() for w in s.split()))
print(s.lower())
print(s.upper())
print(s.swapcase())

''' my result -->
happy Hello World!
Happy hello world!
Happy Hello World!
happy hello world!
HAPPY HELLO WORLD!
HAPPY hELLO wORLD!
'''
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Assume the individual data has to come from the user via cin.

sneekula 969 Nearly a Posting Maven

Do you want to sort or random shuffle your array?

sneekula 969 Nearly a Posting Maven

If you wait till April, they will most likely print a 100 quatrillion Dollar bill. That's the way hyperinflation goes.

sneekula 969 Nearly a Posting Maven

What is folder view?

Got into it using help.

sneekula 969 Nearly a Posting Maven

Tough to do if the folder does not even show up.

sneekula 969 Nearly a Posting Maven

On Windows7 I am trying to read file
C:\programdata\microsoft\application virtualization client\SoftGrid Client\sftfs.fsd
using a Python program, but I get a PermissionError.

How do I get permission?

Why does folder programdata not show in the Microsoft file manager/explorer?

sneekula 969 Nearly a Posting Maven

Can you run Linux on a Windows machine? Would that solve the problem?

sneekula 969 Nearly a Posting Maven

Since the file manager that comes with Windows7 does not even show folder ProgramData, I used used this little Python program to poke around:

''' file_get_full_path2.py
list file names with full path in a given folder and its subfolders
the Windows Explorer file manager does not bring up folder ProgramData
'''

import glob

folder = "C:/programdata/microsoft/application virtualization client"

for full_name2 in glob.glob(folder+"/*/*.*"):
    print(full_name2)

'''
C:/programdata/microsoft/application virtualization client\SoftGrid Client\sftfs.etl
C:/programdata/microsoft/application virtualization client\SoftGrid Client\sftfs.etl.old
C:/programdata/microsoft/application virtualization client\SoftGrid Client\sftfs.fsd
C:/programdata/microsoft/application virtualization client\SoftGrid Client\sftfs.fsG
C:/programdata/microsoft/application virtualization client\SoftGrid Client\shortcut_ex.dat

note:
on my Windows7 computer file sftfs.fsd contains string "PriceLess" (a nasty adware)
'''

print('-'*50)

# more info ...

import os
import stat
import time

# pick a file you have ...
file_name = r"C:/programdata/microsoft/application virtualization client\SoftGrid Client\sftfs.fsd"

file_stats = os.stat(file_name)
file_size_bytes = file_stats[stat.ST_SIZE]
last_modified = time.ctime(file_stats[stat.ST_MTIME])
mode = file_stats[stat.ST_MODE]

print(file_size_bytes)  # 801424592 --> 801,424,592 bytes --> 801 mb
print(last_modified)    # Wed Jan  7 09:36:27 2015
print(mode)  # 33206