unique number of occurrance in a number range - python-3.x

I am interested in figuring out how many times each number occurs once in a numberrange of 5 digits, like 01234, 01243, 01324, etc ....
I know that the occurence is 120 unique times
At the moment I have programmed it with a lot of for loops and a lot of ands.
as you can see in the code
number = 5
for a in range(number):
for b in range(number):
for c in range(number):
for d in range(number):
for e in range(number):
if (a != b and a != c and a != d and a != e and
b != c and b != d and b != e and c != d and
c != e and d != e):
print ('{}{}{}{}{}'.format(a, b, c, d, e))
Is there a different and a nicer way to program the code above?
Greets,
Superfly

Someone suggested using itertools. Here is the code to use:
from itertools import permutations
#generator
factorials = permutations(set(range(5)))
for fact in factorials:
print(fact)
If you would not like to use itertools, but would like to generate every string, you can use a list comprehension to put it all in one line.
rn = range(number)
number= 5
sequences = [(a,b,c,d,e) for a in rn for b in rn for c in rn for d in rn for e in rn if a != b and a!= c and a!= d and a!= e and b!= c and b!=d and b!=e and c!=d and c!= e and d!= e]
Alternatively, you could define a method to recursively create new lists and append items
def rGenFactorials(L, leng=5, collected = [], restrictions=set()):
# base case
if len(L) == leng:
collected.append(L)
return
#induction
options = set(range(leng))
options -= restrictions
for op in options:
# copy restrictions
r = set(restrictions)
# add new restriction
r.add(op)
# copy list
l = L[:]
# append unused int
l.append(op)
# recursive invocation
rGenFactorials(L=l,collected = collected, restrictions=r)
C = []
rGenFactorials([], collected = C)
for c in C:
print(c)

Related

Converting Multiple string inputs to int

I'm trying to convert a, b, c, d to integers, but after I've tried doing this they still come up as strings. I've tried using a loop instead of map, but that didn't work either.
inputs = input()
split_input = inputs.split()
a, b, c, d = split_input
split_input = list(map(int, split_input))
Just swap the last 2 lines:
split_input = list(map(int, split_input))
a, b, c, d = split_input
Unless you need split_input later on, you don't need the list conversion at all:
split_input = map(int, split_input)
a, b, c, d = split_input
# OR in fact simply
a, b, c, d = map(int, split_input)

How can one represent distinct non-numeric symbols in sympy?

I am experimenting with the representation of a trivial statistics problem in Sympy:
For a sample space S, there are 6 possible distinct outcomes
a,b,c,d,e,f. We can define event A as having occurred if any of
a,b,c have, and event B as having ocurred if any of b,c,d have.
Given a probability mass function pmf defined over S, what is the
probability of event A?
When attempting to implement this symbolically, I receive the following error:
~/project/.envs/dev/lib/python3.6/site-packages/sympy/stats/frv.py in _test(self, elem)
164 elif val.is_Equality:
165 return val.lhs == val.rhs
--> 166 raise ValueError("Undecidable if %s" % str(val))
167
168 def __contains__(self, other):
ValueError: Undecidable if Eq(d, a) | Eq(d, b) | Eq(d, c)
The problem is implemented as follows with comments on the failing lines of code:
from sympy import Eq, Function, symbols
from sympy.logic import Or
from sympy.sets import FiniteSet, Union
from sympy.stats import FiniteRV, P
# 1. Define a sample space S with outcomes: a,b,c,d,e,f; Define events A, B
A = FiniteSet(*symbols('a b c'))
B = FiniteSet(*symbols('b c d'))
S = Union(A, B, FiniteSet(*symbols('e f')))
display("Sample Space", S)
pmfFunc = Function("pmf")
pmfDict = {v: pmfFunc(v) for v in S}
X = FiniteRV('X', pmfDict)
a,b = symbols('a b')
# 2. P(X = a) = pmf(a)
display(P(Eq(X,a)))
# 3. A.as_relational(X) yields `(X=a) \lor (X=b) \lor (X=c)`
display(A.as_relational(X))
# 4. P(X = a \lor X = b) = pmf(a) + pmf(b)
# - Actual Output: ValueError: Undecidable if Eq(c, a) | Eq(c, b)
display(P(Or(Eq(X,a), Eq(X,b)))) # [FAILS]
# 5. P(A) = pmf(a) + pmf(b) + pmf(c)
# - Actual Output: ValueError: Undecidable if Eq(d, a) | Eq(d, b) | Eq(d, c)
display(P(A.as_relational(X))) # [FAILS]
I obtain expected output up to display(A.as_relational(X)):
Interpreting the failure message suggests that Sympy is unable to tell that the set members are distinct. Replacing the symbols with integers resolves the error and I get output similar to what I desire.
A = FiniteSet(1, 2, 3)
B = FiniteSet(2, 3, 4)
S = Union(A, B, FiniteSet(5, 6))
If I am not misunderstanding the error or the fundamental use of the library, is there a way to tell Sympy that a collection of symbols is entirely distinct? I have attempted to replace the symbols with Dummy instances without success, and I have also attempted to leverage the assumptions module without success:
facts = [Eq(a,b) if a is b else Not(Eq(a,b)) for a, b in itertools.product(S, S)]
with assuming(*facts):
I would like to avoid confusing mappings between integers and symbolic forms, as user error may not be apparent when the results are printed as latex. I am willing to adopt some burden in a workaround (e.g., as it would have been maintaining a collection of Dummy instances), but I have yet to find an acceptable workaround.
Interesting question. Maybe it can be done with with assuming(Ne(a,b), ...): context but I take a more pragmatic approach: replace symbols with cos(non-zero integer) which SymPy can easily distinguish as equal or not:
>>> reps = dict(zip(var('a:f'),(cos(i) for i in range(1,7))))
>>> ireps = {v:k for k,v in reps.items()}
>>> a,b,c,d,e,f = [reps[i] for i in var('a:f')]
Then remove your a, b = symbols... line and replace display(x) with display(x.subs(ireps) to get
('Sample Space', FiniteSet(a, b, c, d, e, f))
(pmf(a),)
(Eq(X, a) | Eq(X, b) | Eq(X, c),)
(pmf(a) + pmf(b),)
(I use cos(int) instead of int because I am not sure whether any computation would result in addition of two elements and I want to make sure they stay distinct.)
Another approach would be to define a constant class that derives from Symbol:
class con(Symbol):
def __hash__(self):
return id(self)
def __eq__(a,b):
if isinstance(b, con):
return a.name == b.name
_eval_Eq = __eq__
a,b,c,d,e,f=map(con,'abcdef')
display=lambda*x:print(x)
from sympy import Eq, Function, symbols
from sympy.logic import Or
from sympy.sets import FiniteSet, Union
from sympy.stats import FiniteRV, P
A = FiniteSet(a,b,c)
B = FiniteSet(b,c,d)
S = Union(A, B, FiniteSet(e,f))
pmfFunc = Function("pmf")
pmfDict = {v: pmfFunc(v) for v in S}
X = FiniteRV('X', pmfDict)
display("Sample Space", S)
display(P(Eq(X,a)))
display(A.as_relational(X))
display(P(Or(Eq(X,a), Eq(X,b))))
display(P(A.as_relational(X)))
gives
('Sample Space', FiniteSet(a, b, c, d, e, f))
(pmf(a),)
(Eq(X, a) | Eq(X, b) | Eq(X, c),)
(pmf(a) + pmf(b),)
(pmf(a) + pmf(b) + pmf(c),)

python finding the greatest common divisor of two numbers program

I am a new Python learner. I am trying to finding the greatest common divisor of two numbers (a =1071 and b = 462 for example). I have written two programs for this. the first one is working but the second one gives the wrong answer. what is the problem with my program??
# first program (works)
a, b = 1071, 462
while b:
a, b = b, a % b
print(a)
# second program (doesn't work truly)
a = 1071
b = 462
while b:
a = b
b = a % b
print(a)
Explanation:
Yes, HSK is right. In the 2nd loop:
while b:
a = b
b = a % b
print(a)
First a is changed to b and then what you do is b = b% b. But here:
a, b = b, a % b
it is executed as one-line so a is still a.
Solution:
So just add a third variable:
a = 1071
b = 462
while b:
c = a
a = b
b = c % b
print(c)
One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line.
The second doesn't work because, for the calculation of b, you need to use the old a, not the new a that got generated on the line before (this is actually set to b so you will get b % b, which will generally be zero). The equivalent to the first loop would be:
while b:
oldA = a
a = b
b = oldA % b
print(a)
The tuple assignment in Python can be considered an atomic operation where all the values on the right side are loaded up, then assigned to all the variables on the left side.
def divisor(n):
if n ==1 or n ==2 or n ==3:
return []
else:
result=[]
aux=2
while aux <= n:
if n % aux == 0:
result.append(aux)
aux=aux+1
return result
def func (m,n):
div1=divisor(m)
div2=divisor(n)
result =[]
for x in div1:
for y in div2:
if x == y:
result.append(x)
return result
print(func (x,y))

Different syntax, different result

I'm trying an ultra simple novice exercise.
The objective of the exercise was to create a fibonacci pattern, I tried two methods that I thought were going to give the same result. But fires some reason they don't, I can't understand why.
Any ideas?
CODE 1
a = 0
b = 1
while b < 100:
print(b)
a = b
b = a + b
CODE 2:
a, b = 0, 1
while b < 100:
print(b)
a, b = b, a + b
In "CODE 1", a = b makes the next line equivalent to b = b + b, which is not correct.
In "CODE 2", a,b=b,a+b is essentially new_a = old_b; new_b = old_a + old_b. The new values are computed from the old values, then the new values are assigned to the variables. This computes the fibonacci series correctly.
To do it correctly in "CODE 1" a temporary variable is needed:
t = a
a = b
b = t + b # use original a saved in t to compute b
a,b=b,a+b eliminates the need for the temporary variable.

Replacing list in list of list , gives only zeros

I have a matrice (list of list) say a and I want to normalize each "row" such that each element corresponds to the fraction of the corresponding row, i.e [p/sum(p) for p in row].
I have the following code
a_norm[:] = a
for i,row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
the rows being printed (print(b)) are completely fine but a_norm consists of purely zeros for some reason.
EDIT: Adding an example.
a=np.array([[1,2,3], [20,22,13]]) should give a_norm=[[0.16,0.33,0.5],[0.36,0.4,0.24]]
try this one:
a_norm = [[i / sum(row) for i in row] for row in a]
Mistake you did in making list copy.
use a_norm = a[:] instead of a_norm[:] = a
You can try:
a_norm = a[:]
for i, row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
print(a_norm)

Resources