Encyclopedia > Python vs C Plus Plus example

  Article Content

Python vs C Plus Plus example

Here's a sample of how a C++ program would look when converted to Python. It's an implementation of a weird program described in this article (http://wwwipd.ira.uka.de/~prechelt/Biblio/jccpprtTR.pdf) (link to external pdf). Worth noting is that the C++ implementation presented here is over 50% smaller than the smallest program entered in the original "contest", so this comparison between C++ and Python is more than fair towards C++.

The main point here is to show how some of the more advanced C++ features map to Python code. The point is not what the code does (thus no comments), but how it does it. The example codes should be easily comparable, due to same variable and function names.

C++ code

#include <string>
#include <algorithm>
#include <iostream>
#include <functional>
#include <fstream>
#include <map>
#include <vector>
#include <cctype>

using namespace std;

typedef multimap<string, string> DicMap;
typedef vector<string> Answers;

char toNumber(char letter) {
  static string letter2digit[] = { "E", "JNQ", "RWX", "DSY", "FT", "AM", "CIV", "BKU", "LOP", "GHZ" };
  for (int i=0; i<10; ++i)
    if (letter2digit[i].find(letter) != string::npos)
      return '0' + i;
  return '0';

void findMatch(const string& answer, const string& line, const DicMap& dic,
               bool allowNumber, Answers& answers) {
  if (line.empty()) {

  for (size_t i = 1; i <= line.length(); ++i) {
    pair<DicMap::const_iterator, DicMap::const_iterator> range = dic.equal_range(line.substr(0, i));
    for (DicMap::const_iterator e = range.first; e != range.second; ++e) {
      allowNumber = false;
      findMatch(answer + " " + e->second, line.substr(e->first.length(), line.length()), dic, true, answers);

  if (allowNumber)
    findMatch(answer + " " + line[0], line.substr(1, line.length()), dic, false, answers);

bool readDic(DicMap& dic) {
  ifstream in("dic.txt");
  if (!in) return false;
  string line;
  while (!in.eof()) {
    getline(in, line);

    string number = line;
    number.erase( remove_if(number.begin(), number.end(), not1(ptr_fun(isalpha))), number.end());
    transform(number.begin(), number.end(), number.begin(), toupper);
    transform(number.begin(), number.end(), number.begin(), toNumber);
    dic.insert(make_pair(number, line));
  return true;

int main() {
  DicMap dic;
  if (!readDic(dic)) return 1;

  ifstream in("ph.txt");
  if (!in) return 1;
  string line;
  while (!in.eof()) {
    getline(in, line);
    string line_real = line;
    line_real.erase( remove_if(line_real.begin(), line_real.end(), not1(ptr_fun(isdigit))), line_real.end());
    Answers answers;
    findMatch("", line_real, dic, true, answers);
    for (Answers::iterator i = answers.begin(); i != answers.end(); ++i)
      cout << line << ":" << *i << endl;

Python code

import string

letter2digit = "E", "JNQ", "RWX", "DSY", "FT", "AM", "CIV", "BKU", "LOP", "GHZ"

def toNumber(letter):
    for i in range(len(letter2digit)):
        if letter in letter2digit[i]:
            return chr(ord('0') + i)

def findMatch(answer, line, dic, allowNumber, answers):
    if line:

    for i in range(1, len(line) + 1):
        if dic.has_key(line[:i]):
            allowNumber = False
            for e in dic[line[:i]]:
                findMatch(answer + ' ' + e, line[i:], dic, True, answers)
    if allowNumber:
        findMatch(answer + ' ' + line[0], line[1:], dic, False, answers)

def readDic():
    dic = {}
    for line in file('dic.txt'):
        line = line.strip()
        number = filter(lambda x: x in string.ascii_letters, line).upper()
        number = "".join(map(toNumber, number))
        dict[number] = dic.get(number, []) + [line]

def main():
    dic = readDic()
    for line in file('ph.txt'):
        line = line.strip()
        line_real = filter(lambda x: x in string.digits, line)
        answers = []
        findMatch("", line_real, dic, True, answers)
        for answer in answers:
            print line, ':', answer
In Python sample, the "main"-block was moved into a function for convenience; It need not be there.

All Wikipedia text is available under the terms of the GNU Free Documentation License

  Search Encyclopedia

Search over one million articles, find something about almost anything!
  Featured Article

... 22,150 were convicts) at the beginning of 20th century, the population grew to 673,100 today, 83% from whom are Russians. The largest settlement on the island is ...

This page was created in 85.2 ms