0
Asking for help in Python
Hi everyone, my question is that I need a program written in Python (but no problem if it's on other, I just need the idea) to operate some numbers on a n-term list. Like this: [a, b, c] a+b+c, a+b-c, a+b*c, a+b/c, a-b+c, a-b-c, ... and so on. If anyone knows a way to do that please let me know. Thanks.
4 Respostas
+ 5
# With basic loops structure (could be shorwrited/improved using list iteration methods, and/or list comprehension notation, but basic way is better self-explaining):
op = '+-*/'
nb = [1,2,3]
c = len(nb)-1
d = len(op)
D = pow(d,c)
i = 0
a = []
while (i<D):
N = ''
j = i
for n in range(c):
k = j%d
j = j//d
N = str(op[k])+N
a.append(N)
i += 1
print(a,'\n')
b = []
for o in a:
N = str(nb[0])
for i in range(c):
N += o[i]+str(nb[i+1])
b.append(N)
print(b,'\n')
r = []
for e in b:
r.append(eval(e))
print(e,'=',r[-1:][0])
+ 2
# I'm not posting this here for votes, just something to look at curiously (it works, but it annoyed me).
from itertools import product,starmap
varList = ["a", "b", "c"]
formatString = "{}".join(varList)
print(*starmap(formatString.format, product('+-/*', repeat=len(varList)-1)))
# ----- long version of last line ------
r = len(varList)-1
p = product('+-/*', repeat = r)
s = starmap(formatString.format, p)
print(*s)
# ----- explanation -----
# Any number of variables works with this method
# formatString = "a{}b{}c"
# p returns a tuple sequence with 2 repeats (16 tuples): ('+', '+',) ('+', '-') ... ('*', '*')
# format() wants two parameters, p returns tuples, starmap expands tuples
# *s expands the starmap object into its output
+ 1
You can loop through the list, right?
The simplest way is:
1. On each iteration you can ask what operation to process (*, /, +, - )
2. Keep the current result in a variable.
3. At the end print the result variable.
+ 1
##for getting the logic use @ Visph's idea..
##i am giving a non-headeache method..
import itertools
def findsubsets(S,m): ## change the m and try also for bigger no. of digits
for i in set(itertools.permutations(S, m)) :
e=eval('1'+i[0]+'2'+i[1]+'3')
print('1'+i[0]+'2'+i[1]+'3 =',e)
return None
findsubsets("+/+/-*-*",2)
## author--> Sayan Chandra