Multiplying every Nth element in a list by M - python

I have a problem I can't seem to figure out. I am very new to Python and have only been coding for three weeks. Any help is appreciated.
Problem:
We are passing in 3 inputs:
a list of numbers
a multiplier value, M
a value, N
You should multiply every Nth element (do not multiply the 0th element) by M. So if N is 3, you start with the 3rd element, which is index 2.
If there are less than N elements then you should output the unchanged input list.
I can't seem to figure this out. I have tried many different things here. Currently, I have the following, which is not working at all.
Provided:
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
My Code:
for N in numbers:
if numbers[i] > 0:
total = N * M
print(total)
else:
print(numbers)
Output:
I am not even close to what the output should be. Feeling lost on this. Here is what my code comes to. It looks like they want the output in a list.
Program Failed for Input: 1,2,3,4,5,6 5 3
Expected Output: [1, 2, 15, 4, 5, 30]
Your Program Output:
5
10
15
20
25
30

You could try a list comprehension with slicing.
numbers[N-1::N] = [x * M for x in numbers[N-1::N]]

A more elegant solution using list comprehensions ;)
[item*M if (index and not (index+1)%N) else item for index, item in enumerate(items)]

This solution is based on your original one. A more pythonic one would use for instance, a list comprehension so keep that in mind in the future,
output = [numbers[0]]
if len(numbers) >= N:
for i in range(1,len(numbers)):
if ((i+1)%N) is 0:
output.append(numbers[i]*M)
else:
output.append(numbers[i]);
else:
output = numbers
If N is not larger than the list size, the program constructs a new list of numbers with each Nth number being multiplied by M. This is done with a simple modulo operator. Indexing in Python starts with zero and i iterates through index values but your desired output counts the elements as if starting from 1 - thus i+1 in the modulo. If it is not every Nth - program just append the old value. If the list is shorter than N altogether, it assigns the whole unchanged list to the output list.

will this work for you?
res = []
for num in numbers:
if num > 0:
total = num * M
res.append(total)
if len(res) != len(numbers):
print (numbers)
else:
res.reverse()
print (res)

So after many attempts and bouncing this off of a friend who works as a programmer, I ended up with this that gave me the proper output:
newlist = []
if len(numbers) < N:
newlist = numbers
else:
for i in range(0, len(numbers)):
num = numbers[i]
if (i+1) % N == 0:
newlist.append(num*M)
else:
newlist.append(num)
i+=1
print(newlist)

# Input
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
# convert strings to integers
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
# if the length of our list is greater than our supplied value
# loop to multiply(starting at the 3rd position in the list) by M
if len(numbers) > N :
for num in range(2, len(numbers), 3) :
numbers[num] = numbers[num] * M
print(numbers)

Related

Sum of random list numbers after 1st negative number

import random
def mainlist(list, size, min, max):
for i in range(size):
list.append(random.randint(min, max))
print(list)
def counterlist(list):
for i in list:
if i<0:
x=sum(list[(list.index(i)+1):])
print('Reqemlerin cemi:', x)
break
list = []
mainlist(list, 10, -10, 30)
counterlist(list)
I need to calculate sum of numbers after 1st negative number in this random list, did it in second function but want to know is there way not using the sum() function?
Explicitly using an iterator makes it nicer and more efficient:
def counterlist(lst):
it = iter(lst)
for i in it:
if i < 0:
print('Reqemlerin cemi:', sum(it))
No idea why you wouldn't want to use the sum function, that's absolutely the right and best way to do it.
Try this:
import random
lst = [random.randint(-10, 30) for _ in range(10)]
print(sum(lst[next(i for i, n in enumerate(lst) if n < 0) + 1:]))
First you generate the list lst. Then, you iterate over your list and you find the first negative element with next(i for i, n in enumerate(lst) if n < 0). Finally, you compute the sum of the portion of the list you're interested about.
If you really don't want to use sum but keep things concise (and you're using python >= 3.8):
import random
lst = [random.randint(-10, 30) for _ in range(10)]
s = 0
print([s := s + x for x in lst[next(i for i, n in enumerate(lst) if n < 0) + 1:]][-1])
Assuming there's a negative value in the list, and with a test list "a":
a = [1,2,3,-7,2,3,4,-1,23,3]
sum(a[(a.index([i for i in a if i < 0][0]) + 1):])
Evaluates to 34 as expected. Could also add a try/except IndexError with a simple sum to catch if there's no negative value.
Edit: updated the index for the search.
Yes, you can iterate over the elements of the list and keep adding them to some var which would store your result. But what for? sum approach is much more clear and python-ish.
Also, don't use list as a list name, it's a reserved word.
# After you find a first negative number (at i position)
j = i + 1
elements_sum = 0
while j < len(list):
elements_sum += list[j]
j += 1
Not as good as the marked answer, but just to know how to make use of numpy, being sure there is a negative number in the list.
Sample list: lst = [12, 2, -3, 4, 5, 10, 100]
You can get your result using np.cumsum:
import numpy as np
np_lst = np.array(lst)
cum_sum = np.cumsum(np_lst)
res = cum_sum[-1] - cum_sum[np_lst<0][0]
res #=> 119
First of all don't use list as a variable name, it's a reserved keyword. Secondly, make your loop as follows:
for index, x in enumerate(list_):
if x < 0:
sum_ = sum(list_[(index + 1):])
print('Reqemlerin cemi:', sum_)
break
That way, you don't need to find a value.
At last if you don't want to use sum
found_negative = false
sum_ = 0
for x in list_:
if found_negative:
sum_ += x
elif x < 0:
found_negative = true
print('Reqemlerin cemi:', sum_)

Python Program to Print all Numbers in a Range Divisible by a Given Number

Python Program to Print all Numbers in a Range Divisible by a Given Numbers
L=int(input()) #L=[2,4,5] take all input at a time to process with range number divisible with give inputs those numbers print output is 20,40 bcuz of 2,4,5 divisible 20, 40 only
L=int(input))
for i in l:
for j in range(1,50):
if j%i==0:
print(j)
I want out put 20,40
Range divisible with all list l
I'm not sure quite sure what you're asking, but I think the gist of it is that you want to print all numbers in a given range that are divisible by a list.
In that case, there is no need to do a type coercion to int on your list, I'm not sure why you did that.
my_list = [2, 4, 5]
# create an empty output list
output = []
# iterate through a range.
for i in range(1, 50):
# create a boolean array that checks if the remainder is 0 for each
# element in my_list
if all([i % j == 0 for j in my_list]):
# if all statements in the boolean list created above are true
# (number is divisible by all elements in my_list), append to output list
output.append(i)
print(output)
First you need to calculate the least common multiple (lcm) of the numbers in the list. Math library in python 3.9 has included a lcm function, so you can use it. If you dont have python 3.9 you can search some solutions.
import math
lcm = math.lcm(2,4,5)
At this point you know that every integer number that you multiply by 20 is going to be divisible by all the numbers in the list (2 * 20=40, 3 * 20=60 ...). So for a range you must divide the maximum range number (in your case 50) and truncate the result.
high = 50
low = 1
n = int(high/lcm)
Make a loop and multiply from 1 to n by the lcm result. Then for each result check if it is equal or higher than the lower range.
for j in range(1,n):
res = j*lcm
if res >= low:
print(res)
values = int(input('enter value count :'))
n = []
for k in range(values):
temp = int(input('enter int value :'))
n.append(temp)
for i in range(1,50):
count = 0
for j in n:
if i%j == 0:
count=count+1
else:
if count==len(n):
print(i,end=',')

How to sum even and odd values with one for-loop and no if-condition?

I am taking a programming class in college and one of the exercises in the problem sheet was to write this code:
number = int(input())
x = 0
y = 0
for n in range(number):
if n % 2 == 0:
x += n
else:
y += n
print(x)
print(y)
using only one "for" loop, and no "while" or "if".
The purpose of the code is to find the sum of the even and the sum of
the odd numbers from zero to the number inputted and print it to the
screen.
Be reminded that at this time we aren't supposed to know about
functions.
I've been trying for a long time now and can't seem to find a way of doing it without using "if" statements to know if the loop variable is even or odd.
Purely for educational purposes (and a bit of fun), here is a solution that does not use any for loops at all. (Granted, in the underlying logic of the functions, there are at least five loops.)
num = list(range(int(input('Enter number: '))))
even = num[::2]
odd = num[1::2]
print('Even list:', even)
print('Odd list:', odd)
print('Even:', sum(even))
print('Odd:', sum(odd))
Output:
Enter number: 10
Even list: [0, 2, 4, 6, 8]
Odd list: [1, 3, 5, 7, 9]
Even: 20
Odd: 25
How does it work?
The input() function returns a str object, which is converted into an integer using the int() function.
The integer is wrapped in the range() and list() functions to convert the given number into a list of values within that range.
This is a convention you will use/see a lot through your Python career.
List slicing is used to get every second element in the list. Given the list is based at zero, these will be even numbers.
Slice the same list again, starting with the second element, and get every second element ... odd numbers.
Link to a nice SO answer regarding slicing in Python.
The simply use the sum() function to get the sums.
for n in range(number):
x += (1 - n % 2) * n
y += (n % 2) * n
You asked for a solution with one loop, but how about a solution with no loop?
It is well known that the sum of the numbers from 1 to n is (n+1)*n/2. Thus, the sum of even numbers is 2 * (m+1)*m/2 with m = n//2 (i.e. floor(n/2)). The sum of odd can then be calculated by the sum of all numbers minus the sum of even numbers.
n = 12345
m = n // 2
e = (m+1)*m
o = (n+1)*n//2 - e
Verification:
>>> e, e==sum(i for i in range(n+1) if i % 2 == 0)
38112102 True
>>> o, o==sum(i for i in range(n+1) if i % 2 == 1)
38105929 True
Note: This calculates the sums for number up to and including n.
for n in range(1,number,2):
x += n
y += n-1
print(y)
print(x)
This code has the same output with the example.
Ternary operator:
for n in range(number):
x += (n,0)[n%2]
y += (0,n)[n%2]
I think you are a beginner. I wouldn't like to confuse you with slicing operators complex implementation.
As you mentioned
The purpose of the code is to find the sum of the even and the sum of
the odd numbers from zero to the number inputted and print it to the
screen.
There is no need to find the initial number is odd/even
And your program is wrong if you want to include the input number in calculating the even/odd sum.
Example
Input
5
Expected Output
6
9
Explanation
Even Sum : 2+4 = 6
Odd Sum : 1+3+5 = 9
Your Output
6 4 (wrong output)
The range() function will exclude the number. It will only iterate from 0 to 4 while the input is 5. so if you want to include 5, you should add 1 to the number while passing it in the range() function.
number = int(input())
x = 0
y = 0
for n in range(number+1):
x += (1 - n % 2) * n #this will add 0 if not even
y += (n % 2) * n #this will add 0 if not odd
print(x)
print(y)
There is also mathematical way:
num = int(input("Enter number:"))
odd = ((num+1)/2)**2
even = num*(num+1)/2 - odd
The sum of the first n odd numbers is n^2. To get count of odd numbers we use (num+1)/2. To get sum of even numbers, we could use similar approach, but I preferred, subtracting odd from the sum of the first n numbers, which is n*(n+1)/2.
Here is my 2cents if we are allowed to use numpy.
import numpy as np
number = int(input())
l = np.array(range(number))
print('odd:',sum(l % 2 * l))
print('even:', sum((1- l % 2) * l))
If you're allowed to use a list
number = int( input() )
counts = [ 0, 0 ]
for n in range( number ):
counts[ n % 2 ] += n
print( counts[ 0 ] )
print( counts[ 1 ] )
There's another way which sums the odd and even indices together in the for loop based on the remainder modulo 2:
number = int(input())
odd = 0
even = 0
for i in range(len(number)):
odd += i * (i % 2)
even += i * ((i + 1) % 2)
print (odd, even)
number = 1000000
x = 0
y = 0
[(x:=x+n, y:=y+(n+1)) for n in range(0,number,2)]
print(f'{x}, {y}')
This uses a list comprehension and the new Python assignment operator.
Sum of first n numbers is n(n+1)/2 (Mathematically derived). So if we know the value of n then we can find the sum of all numbers from 1 to n.
If we find the sum of all odd numbers before n and subratract it from the sum of first n we get he sum of all even numbers before n.
Here's the code:
n = int(input("Enter a number: "))
odd = 0
for i in range(1,n+1,2):
odd += i
even = int(n*(n+1)/2) - odd
print("even:",even,"odd:",odd)

Write an efficient algorithm in python to solve math problem

I can't came up with an algorithm to solve the following problem:
Generate an array of first n prime numbers.
Remove k numbers from this array in such way that after concatenating all numbers left we get the largest possible result.
E.G.
Input: 4 2
First value(4) is n
Second value(2) is k
Array [2, 3, 5, 7] is generated
the program have to remove numbers 2 and 3 from this array(to get 57, which is the max possible number we can get from this array after deleting k numbers and merging all the numbers left together).
e.g. If it removes 2 and 7 - we will get 35(which is not the max number). So, this solution is wrong.
Output: 57
This is the code I have so far:
def getInputedVals():
return [int(el) for el in input().split(" ")]
def get_primes_array(x):
primes = []
a = 2
# for a in range(2, 10000):
while(len(primes) != x):
for b in range(2, a):
if a % b == 0:
break
else:
primes.append(a)
a += 1
if len(primes) == x:
return primes
def combine_numbers(nums):
s = [str(i) for i in nums]
return int("".join(s))
# Algorithm to find the max number should be written here
def get_result(nums, n_nums_to_delete):
print("algorithm goes here")
def main(item):
primes = get_primes_array(item["n_first"])
summed = sum(primes)
# print(get_result(primes, item["n_nums_to_delete"]))
print("Primes: ", primes)
n_first, n_nums_to_delete = getInputedVals()
item = {"n_first": n_first, "n_nums_to_delete": n_nums_to_delete}
main(item)
You have the answer, sort your results and take the sorted list starting from the n_nums_to_delete :
def get_result(nums, n_nums_to_delete):
return sorted(nums)[n_nums_to_delete:]
As #Yuri Ginsburg mentioned in the comment, your prime number list is already sorted, so you can simply do :
def get_result(nums, n_nums_to_delete):
return nums[n_nums_to_delete:]

How can I find the sum of numbers in a list that are not adjacent to a given number?

Given a list of integers and number, I want to find the sum of all numbers in the list such that numbers and before and after a given number are not added. The given number should also be excluded from the numbers used for the final sum.
Examples:
mylist=[1,2,3,4]
number=2
#output is 4
mylist=[1,2,2,3,5,4,2,2,1,2]
number=2
#output is 5
mylist=[1,7,3,4,1,7,10,5]
number=7
#output is 9
mylist=[1,2,1,2]
number=2
#output is 0
In the first example, only the number 4 is not adjacent to the number 2. Thus the sum is 4. In the last example, no numbers meet the criteria so the sum is 0.
This is what I tried:
def add(list1,num):
for i,v in enumerate(list1):
if v==num:
del list1[i-1:i+2]
print list1
add([1,7,3,4,1,7,10,5],7)
However, my code only works for first and third example.
I worked through your code and here is a working solution:
def check_around(array, index, num):
return True if array[index - 1] != num and array[index + 1] != num else False
def get_result(array, num):
arr = []
for i, number in enumerate(array):
if number != num:
if i == 0 and array[1] != num: # Beginning of list
arr.append(number)
elif (i > 0 and i < len(array) - 1) and check_around(array, i, num): # Middle of list
arr.append(number)
elif i == len(array) - 1 and array[i-1] != num: # End of list
arr.append(number)
return arr
test = [([1,2,3,4], 2),
([1,2,2,3,5,4,2,2,1,2], 2),
([1,7,3,4,1,7,10,5], 7),
([1,2,1,2], 2)]
for (arr, num) in test:
res = get_result(arr, num)
print(f'output is {sum(res)}')
#output is 4
#output is 5
#output is 9
#output is 0
The idea is to create a temp array that saves items that do belong in the summation. Otherwise, we ignore them.
I tried all the tests you gave and it seems to be working fine. Hope this helps.
Get the indexes of the element into a list. +1 and -1 to those will give you indexes of 'before' and 'after' elements. Then take the sum avoiding elements in all these indexes.
list=[1,2,2,3,5,4,2,2,1,2]
number=2
#get all indexes of that number
list_of_indexes=[i for i,x in enumerate(list) if x==number]
#no need to remove -1 if there b'coz we are going to enumerate over 'list'
before_indexes=[i-1 for i in list_of_indexes]
#no need to remove len(list) index if present
after_indexes=[i+1 for i in list_of_indexes]
#might contain duplicate values but no problem
all_indexes_to_avoid=list_of_indexes+before_indexes+after_indexes
sum=sum([x for i,x in enumerate(list) if i not in all_indexes_to_avoid ])
print(sum)
Output
5
Why not just use a if statement and generate a new list instead of removing from the list?
def add(list,num):
j=0
new_list=[]
for i in range(len(list)):
if (i<len(list)-1 and list[i+1]==num) or list[i]==num or list[j]==num:
pass
else:
new_list.append(list[i])
j=i
print(sum(new_list))
print(new_list)
return sum
add([1,2,3,4],2)
add([1,2,2,3,5,4,2,2,1,2],2)
add([1,7,3,4,1,7,10,5],7)
add([1,2,1,2],2)
OUTPUT
4
[4]
5
[5]
9
[4, 5]
0
[]

Categories