Calculating Log base c in python3 - python-3.x

Is there a way to calculate log base c in python?
c is a variable and may change due to some dependencies.
I am new to programming and also python3.

There is already a built in function in the math module in python that does this.
from math import log
def logOc(c, num):
return log(num,c)
print(log(3,3**24))
You can read more about log and the python math module here

Yes, you can simply use math's function log():
import math
c = 100
val = math.log(10000,c) #Where the first value is the number and the second the base.
print(val)
Example:
print(val)
2.0

Related

ipython: print numbers with thousands separator

I am using ipython 5.8.0 on Debian 10.
This is how output looks like:
In [1]: 50*50
Out[1]: 2500
Is it possible to configure ipython to print all numbers with thousands separators? ie:
In [1]: 50*50
Out[1]: 2'500
In [2]: 5000*5000
Out[2]: 25'000'000
And perhaps, is it possible to make ipython also understand thousands separators on input?
In [1]: 5'000*5'000
Out[1]: 25'000'000
UPDATE
The accepted answer from #Chayim Friedman works for integers, but does not work for float:
In [1]: 500.1*500
Out[1]: 250050.0
Also, when it works, it uses , as the character for thousand separator:
In [1]: 500*500
Out[1]: 250,000
Can I use ' instead?
Using ' as thousands separator in input is quite problematic because Python uses ' to delimit strings, but you can use _ (PEP 515, Underscores in Numeric Literals):
Regarding output, this is slightly harder, but can be done using IPython extensions.
Put the following Python code in a new file at ~/.ipython/extensions/thousands_separator.py:
default_int_printer = None
def print_int(number, printer, cycle):
printer.text(f'{number:,}') # You can use `'{:,}'.format(number)` if you're using a Python version older than 3.6
def load_ipython_extension(ipython):
global default_int_printer
default_int_printer = ipython.display_formatter.formatters['text/plain'].for_type(int, print_int)
def unload_ipython_extension(ipython):
ipython.display_formatter.formatters['text/plain'].for_type(int, default_int_printer)
This code tells IPython to replace the default int formatter with one that prints thousand separators when this extension is loaded, and restore the original when it is unloaded.
Edit: If you want a different separator, for instance ', replace the f'{number:,}' with f'{number:,}'.replace(',', "'").
You can load the extension using the magic command %load_ext thousands_separator and unload it using %unload_ext thousands_separator, but if you want it always, you can place it in the default profile.
Run the following code in the terminal:
ipython3 profile create
It will report that a file ~/.ipython/profile_default/ipython_config.py was created. Enter it, and search for the following string:
## A list of dotted module names of IPython extensions to load.
#c.InteractiveShellApp.extensions = []
Replace it with the following:
# A list of dotted module names of IPython extensions to load.
c.InteractiveShellApp.extensions = [
'thousands_separator'
]
This tells IPython to load this extension by default.
Done!
Edit: I saw that you want to a) use ' as separator, and b) do the same for floats:
Using different separator is quite easy: just str.replace():
def print_int(number, printer, cycle):
printer.text(f'{number:,}'.replace(',', "'"))
Doing the same for floats is also easy: just setup print_int so it prints floats to. I also suggest to change the name to print_number.
Final code:
default_int_printer = None
default_float_printer = None
def print_number(number, printer, cycle):
printer.text(f'{number:,}'.replace(',', "'"))
def load_ipython_extension(ipython):
global default_int_printer
global default_float_printer
default_int_printer = ipython.display_formatter.formatters['text/plain'].for_type(int, print_number)
default_float_printer = ipython.display_formatter.formatters['text/plain'].for_type(float, print_number)
def unload_ipython_extension(ipython):
ipython.display_formatter.formatters['text/plain'].for_type(int, default_int_printer)
ipython.display_formatter.formatters['text/plain'].for_type(float, default_float_printer)
After update: you can subclass int:
class Int(int):
def __repr__(self):
return "{:,}".format(self)
Int(1000)
# 1,000
I don't believe you can achieve all that you are looking for without rewriting the iPython interpreter, which means changing the Python language specification, to be able to input numbers with embedded ' characters and have them ignored. But you can achieve some of it. Subclassing the int class is a good start. But you should also overload the various operators you plan on using. For example:
class Integer(int):
def __str__(self):
# if you want ' as the separator:
return "{:,}".format(self).replace(",", "'")
def __add__(self, x):
return Integer(int(self) + x)
def __mul__(self, x):
return Integer(int(self) * x)
"""
define other operations: __sub__, __floordiv__, __mod__, __neg__, etc.
"""
i1 = Integer(2)
i2 = Integer(1000) + 4.5 * i1
print(i2)
print(i1 * (3 + i2))
Prints:
1'009
2'024
Update
It seems that for Python 3.7 you need to override the __str__ method rather than the __repr__ method. This works for Python 3.8 and should work for later releases as well.
Update 2
import locale
#locale.setlocale(locale.LC_ALL, '') # probably not required
print(locale.format_string("%d", 1255000, grouping=True).replace(",", "'"))
Prints:
1'255'000
An alternative if you have package Babel from the PyPi repository:
from babel import Locale
from babel.numbers import format_number
locale = Locale('en', 'US')
locale.number_symbols['group'] = "'"
print(format_number(1255000, locale='en_US'))
Prints:
1'255'000
Or if you prefer to custom-tailor a locale just for this purpose and leave the standard en_US locale unmodified. This also shows how you can parse input values:
from copy import deepcopy
from babel import Locale
from babel.numbers import format_number, parse_number
my_locale = deepcopy(Locale('en', 'US'))
my_locale.number_symbols['group'] = "'"
print(format_number(1255000, locale=my_locale))
print(parse_number("1'125'000", locale=my_locale))
Prints:
1'255'000
1125000
Based on PEP-0378, you can use the following code:
a = 1200
b = 500
c = 10
#res = a
#res = a*b
res = a*b*c
dig = len(str(res)) # to figure out how many digits are required in result
print(format(res, "{},d".format(dig)))
It will produce:
6,000,000

Python equivalent of Pulse Integration (pulsint) MATLAB function?

I am surfing online to find Python equivalent of function pulsint of MATLAB , and till now I haven't found anything significantly close to it.
Any heads up in this regards will be really helpful!
You can easily create your own pulsint function.
The pulsint formula:
You need the numpy library to keep the things simple
import numpy as np
import matplotlib as mpl
# Non coherent integration
def pulsint(x):
return np.sqrt(np.sum(np.power(np.absolute(x),2),0))
npulse = 10;
# Random data (100x10 vector)
x = np.matlib.repmat(np.sin(2*np.pi*np.arange(0,100)/100),npulse,1)+0.1*np.random.randn(npulse,100)
# Plot the result
mpl.pyplot.plot(pulsint(x))
mpl.pyplot.ylabel('Magnitude')

How to use get_operation_by_name() in tensorflow, from a graph built from a different function?

I'd like to build a tensorflow graph in a separate function get_graph(), and to print out a simple ops a in the main function. It turns out that I can print out the value of a if I return a from get_graph(). However, if I use get_operation_by_name() to retrieve a, it print out None. I wonder what I did wrong here? Any suggestion to fix it? Thank you!
import tensorflow as tf
def get_graph():
graph = tf.Graph()
with graph.as_default():
a = tf.constant(5.0, name='a')
return graph, a
if __name__ == '__main__':
graph, a = get_graph()
with tf.Session(graph=graph) as sess:
print(sess.run(a))
a = sess.graph.get_operation_by_name('a')
print(sess.run(a))
it prints out
5.0
None
p.s. I'm using python 3.4 and tensorflow 1.2.
Naming conventions in tensorflow are subtle and a bit offsetting at first.
The thing is, when you write
a = tf.constant(5.0, name='a')
a is not the constant op, but its output. Names of op outputs derive from the op name by adding a number corresponding to its rank. Here, constant has only one output, so its name is
print(a.name)
# `a:0`
When you run sess.graph.get_operation_by_name('a') you do get the constant op. But what you actually wanted is to get 'a:0', the tensor that is the output of this operation, and whose evaluation returns an array.
a = sess.graph.get_tensor_by_name('a:0')
print(sess.run(a))
# 5

Iterate through each integer python separated by a blankspace/endline

I am a Python 2.7 user who recently switched to python3. While reading integers separated by a blackspace/endline I used nex = iter(map(int,stdin.read().split())).next, where nex() acts as a function to input integers (Suppose for inputting an integral value in x -> x=nex(). But in python3 this doesn't seem to work. Someone please propose a workaround for using the same in Python3.
.next() method is called .__next__() in Python 3. You could use next() function to write single-source Python 2/3 compatible code:
from functools import partial
nex = partial(next, iter(iterable))
print(nex())

RPy2 Convert Dataframe to SpatialGridDataFrame

how can a Dataframe be converted to a SpatialGridDataFrame using the R maptools library? I am new to Rpy2, so this might be a very basic question.
The R Code is:
coordinates(dataf)=~X+Y
In Python:
import rpy2
import rpy2.robjects as robjects
r = robjects.r
# Create a Test Dataframe
d = {'TEST': robjects.IntVector((221,412,332)), 'X': robjects.IntVector(('25', '31', '44')), 'Y': robjects.IntVector(('25', '35', '14'))}
dataf = robjects.r['data.frame'](**d)
r.library('maptools')
# Then i could not manage to write the above mentioned R-Code using the Rpy2 documentation
Apart this particular question i would be pleased to get some feedback on a more general idea: My final goal would be to make regression-kriging with spatial data using the gstat library. The R-script is working fine, but i would like to call my Script from Python/Arcgis. What do you think about this task, is this possible via rpy2?
Thanks a lot!
Richard
In some cases, Rpy2 is still unable to dynamically (and automagically) generate smart bindings.
An analysis of the R code will help:
coordinates(dataf)=~X+Y
This can be more explicitly written as:
dataf <- "coordinates<-"(dataf, formula("~X+Y"))
That last expression makes the Python/rpy2 straigtforward:
from rpy2.robjects.packages import importr
sp = importr('sp') # "coordinates<-()" is there
from rpy2.robjects import baseenv, Formula
maptools_set = baseenv.get('coordinates<-')
dataf = maptools_set(dataf, Formula(' ~ X + Y'))
To be (wisely) explicit about where "coordinates<-" is coming from, use:
maptools_set = getattr(sp, 'coordinates<-')

Resources