It gives the character that is represented by the ASCII code "34".
If you look up an ASCII table you will notice that 34 = "
Answer from Loocid on Stack OverflowIt gives the character that is represented by the ASCII code "34".
If you look up an ASCII table you will notice that 34 = "
The %c is a format character gives the character representation. For example consider the following statements
>>> print "%c" % 'a'
a
>>> print ("%c" % 97)
a
>>> print "%c" %'"'
"
>>> print "%c" %34
"
>>> print "%c" %'asdf'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %c requires int or char
Breaking up
"%c" % 34 == '"'
would be like
>>> "%c" % 34
"
>> '"' == '"'
True
How to use the -c flag in python - Stack Overflow
Can we use C code in Python? - Stack Overflow
printf - How to print a C format in python - Stack Overflow
How is python able to use c code?
Just pass regular Python code as the argument to the flag:
python -c 'print 1
print 2'
Import modules works, and blank lines are OK, too:
python -c '
import pprint
pprint.pprint(1)
'
When using this feature, just be mindful of shell quoting (and indentation), and keep in mind that if you're using this outside of a few shell scripts, you might be doing it wrong.
Easiest example
python -c "print 'example'"
It is useful whenever your program has a single line of code, for example, list comprehensions, etc.
Another example can be
python -c "a='example';print a"
As you can see, multiple statements are separated by ;
I want to invoke those C function or executables in python. Is that possible.
Yes, you can write C code that can be imported into Python as a module. Python calls these extension modules. You can invoke it from Python directly, an example from the documentation:
Python Code
import example
result = example.do_something()
C Code
static PyObject * example(PyObject *self)
{
// do something
return Py_BuildValue("i", result);
}
If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.
You build it as a shared library *.dll or *.so You can also investigate using distutils to distribute your module.
If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?
If you write a *.exe then you are doing the opposite (invoking Python from C). The method you choose (exe vs shared library) depends on if you want a "C program with some Python" or a "Python program with some C".
Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?
Python reads *.py files and compiles to *.pyc bytecode files when you run it. The bytecode is then run in the Python virtual machine. This means "executing the same file is faster the second time as recompilation from source to bytecode can be avoided." (from the Python glossary) So if you haven't edited your *.py files, it will run the *.pyc. You can distribute *.pyc files without *.py files, however they are not encrypted and can be reverse-engineered.
You don't necessary need to extend Python (which is not trivial, btw), but can use foreign function interface such as ctypes.
Strings overload the modulus operator, %, for printf-style formatting, and special case tuples for formatting using multiple values, so all you need to do is convert from list to tuple:
print(string % tuple(agrs))
Tuple:
Example:
print("Total score for %s is %s " % (name, score))
In your case:
print(string % tuple(agrs))
Or use the new-style string formatting:
print("Total score for {} is {}".format(name, score))
Or pass the values as parameters and print will do it:
print("Total score for", name, "is", score)
Source
I was always curious how python modules in c work. I know how to write and use a python c module, but i dont know how it works internally. Can anyone put me in the right path where can i start, an article or sthm or try to explain. And are there any simple tutorials to implement that sort of thing. Like calling .so files from your language etc...
It's combining two-arg next (which pulls the next value from an iterator, and if the iterator is exhausted returns the second argument as the default) with a generator expression, which is like a lazy list comprehension (it produces an iterator/generator that produces values on demand).
So:
r = next((c for c in l if config.equalsForConfigSet(c)), None)
in English, means "Get the first element of l for which config.equalsForConfigSet of that element is truthy; if no such element is found, return None". And it does it lazily, or if you prefer, with short-circuiting, so as soon as one c value passes, it doesn't need to continue; the rest of l isn't even loaded, let alone tested (unlike how a list comprehension would do it).
In code, you could express the same behavior with a function like so:
def firstEqualsConfigSet(l, config):
for c in l:
if config.equalsForConfigSet(c):
# Short-circuit: got one hit, return it
return c
# Didn't find anything
return None # Redundant to explicitly return None, but illustrating
# that two-arg next could use non-None default
then use the function to do:
r = firstEqualsConfigSet(l, config)
My understanding is
next(iterator, default) The next() function returns the next item from the iterator.
its taking 'c' from the for loop which is extracting c from the list l (populated earlier), wherein the for loop is evaluating with a condition that config.equalsForConfigSet(C) should return true.
If there is no value for 'c' in the first parameter to next(), it will return None
https://www.programiz.com/python-programming/methods/built-in/next
Some ways would be:
def mod_c0(a, b):
if b < 0:
b = -b
return -1 * (-a % b) if a < 0 else a % b
def mod_c1(a, b):
return (-1 if a < 0 else 1) * ((a if a > 0 else -a) % (b if b > 0 else -b))
def mod_c2(a, b):
return (-1 if a < 0 else 1) * (abs(a) % abs(b))
def mod_c3(a, b):
r = a % b
return (r - b) if (a < 0) != (b < 0) and r != 0 else r
def mod_c4(a, b):
r = a % b
return (r - b) if (a * b < 0) and r != 0 else r
def mod_c5(a, b):
return a % (-b if a ^ b < 0 else b)
def mod_c6(a, b):
a_xor_b = a ^ b
n = a_xor_b.bit_length()
x = a_xor_b >> n
return a % (b * (x | 1))
def mod_c7(a, b):
a_xor_b = a ^ b
n = a_xor_b.bit_length()
x = a_xor_b >> n
return a % ((-b & x) | (b & ~x))
def mod_c8(a, b):
q, r = divmod(a, b)
if (a >= 0) != (b >= 0) and r:
q += 1
return a - q * b
def mod_c9(a, b):
if a >= 0:
if b >= 0:
return a % b
else:
return a % -b
else:
if b >= 0:
return -(-a % b)
else:
return a % b
which all work as expected, e.g.:
print(mod_c0(31, -3))
# 1
Essentially, mod_c0() implements an optimized version of mod_c1() and mod_c2(), which are identical except that in mod_c1() the call to (relatively expensive) call to abs() is replaced by a ternary conditional operator with the same semantic.
Instead, mod_c3() and mod_c4() try to directly fix the a % b value for the cases where it is needed. The difference between the two is in how they detect opposite signs of the arguments: (a < 0) != (b != 0) versus a * b < 0.
The mod_c5() approach is inspired by @ArborealAnole's answer, and essentially uses the bit-wise xor to handle the cases correctly, while mod_c6() and mod_c7() are the same as @ArborealAnole's answer but using adaptive right shift with int.bit_length().
The mod_c8() approach uses a corrected definition of integer division to fix up the modulus value.
The mod_c9() method is inspired by @NeverGoodEnough's answer, and essentially goes full conditional.
Covering all sign cases:
vals = (3, -3, 31, -31)
s = '{:<{n}}' * 4
n = 14
print(s.format('a', 'b', 'mod(a, b)', 'mod_c(a, b)', n=n))
print(s.format(*(('-' * (n - 1),) * 4), n=n))
for a, b in itertools.product(vals, repeat=2):
print(s.format(a, b, mod(a, b), mod_c0(a, b), n=n))
a b mod(a, b) mod_c(a, b)
------------- ------------- ------------- -------------
3 3 0 0
3 -3 0 0
3 31 3 3
3 -31 -28 3
-3 3 0 0
-3 -3 0 0
-3 31 28 -3
-3 -31 -3 -3
31 3 1 1
31 -3 -2 1
31 31 0 0
31 -31 0 0
-31 3 2 -1
-31 -3 -1 -1
-31 31 0 0
-31 -31 0 0
A bit more tests and benchmarks:
import itertools
n = 100
l = [x for x in range(-n, n + 1)]
ll = [(a, b) for a, b in itertools.product(l, repeat=2) if b]
funcs = mod_c0, mod_c1, mod_c2, mod_c3, mod_c4, mod_c5, mod_c6, mod_c7, mod_c8, mod_c9
for func in funcs:
correct = all(func(a, b) == funcs0 for a, b in ll)
print(f"{func.__name__} correct:{correct} ", end="")
%timeit -n 8 -r 8 [func(a, b) for a, b in ll]
# mod_c0 correct:True 8 loops, best of 8: 9.67 ms per loop
# mod_c1 correct:True 8 loops, best of 8: 11.1 ms per loop
# mod_c2 correct:True 8 loops, best of 8: 12.3 ms per loop
# mod_c3 correct:True 8 loops, best of 8: 10.3 ms per loop
# mod_c4 correct:True 8 loops, best of 8: 10 ms per loop
# mod_c5 correct:True 8 loops, best of 8: 10.1 ms per loop
# mod_c6 correct:True 8 loops, best of 8: 17.1 ms per loop
# mod_c7 correct:True 8 loops, best of 8: 20.3 ms per loop
# mod_c8 correct:True 8 loops, best of 8: 15.8 ms per loop
# mod_c9 correct:True 8 loops, best of 8: 9.29 ms per loop
Perhaps there are better (shorter?, faster?) ways, given that the implementation of Python's % using C's % seems much simpler:
((a % b) + b) % b
To get some feeling on how the C-style % computation (mod_c*() functions from above) stands against the usual % or the operations required to get Python-style % from C:
def mod_py(a, b):
return a % b
def mod_c2py(a, b):
return ((a % b) + b) % b
%timeit [mod_py(a, b) for a, b in ll]
# 100 loops, best of 3: 5.85 ms per loop
%timeit [mod_c2py(a, b) for a, b in ll]
# 100 loops, best of 3: 7.84 ms per loop
Note of course that mod_c2py() is only useful to get a feeling of what performances we could expect from a mod_c() function.
(EDITED to fix some of the proposed methods and include some timings)
(EDITED-2 to add the mod_c5() solution)
(EDITED-3 to add the mod_c6() to mod_c9() solutions)
I am following up the very comprehensive answer of @norok2. I have tried the super-naive approach with branches, and it appears to be slightly but consistently faster (~2-4%).
def mod_naive(x,y):
if y < 0:
if x < 0:
return x%y
else:
return (x%-y)
else:
if x < 0:
return -(-x%y)
else:
return x%y
or with a lambda (does not affect speed, only coolness):
mod_naive = lambda x,y: (x%y if x < 0 else x%-y) if y < 0 else (-(-x%y) if x < 0 else x%y)
Compared to @norok2's fastest solution (mod_c0):
mod_c0 correct: True 100 loops, best of 3: 6.86 ms per loop mod_naive correct: True 100 loops, best of 3: 6.58 ms per loop
My (naive) guess on the reason why is that the branch prediction algorithms will eventually produce less operations overall.