I need to implement the C++ equivalent of the expandtabs() function. Can someone help me with converting this code to C++?
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# instead of the tab character, append the
# number of spaces to the next tab stop
char = " " * (n - pos % n)
pos = 0
elif char == "\n":
pos = 0
else:
pos += 1
result += char
return result
This is what I have:
std::string ExpandTabs(const std::string &str, int tabsize =4){
std::string ReturnString = str;
std::string result = " ";
int pos = 0;
for(std::string::size_type i = 0; i < ReturnString.size(); ++i) {
if (ReturnString[i] == '\t'){
int spaces = tabsize - pos % tabsize ;
ReturnString.append(" ", spaces);
pos = 0;
}
else{
pos+=1;
}
}
return ReturnString;
You need to build up the string character by character. Currently you assign str to ReturnString at the start of the function and then append whatever spaces you decide are necessary to the end of the string, instead of in place of the tabs.
There are no doubt more idiomatic ways to achieve the same result, but a like for like conversion of the python might look like.
#include <iostream>
#include <string>
std::string expand_tabs(const std::string &str, int tabsize=4)
{
std::string result = "";
int pos = 0;
for(char c: str)
{
if(c == '\t')
{
// append the spaces here.
result.append(tabsize - pos % tabsize, ' ');
pos = 0;
} else
{
result += c;
pos = (c == '\n') ? 0: pos + 1;
}
}
return result;
}
int main()
{
std::cout << expand_tabs("i\tam\ta\tstring\twith\ttabs") << '\n';
std::cout << expand_tabs("1\t2\t3\t4", 2) << '\n';
}
It basically steps through the input forwarding on any non tab characters to the result string, otherwise it adds the correct number of spaces to the result.
Output:
i am a string with tabs
1 2 3 4
A straight translation of the python code is problematic, since char cannot be both a string and a single character, but apart from that it's straightforward:
std::string expandtabs(std::string const&str, std::string::size_type tabsize=8)
{
std::string result;
std::string::size_type pos = 0
result.reserve(str.size()); // avoid re-allocations in case there are no tabs
for(c : str)
switch(c) {
default:
result += c;
++pos;
break;
case '\n':
result += c;
pos = 0;
break;
case '\t':
result.append(tabsize - pos % tabsize,' ');
pos = 0;
}
return result
}
Related
I would like to know how can I read the charaters into a buffer in Python?
In C code, I can easy decralare the buffer character like char buffer[256];:
void read_char(int x, char buffer[], int *flag_stop) {
int i, length;
char character;
i = 0;
bzero(buffer, 256);
do {
if ((length = read(x, &character, 1)) <= 0)
{
*flag_stop = 1;
break;
}
buffer[i] = character;
i++;
}
while(c != 0x0A);
}
But I don't know how to do in Python so the code is something like this:
def read_char(x,buffer,**flag_stop):
i = 0
buffer = np.array([], dtype='S64')
while True:
if os.read(x, character, 1) <= 0:
**flag_stop == 1
break
buffer[i] = str(character)
i=i+1
if(character != 0x0A):
break
I have tried with numpy.chararray but I did not work. Any idea for this problem? thank you very much!
Your main problem is that you want in Python write code exactly like in C.
Python would need something like this
def read_char(x):
flag_stop = False # or 0
i = 0
buffer = np.array([], dtype='S64')
while True:
character = os.read(x, 1)
if not character: # if len(character) < 0
flag_stop = True # or 1
break
buffer[i] = character
i += 1
if character != 0x0A:
break
return buffer, flag_stop
# ---
buffer, flag_stop = read_char(file_handler)
I don't like str() in your code - you may get single byte which is part of mulit-bytes code (like utf-8) and converting to str() can only mess it.
I have a string with characters and a number for the rows and columns that will be in the pattern:
char_str1 = 'abc'
char_str1 = '31452'
num = 5
I would like the output to be:
abcab 31452
bcabc 14523
cabca 45231
abcab 52314
bcabc 23145
I have tried doing:
for i in range(num):
for j in range(num):
print(char_str1, end='')
print()
output:
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
abcabcabcabcabc
If you replicate the strings at least num times, simple slicing works. The original strings need to be at least length 1 of course:
char_str1 = 'abc'
char_str2 = '31452' # You had a typo here st1 instead of str2
num = 5
a = char_str1 * num
b = char_str2 * num
for i in range(num):
print(a[i:i+num], b[i:i+num])
Output:
abcab 31452
bcabc 14523
cabca 45231
abcab 52314
bcabc 23145
Please use the below code in java for your pattern!!
JAVA
public class Main {
public static void printPattern(String s, int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n + i; j++) {
System.out.print(s.charAt(j % s.length()));
}
System.out.println();
}
}
public static void main(String[] args) {
printPattern("abc", 5);
printPattern("31452", 5);
}
}
EDIT:
Python
def printPattern(s, n):
for i in range(n):
for j in range(i, n + i):
print(s[j % len(s)], end='')
print()
printPattern("abc", 5);
printPattern("31452", 5);
Problem Statement
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form "name=phoneNumber"; if an entry for name is not found, print "Not found" instead.
Input Format: ...
After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and
You must continue reading lines until there is no more input.
How should I loop it until there is no more input?
Also can someone tell me how this is possible in C++?
Here's my code in Python 3:
n = int(input())
names = {}
for foo in range(n):
entry = input().split(' ')
names[entry[0]] = entry[1]
while (1==1):
check = input()
if(names.get(check)!=None):
print(check + '=' + names.get(check))
else:
print('Not Found')
It just loops infinitely and therefore triggers the error.
Here's the C++ code:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(void)
{
map<string, string> phonebook;
int n;
cin >> n;
string key, num;
for(int i = 0; i < n; i++)
{
cin >> key >> num;
phonebook.insert(pair<string, string>(key, num));
}
while (1 == 1)
{
cin >> key;
if(phonebook.count(key) > 0)
cout << key << "=" << phonebook[key] << endl;
else
cout << "Not found" << endl;
}
}
How should I loop it until there is no more input?
Your use of the while loop is appropriate. To catch and silence the error, you can use a try-except block:
n = int(input())
names = {}
for foo in range(n):
entry = input().split(' ')
names[entry[0]] = entry[1]
while True: # (1 == 1) == True
try:
check = input()
except EOFError: # catch the error
break # exit the loop
if(names.get(check)!=None):
print(check + '=' + names.get(check))
else:
print('Not Found')
Also can someone tell me how this is possible in C++?
Hmm... weird request. I'll point you to std::getline and std::map and let them do the talking. :-)
Here's the correct C++ code:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(void)
{
map<string, string> phonebook;
int n;
cin >> n;
string key, num;
for(int i = 0; i < n; i++)
{
cin >> key >> num;
phonebook.insert(pair<string, string>(key, num));
}
getline(cin, key);
while(getline(cin, key)) //Loop runs while we are getting input.
{
if(phonebook.count(key) > 0)
cout << key << "=" << phonebook[key] << endl;
else
cout << "Not found" << endl;
}
}
This game uses this encryption to stop people from being able to connect bots easily the function used by the game is:
function djinndecrypt(string, key) {
var crypt = "";
var part = "";
var parts = 0;
var keyGen = key.length;
for(var i = 0; i < string.length; i++) {
var char = string.charAt(i);
var chrNum = string.charCodeAt(i);
var keyChr = key.charAt(parts % key.length);
var keyNum = key.charCodeAt(parts % key.length);
part += char;
if((i+1) % 3 == 0 && i > 0) {
crypt += String.fromCharCode((coreHash.indexOf(part)+2) - keyNum - keyGen);
part = "";
parts++;
}
}
return crypt;
I have attempted to port this to python my code is:
coreHash = "4Qiqc3mpjw2jFLJBaV9ANsWoYDR8ktvZIMeJTfOd1lyH5P7XKxhU6rCbzuE10nS5Ks7rPj1YvnDlbX4m2jI0NkyOL3hHU6FRVduJJoCwfWiABzqSaETMet1pZ89xQc81ieHA0F5EuNnWCwJvMJLQhV3UxPYRB76pbfIy2dcoaT14XkqlZsSzj9KDtrmjO9fjdMPERB12TYzDJrNxc3QajKU0kbvu4F56yHAXWO7tlwni8mZqCSosLVIehJ1pzT1kEsSXAl1O45CdLnRwQeM06ZqxJfJayBN8FWj2prYjuKIhiHU7VbomDPvct935yULcOHNJZsa31DeSlmnPBxJkYbTdAFRotIizv2VpXuf9w0KqQ8Ehjr4MW7Cj164Y1ukWxp9EjOwDPF8rsX5vlZN7QJqfteCATKncUoLVaM16Shy";
def djinndecrypt(string, key):
crypt = ""
part = ""
parts = 0;
keyGen = len(key)
for i in xrange(len(string)):
char = string[i]
chrNum = ord(char)
keyChr = key[parts % len(key)]
keyNum = ord(keyChr)
part += char
if((i + 1) % 3 == 0 and i > 0):
crypt += chr((coreHash.find(part) + 2) - keyNum - keyGen)
part = ""
parts += 1
print crypt
djinndecrypt("zQDHzljoHM6RhuhuhWzQDA5dgOAzQDlbAqkgOA57mM", "69338277581336797325449966279465")
The code ends up raising an exception:
ValueError: chr() arg not in range(256)
chr() only accepts up to 255 as described by the error. You can get more distance using unichr() but that returns Unicode characters instead of ACSII like chr().
However, given that this is supposed to result in an English string, the problem appears to be in the coreHash, as results above 122 [ chr(122) is 'z' ] will be out of alphabetical range.
I'm using the fractions module in Python v3.1 to compute the greatest common divisor. I would like to know what algorithm is used. I'm guessing the Euclidean method, but would like to be sure. The docs (http://docs.python.org/py3k/library/fractions.html?highlight=fractions.gcd#fractions.gcd) don't help. Can anybody clue me in?
According to the 3.1.2 source code online, here's gcd as defined in Python-3.1.2/Lib/fractions.py:
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
So yes, it's the Euclidean algorithm, written in pure Python.
From fractions python
"Deprecated since version 3.5: Use math.gcd() instead."
I was looking for the algorithm as well. I hope it helped.
Since Python 3.5, the GCD code has been moved to math.gcd. Since Python 3.9, math.gcd takes an arbitrary number of arguments.
The actual GCD code is now implemented in C (for CPython), making it significantly faster than the original pure Python implementation.
Boilerplate:
static PyObject *
math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
{
PyObject *res, *x;
Py_ssize_t i;
if (nargs == 0) {
return PyLong_FromLong(0);
}
res = PyNumber_Index(args[0]);
if (res == NULL) {
return NULL;
}
if (nargs == 1) {
Py_SETREF(res, PyNumber_Absolute(res));
return res;
}
PyObject *one = _PyLong_GetOne(); // borrowed ref
for (i = 1; i < nargs; i++) {
x = _PyNumber_Index(args[i]);
if (x == NULL) {
Py_DECREF(res);
return NULL;
}
if (res == one) {
/* Fast path: just check arguments.
It is okay to use identity comparison here. */
Py_DECREF(x);
continue;
}
Py_SETREF(res, _PyLong_GCD(res, x));
Py_DECREF(x);
if (res == NULL) {
return NULL;
}
}
return res;
}
The actual computation uses Lehmer's GCD algorithm:
PyObject *
_PyLong_GCD(PyObject *aarg, PyObject *barg)
{
PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
stwodigits x, y, q, s, t, c_carry, d_carry;
stwodigits A, B, C, D, T;
int nbits, k;
Py_ssize_t size_a, size_b, alloc_a, alloc_b;
digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
a = (PyLongObject *)aarg;
b = (PyLongObject *)barg;
size_a = Py_SIZE(a);
size_b = Py_SIZE(b);
if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
Py_INCREF(a);
Py_INCREF(b);
goto simple;
}
/* Initial reduction: make sure that 0 <= b <= a. */
a = (PyLongObject *)long_abs(a);
if (a == NULL)
return NULL;
b = (PyLongObject *)long_abs(b);
if (b == NULL) {
Py_DECREF(a);
return NULL;
}
if (long_compare(a, b) < 0) {
r = a;
a = b;
b = r;
}
/* We now own references to a and b */
alloc_a = Py_SIZE(a);
alloc_b = Py_SIZE(b);
/* reduce until a fits into 2 digits */
while ((size_a = Py_SIZE(a)) > 2) {
nbits = bit_length_digit(a->ob_digit[size_a-1]);
/* extract top 2*PyLong_SHIFT bits of a into x, along with
corresponding bits of b into y */
size_b = Py_SIZE(b);
assert(size_b <= size_a);
if (size_b == 0) {
if (size_a < alloc_a) {
r = (PyLongObject *)_PyLong_Copy(a);
Py_DECREF(a);
}
else
r = a;
Py_DECREF(b);
Py_XDECREF(c);
Py_XDECREF(d);
return (PyObject *)r;
}
x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
(a->ob_digit[size_a-3] >> nbits));
y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
(size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
(size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
/* inner loop of Lehmer's algorithm; A, B, C, D never grow
larger than PyLong_MASK during the algorithm. */
A = 1; B = 0; C = 0; D = 1;
for (k=0;; k++) {
if (y-C == 0)
break;
q = (x+(A-1))/(y-C);
s = B+q*D;
t = x-q*y;
if (s > t)
break;
x = y; y = t;
t = A+q*C; A = D; B = C; C = s; D = t;
}
if (k == 0) {
/* no progress; do a Euclidean step */
if (l_mod(a, b, &r) < 0)
goto error;
Py_SETREF(a, b);
b = r;
alloc_a = alloc_b;
alloc_b = Py_SIZE(b);
continue;
}
/*
a, b = A*b-B*a, D*a-C*b if k is odd
a, b = A*a-B*b, D*b-C*a if k is even
*/
if (k&1) {
T = -A; A = -B; B = T;
T = -C; C = -D; D = T;
}
if (c != NULL) {
Py_SET_SIZE(c, size_a);
}
else if (Py_REFCNT(a) == 1) {
c = (PyLongObject*)Py_NewRef(a);
}
else {
alloc_a = size_a;
c = _PyLong_New(size_a);
if (c == NULL)
goto error;
}
if (d != NULL) {
Py_SET_SIZE(d, size_a);
}
else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
d = (PyLongObject*)Py_NewRef(b);
Py_SET_SIZE(d, size_a);
}
else {
alloc_b = size_a;
d = _PyLong_New(size_a);
if (d == NULL)
goto error;
}
a_end = a->ob_digit + size_a;
b_end = b->ob_digit + size_b;
/* compute new a and new b in parallel */
a_digit = a->ob_digit;
b_digit = b->ob_digit;
c_digit = c->ob_digit;
d_digit = d->ob_digit;
c_carry = 0;
d_carry = 0;
while (b_digit < b_end) {
c_carry += (A * *a_digit) - (B * *b_digit);
d_carry += (D * *b_digit++) - (C * *a_digit++);
*c_digit++ = (digit)(c_carry & PyLong_MASK);
*d_digit++ = (digit)(d_carry & PyLong_MASK);
c_carry >>= PyLong_SHIFT;
d_carry >>= PyLong_SHIFT;
}
while (a_digit < a_end) {
c_carry += A * *a_digit;
d_carry -= C * *a_digit++;
*c_digit++ = (digit)(c_carry & PyLong_MASK);
*d_digit++ = (digit)(d_carry & PyLong_MASK);
c_carry >>= PyLong_SHIFT;
d_carry >>= PyLong_SHIFT;
}
assert(c_carry == 0);
assert(d_carry == 0);
Py_INCREF(c);
Py_INCREF(d);
Py_DECREF(a);
Py_DECREF(b);
a = long_normalize(c);
b = long_normalize(d);
}
Py_XDECREF(c);
Py_XDECREF(d);
simple:
assert(Py_REFCNT(a) > 0);
assert(Py_REFCNT(b) > 0);
/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
undefined behaviour when LONG_MAX type is smaller than 60 bits */
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
/* a fits into a long, so b must too */
x = PyLong_AsLong((PyObject *)a);
y = PyLong_AsLong((PyObject *)b);
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
x = PyLong_AsLongLong((PyObject *)a);
y = PyLong_AsLongLong((PyObject *)b);
#else
# error "_PyLong_GCD"
#endif
x = Py_ABS(x);
y = Py_ABS(y);
Py_DECREF(a);
Py_DECREF(b);
/* usual Euclidean algorithm for longs */
while (y != 0) {
t = y;
y = x % y;
x = t;
}
#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
return PyLong_FromLong(x);
#elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
return PyLong_FromLongLong(x);
#else
# error "_PyLong_GCD"
#endif
error:
Py_DECREF(a);
Py_DECREF(b);
Py_XDECREF(c);
Py_XDECREF(d);
return NULL;
}