0

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()
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
0

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
*/
0

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.

0

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

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