Python : Subtracting inside an array [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to subtract the values in an array with 10 values that the user inputs. So far I can't find how to do that. This is what I have...
g = 0
q = []
for s in range(9):
while g < 10:
n = input()
q.append(int(n))
g = g+1
add = sum(Q)
sub =

There are more succinct ways to do this; I've opted instead for readability:
# get our initial input:
n = input()
result = int(n)
# subtract the rest of the user's inputs:
for x in range(9):
n = input()
result -= int(n)
# ... do something with the result ...

You don't need to assign all of those to individual variables. At each iteration of the loop, you could just append the newly input value to the array:
q = []
g = 0
while g < 10:
n = input()
q.append(int(n))
g = g + 1
At the end of this loop, q will contain the 10 values that the user entered.
It's not clear to me what needs to be subtracted from what, but that might get you a little closer to where you need to be.

Be pythonic
a = [int(input()) for x in range(10)]
Or for python 2.X
a = [int(raw_input()) for x in xrange(10)]
This gives you a list containing 10 integers.
Then you can
q = map(lambda x: x-sum(a), q),
which subtracts the sum of user inputs

Just use python API
li = []
for x in xrage(10):
li.append(input())
result = reduce(lambda x, y: x - y, li)

Related

Deleting max value in set without max() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a working code
task = set()
x = 1
while x != 0:
x = int(input('input your number '))
task.add(x)
print('Just 0 could stop it!')
task.remove(max(task))
print(max(task))
And need to get the same result without using max(). What could be an alternative?
Something like this, unless you have really large sets, I don`t see the advantage
task = set()
x = 1
m = 0
while x != 0:
x = int(input('input your number '))
task.add(x)
if x > m:
m = x
print('Just 0 could stop it!')
task.remove(m)
print(max(task))
Notice this will only work for positive numbers, if you want to the complete int range you should init m like this m = -sys.maxsize - 1
You could use min with a key arg that inverts the element:
>>> task = {1, 2, 3, 4, 5}
>>> max(task)
5
>>> min(task, key=lambda x: -x)
5
Or you could sort it and take the last element...
>>> sorted(task)[-1]
5

How to duplicate numbers in string n times? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).
I want to duplicate the numbers in the string n times, the 61 i want to duplicate twice, the 62 i want to duplicate four times, how do i code something that duplicates a number in the string n times?
Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)
if both your inputs are strings:
a = '(61, 62, 63, 64,)'
b = '(2,4,1,1)'
a = [i for i in a[1:-1].strip().replace(" ","").split(",")]
a.remove('')
b = [int(i) for i in b[1:-1].strip().replace(" ","").split(",")]
result = "("
for i in range(len(b)):
for j in range(b[i]):
result += a[i]
result += ", "
result = result.strip()[:-1]+")"
print(result)
Here is a possible solution (if rep is a string and not a tuple, you just need to do rep = eval(rep)):
s = "(61,62,63,64)"
rep = (2,4,1,1)
# convert the string to a tuple
t = eval(s)
# compute the result as a tuple
result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
# convert the result into a string
result = str(result)
If you want something more compact:
s = "(61,62,63,64)"
rep = (2,4,1,1)
result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))
Be careful with using eval!! Check this question for more info.

How the looping with for in Python really works? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm learning python and in a test, I made a class that have a list of numbers, in other class, a list of previous class. In the second class, I wrote a method for put the numbers dinamically but it put the numbers x times for the length of the list of previous class.
def make_connection(self, number):
if not self.__has_con:
for i in range(number):
self.__weight.append(1)
self.__has_con = True
The method above is from the first class, to get n numbers.
inp = len(self.__inputs)
for n in self.__hidden:
n.make_connection(inp)
This is from the second class. If __hidden has 9 objects, it put the inp 9 times for all the 9 elements.
init of second class
def __init__(self, array):
if isinstance(array, list):
if len(array) > 2:
inps = []
hidd = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[len(array)-1]):
k = kn(kn.OUTPUT)
outs.append(k)
a = array[1:]
h = a[:len(a)-1]
if len(h) > 1:
for i in h:
hd = []
for p in range(i):
k = kn(kn.HIDDEN)
hd.append(k)
hidd.append(hd)
else:
for p in range(h[0]):
k = kn(kn.HIDDEN)
hidd.append(k)
self.__inputs = inps
self.__hidden = hidd
self.__output = outs
else:
inps = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[0]):
k = kn(kn.OUTPUT)
outs.append(k)
self.__inputs = inps
self.__output = outs
The for var in collection syntax in Python uses an iterator. Instead of a for loop where you specify a starting value, an increment and a terminating value, it says iterate over all the values in the collection.
So when you say this in Python:
for x in range(4):
print x
it's like saying this in other languages:
for (x = 0; x < 4; ++x) {
print(x);
}
Python's range returns a iterator over 0..4 in this case. In your example, Python gives you each element of your collection.
See, for more details: https://www.w3schools.com/python/python_iterators.asp
In python Use the for loop like that:
for str in str_list
print (str)

Is it valid to write some code that a bit tricky as long as I get same result (fibonacci in python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In Pycharm Edu I've encountered with this code:
def fib(n):
"""This is documentation string for function. It'll be available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 1
b = 1
while a < n:
result.append(a)
tmp_var = b
b = a+b
a = tmp_var
return result
Since I am still learning I tried to do something similar with lists but the problem is to get a proper fibonacci series I used [-1,1] to start calculation, but results are same. Here is my code:
x = [-1,1]
y = []
for i in range(10):
c = x[0] + x[1]
y.append(c)
x[0] = x[1]
x[1] = c
print(y)
The question is, can I get away with this ?
This question might be too opinion-based for this site, but take into consideration that your code doesn't just need to run, it also needs to be readable. Otherwise, what you have written is entirely valid.
Consider this:
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
print(fibonacci_sequence)
As I said, this may seem like opinion, but make sure you keep the beginning PEP 20 in mind:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts...
As a final note, your code is not a function, but the original code snippet is a function. Here is your code as a function:
def fibonacci():
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
return fibonacci_sequence
print(fibonacci())

Multiply digits in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Let's say we have list of numbers and we want to multiply all numbers in it as long as product is digit.
For Example:
[2,2,5] => [4,5]
[3,3,7] => [9,7]
[5,5,5,5,5] => [5,5,5,5,5]
Can I somehow use functools.reduce here? What's pythonic way to solve this problem?
This can be solved easily by a simple stateful algorithm:
def multiply_digits(lst):
res = []
for x in lst:
if res and res[-1] * x < 10:
res[-1] *= x
else:
res.append(x)
return res
While there is an equivalent functional way (with reduce), that will not be as simple since you either need to reassemble the result list in each step, or carry the current number value separately.
This might do the trick:
def process(lst):
lst = sorted(lst)
last = 1
result = []
for el in lst:
if last * el >= 10:
result.append(last)
last = el
continue
last *= el
result.append(last)
return result
This is better I guess:
from numpy import product
reduce(lambda x , y : (x[0:-1]+[y*x[-1]] if product(x+[y])<10 else x+[y]) if len(x)>0 else [y] ,[21,1,2,3,4,5,6],[])

Categories