Multiply digits in list [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 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],[])

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 do i print every 3rd number in a list in python WITHOUT USING slice notation (square brackets)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
def every_third(lst):
'''
every_third that takes a list as a parameter and returns
a new list that contains every third element of the original
list, starting at index 0.
>>> every_third([1,2,3,4,5,6,7,8,9,10])
[1,4,7,10]
How would I do this? I know that we can use a for loop, but i just dont know how to begin.
If range is allowed with all of start, stop, step (which is not exactly slice notation), just do:
def every_third(lst):
return [lst[i] for i in range(0, len(lst), 3)]
If not, use a conditional comprehension with a condition based on modulo:
def every_third(lst):
return [lst[i] for i in range(len(lst)) if i%3 == 0]
Another trick using enumerate:
seq = [1,2,3,4,5,6,7,8,9,10]
every_three = [value for idx, value in enumerate(seq) if idx % 3 == 0]
But my first comment if code review of lines above would be: Use slice syntax, there's no need to use an enumerate here.
If the problem is just the slice notation, as in [::3] I think it should be somethink like this, I figure You are doing exercises right?
list=[1,2,3,4,5,6,7,8,9,10]
def third(list):
res=[]
count=3
res.append(list[0])
while len(list)>0:
if count>0:
list.pop(0)
else:
res.append(list[0])
list.pop(0)
count=3
count -= 1
return res
print(third(list))

Python: Total sum of a list of numbers with the for loop [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 8 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm new to Python and I have this problem:
I need to program a Python function that gives me back the sum of a list of numbers using a for loop.
I just know the following:
sum = 0
for x in [1,2,3,4,5]:
sum = sum + x
print(sum)
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum is already built in!
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum

Python : Subtracting inside an array [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 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)

Categories