1

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)
2

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
'''
Votes + Comments
time well spent! :D
1

@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 to use **else ...

Votes + Comments
Nice
2

@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
*/
Votes + Comments
thanks
2

Why Did the Chicken Cross the Road?

KINDERGARTEN TEACHER: To get to the other side

PLATO: For the greater good.

ARISTOTLE: It is the nature of chickens to cross roads.

KARL MARX: It was a historical inevitability.

GEORGE W. BUSH: We don't really care why the chicken crossed the road.
We just want to know if the chicken is on our side of the road or not.

PROGRAMMER: It heard that they paid better on the other side.

1

@RobertHDD
I tried all your suggestions, but to no avail. PriceLess keeps popping up in the Chrome browser extensions.

I took XFind.exe and searched for the string PriceLess and found it in folder ProgramData, hidden in the Wildtangent games that MS shipped with Windows7. I deleted those silly games.

Then I disabled it in the Chrome extension and so far it stays disabled. When I removed it in the past, it simply came back after a few boots.

It is also found in folder:
ProgramData/Microsoft/Application Virtualization Client/Softgrid Client/sftfs.fsd

That is a huge file and I don't want to mess with it. Let's hope it stays disabled in the Chrome extensions.

1

I got infected right after a Java and Adobe update on my Windows7 machine.
folder \jnihmpibahpjjmcodbopcpdaelkbpjnc is most likely a random generated folder.

Note on malware PriceLess (pops up as Chrome extension, highlights strings for ads):
PriceLess is in folders:
C:\Users\HomeGroupUser$\AppData\Local\Chromatic Browser\User Data\Default\Extensions\jnihmpibahpjjmcodbopcpdaelkbpjnc\5.2
C:\Users\HomeGroupUser$\AppData\Local\Comodo\Dragon\User Data\Default\Extensions\jnihmpibahpjjmcodbopcpdaelkbpjnc\5.2
C:\Users\HomeGroupUser$\AppData\Local\Google\Chrome\User Data\Default\Extensions\jnihmpibahpjjmcodbopcpdaelkbpjnc\5.2
C:\Users\HomeGroupUser$\AppData\Local\Google\Chrome SxS\User Data\Default\Extensions\jnihmpibahpjjmcodbopcpdaelkbpjnc\5.2
C:\Users\HomeGroupUser$\AppData\Local\Torch\User Data\Default\Extensions\jnihmpibahpjjmcodbopcpdaelkbpjnc\5.2
go down to /Extensions each and delete folder \jnihmpibahpjjmcodbopcpdaelkbpjnc

do the same for folders:
C:\Users\Guest\AppData\Local\Chromatic Browser\User Data\Default\Extensions
C:\Users\Guest\AppData\Local\Comodo\Dragon\User Data\Default\Extensions
C:\Guest\AppData\Local\Google\Chrome\User Data\Default\Extensions
C:\Users\Guest\AppData\Local\Google\Chrome SxS\User Data\Default\Extensions
C:\Users\Guest\AppData\Local\Torch\User Data\Default\Extensions

also do the same for folders:
C:\Users\Administrator\AppData\Local\Chromatic Browser\User Data\Default\Extensions
C:\Users\Administrator\AppData\Local\Comodo\Dragon\User Data\Default\Extensions
C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Extensions
C:\Users\Administrator\AppData\Local\Google\Chrome SxS\User Data\Default\Extensions
C:\Users\Administrator\AppData\Local\Torch\User Data\Default\Extensions

in each case remove folder /jnihmpibahpjjmcodbopcpdaelkbpjnc
contains subfolder /5.2
with files -->
background.html
content.js
lsdb.js
manifest.json --> contains ref to "PriceLess"
r1Iz.js

Do a FindFile search for
*/5.2/r1Iz.js
to make sure you deleted them all

Clear your Recycle Bin

1

Just a little faster than isprime2():

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
1

Okay, I got my Raspberry Pi B+ and have the Linux installed and running. Even wrote a few Python programs on the included Idle IDE.

I tried to write a Python program to turn on some of the io pins, but can't find good examples. Most of the web site references are pretty bad or nonexistent.

1

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.

2

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
'''
1

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)
2

The British spy agency the Government Communications Headquarters (GCHQ) has used a sophistcated version of the Regin virus to infect the Belgian telecommunications company Belgacom.

By targeting engineers through a faked LinkedIn page, GCHQ was able to get deep inside the Internet provider to steal data. One of Belgacom's main clients was the European Commission, the European Parliament, and the European Council of member state leaders.

Source:
http://news.yahoo.com/now-know-developed-state-sponsored-180205552.html