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)
Related
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))
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)
Is there an easy way to search for a sequence of strings in a list? For example:
testlist = [a,b,c,d,e,f,g,a,b,c,d,j,k,j]
and I want to search for the sequence abc and getting the index returned. So to clarify if the string I want to search consists of more than one element of the list. For some context: I have a list with datablocks and I want to find out how big each datablock is therefore searching for a reoccuring string in the list.
There are many good string search algorithms: KMP, Boyer-Moore, Rabin-Karp. You can use the builtin str.index function on ''.join(L) if you are dealing with characters (str.index implements Boyer-Moore algorithm in CPython: https://github.com/python/cpython/blob/3.7/Objects/stringlib/fastsearch.h).
But in most cases, the naive algorithm is good enough. Check every index of the haystack to find the needle:
>>> a, b, c, d, e, f, g, j, k = [object() for _ in range(9)]
>>> haystack = [a, b, c, d, e, f, g, a, b, c, d, j, k, j]
>>> needle = [a, b, c]
>>> for i in range(len(haystack)-len(needle)+1):
... if haystack[i:i+len(needle)] == needle:
... print(i)
...
0
7
The complexity is O(|haystack|*|needle|).
I'm trying to write a function to back solve for a variable from another function in python, kind of like what Excel solver does.
To simplify my example, I have a function takes in several variables then calculate a price. I will be passing actual values (a,b,c,d,x) into this function so it returns a numeric value.
def calc_price(a,b,c,d,x):
value = a+b*c-d + x
return value
Now I'm given a target price, and a,b,c,d. Only unknown is variable x, so I want to back solve variable x. I want to build this into a function that takes into the same variables as calc_price, with an additional variable target_price.
def solve(target_price, a,b,c,d):
#this function takes in values for target_price, a,b,c,d
#and should do something like this:
target_price = calc_price(a,b,c,d,x)
solve for x <---------this is the part I'm not sure how to do
return x
I created a function like this below to back solve the value x by a loop but it's inefficient in calculating large datasets, so I'm looking for a more efficient solution.
def solve(target_price,a,b,c,d):
x = 0.01
while x < 1:
if abs(target_price - calc_price(a,b,c,d,x)) < 0.001:
return x
x += 0.001
Thank you!
Consider this a demo (as your task is still a bit unclear to me) and make sure to read scipy's docs to learn about the basic guarantees these method provides.
One could argue, that an approach based on root-finding is more appropriate (we are minimizing a function here; therefore the abs-construction in the residual-function), but this approach here does not need you to give some bracketing-interval.
Code:
import numpy as np
from scipy.optimize import minimize_scalar
np.random.seed(0)
""" Utils """
def calc_price(x, a, b, c, d):
value = a+b*c-d + x
return value
def calc_price_res(x, target, a, b, c, d):
value = a+b*c-d + x
return abs(value - target) # we are looking for f(x) == 0
""" Create fake-data (typically the job of OP!) """
a, b, c, d, x = np.random.random(size=5)
fake_target = calc_price(x, a, b, c, d)
print('a, b, c, d: ', a, b, c, d)
print('real x: ', x)
print('target: ', fake_target)
print('noisy obj (just to be sure): ', calc_price_res(x, fake_target, a, b, c, d))
""" Solve """
res = minimize_scalar(calc_price_res, args=(fake_target, a, b, c, d))
print('optimized x: ', res.x)
print('optimized fun: ', res.fun)
Output:
a, b, c, d: 0.548813503927 0.715189366372 0.602763376072 0.544883182997
real x: 0.423654799339
target: 0.858675077275
noisy obj (just to be sure): 0.0
optimized x: 0.423654796297
optimized fun: 3.04165614917e-09
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)