write a python program to print sum of 3 consecutive numbers in a range in a list. for example we take input n = 8 so the program will print
[1+2+3,2+3+4,3+4+5,4+5+6+,5+6+7,6+7+8]
means the output should be
=[6,9,12,15,18,21]
i am new in programming, my code is:-
arr=[]
N=int(input("enter the value of N"))
def lst(arr):
for i in range(N):
x=[i]+[i+1]+[i+2]
arr.append(x)
lst(arr)
print(arr)
This will give you the output you are looking for. It starts indexed at 1 instead of 0 and calls sum on the lists you are creating in each iteration.
Edit: as pointed out in the comments, creating these lists is unnecessary you can just do a sum.
arr=[]
N=int(input("enter the value of N"))
def lst(arr):
for i in range(1, N - 1):
x = (i) + (i + 1) + (i + 2) # for ease of reading
arr.append(x)
lst(arr)
print(arr)
Using list comprehension - given a list and a length of interest lgt:
l = list(range(1, 9))
lgt = 3
print([sum(l[i-lgt:i]) for i in range(lgt, len(l) + 1)])
OUTPUT
[6, 9, 12, 15, 18, 21]
Why can't you use list comprehension,
In [1]: [(i+1) + (i+2) + (i+3) for i in range(7)]
Out[1]: [6, 9, 12, 15, 18, 21, 24]
Related
I have to replace in a list the multiples of 5 by the number + x. For example, if I have the list [1,3,5,7,9,9,11,13,15,17,19,21,23,25,27,29], the result has to be [1,3,5x,7,9,11,13,15x,17,19,21,23,25x,27,29]. I have tried to develop the script but it doesn't work, can anyone help me?
numbers = list (range(1,31))
odds = [number for number in numbers if number % 2 == 1]
print(odds)
for index, value in enumerate(odds):
if value%5==0:
odds[index] = '5x'
print(odds)
We can solve your problem by using the value variable, which stores the current number. We just need to reference this variable when setting the current element to add to "x", like this:
odds[index] = str(value) + "x"
Notice the need to cast value as a string, as we cannot concatinate an integer and a string without creating a touple.
You can make your code much simpler:
numbers = range(1, 31, 2)
res = [str(i) + 'x' if i%5 == 0 else i for i in numbers]
print(res)
Result:
[1, 3, '5x', 7, 9, 11, 13, '15x', 17, 19, 21, 23, '25x', 27, 29]
Explanation:
numbers = range(1, 31, 2)
This creates an iterable with odd numbers from 1 to 29 without having to do:
numbers = list(range(1,31))
odds = [number for number in numbers if number % 2 == 1]
which is redundant. The syntax for the range function is range(start, stop, step), so for odd numbers from 1 to 30, it'll be range(1, 31, 2) which will give 1, 3, 5, 7, and so on.
res = [str(i) + 'x' if i%5 == 0 else i for i in numbers]
I'm assuming you know how to use list comprehensions since you've used it in your code. The above line of code simply searches for a value that is divisible by 5 and adds an x to this value, else it simply adds i to the list.
You can also use f-strings instead of str(i) + x (as Stuart suggests under Jensen's answer):
res = [f'{i}x' if i%5 == 0 else i for i in numbers]
I'm calling a function inside itself many times to solve the subset sum problem, using as it called, the recursion solution; anyway, I can't figure out why n (which is the number of elements of the array) value is getting decreasing at first, until it reach 0, which is I get it, but then, after calling it again within itself, it makes n value incremented. Why is that happening, as the whole function doesn't even have an increment contribution for the n value? Where n gets its increasing value from?
Here is the code:
def printAllSubsetsRec(arr, n, currentSubset, sum):
# If remaining sum is 0, then print all
# elements of current subset.
if (sum == 0):
i = 0
sumOfValue = 0
for value in currentSubset:
i += 1
sumOfValue += value
if (i == len(currentSubset)):
print(value, " = ", sumOfValue)
else:
print(value, end=" + ")
return True
# If there are no elements in the array and the sum is not equal to 0.
if (n == 0 and sum != 0):
return None
# I consider two cases for every element:
# a) Excluding last element.
# b) Including last element in current subset.
# -------------------------------------------------
# Excluding the last element:
printAllSubsetsRec(arr, n - 1, currentSubset, sum)
v = [] + currentSubset
v.append(arr[n - 1])
# Including the last element:
printAllSubsetsRec(arr, n - 1, v, sum - arr[n - 1])
#Main:
arr = [10, 7, 5, 18, 12, 20, 15]
sum = 35
n = len(arr)
currentSubset = []
printAllSubsetsRec(arr, n, currentSubset, sum)
The output should be:
18 + 7 + 10 = 35
12 + 18 + 5 = 35
20 + 5 + 10 = 35
15 + 20 = 35
Thanks in advance!
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutation, variable reassignment, and other side effects -
logical if without a corresponding else
mutation and reassignment of i and sumOfValue
side effects like print
Recursion doesn't have to be difficult or painful. Using functional disciplines we can write subsets(t,n) with inductive reasoning -
If the target sum n is zero, yield the empty solution
(inductive) otherwise n is negative or positive. If n is negative or the input array t is empty, we are out-of-bounds. stop iteration.
(inductive) n is positive and t has at least one element. For all s of the subproblem (t[1:],n-t[0]), prepend t[0] to s and yield. And yield all results of the subproblem (t[1:],n)
def subsets(t, n):
if n == 0:
yield () #1
elif n < 0 or not t:
return #2
else:
for s in subsets(t[1:], n - t[0]): #3
yield (t[0], *s)
yield from subsets(t[1:], n)
for s in subsets([10, 7, 5, 18, 12, 20, 15], 35):
print(s)
(10, 7, 18)
(10, 5, 20)
(5, 18, 12)
(20, 15)
Notice -
All operations do not mutate or reassign variables
Side effects like print are traded for yield
Caller is free to utilize and transform the results any way desired
To format the results as an mathematical expression -
for s in subsets([10, 7, 5, 18, 12, 20, 15], 35):
print(" + ".join(map(str, s)), "=", 35)
10 + 7 + 18 = 35
10 + 5 + 20 = 35
5 + 18 + 12 = 35
20 + 15 = 35
To collect all outputs of a generator into a list, use list -
print(list(subsets([10, 7, 5, 18, 12, 20, 15], 35)))
[(10, 7, 18), (10, 5, 20), (5, 18, 12), (20, 15)]
i'm trying to write a function where user can input a list of numbers, and then each number gets squared based on range 0 to n. For example, i want to input 7 and then the output is in range 0 to 7 is all square
number = []
n = int(input('input number: '))
for i in range(0, n):
n.append(i**2)
print(n)
a list comprehension is a great way to accomplish this in a fairly compact bit of code. https://realpython.com/list-comprehension-python/
n = int(input('input number: '))
squares = [x*x for x in range(n)]
List comprehensions are quite good for this situation.
number = [entry**2 for entry in range(n)]
Python one-liner :)
vals=list(map(lambda x:int(x)**2,input().split()))
print(vals)
Here is the output: [0,1,4,9,16,..]
This should do it
number = []
for i in range(8):
number.append(int(input('input number: '))**2)
print(number)
Given the list:
n = [3, 6, 12, 24, 36, 48, 60]
I need to turn a random number divisible by 3, after by 6, after by 12, after by 24, after by 36, after by 48 and after by 60. One at each time, not the divisible for the seven numbers simultaneously.
But, to make the number divisible, I need to sum another number to reach the number divisible by 3, 6, 12, 24, 36, 48 or 60.
I don't know the random number neither the number to add to this random number in order to turn it divisible by 3, 6, 12, 24, 36, 48 or 60.
Can someone help me, please?
Using the map function list comprehension:
import random
n = [3, 6, 12, 24, 36, 48, 60]
a = random.randint(start, stop)
result = [a + x - a % x if a % x else a for x in n]
addition = [x - a for x in result]
print(a)
print(result)
print(addition)
start and stop are the limits for your random number.
Output for a = 311:
311
[312, 312, 312, 312, 324, 336, 360]
[1, 1, 1, 1, 13, 25, 49]
Begin of the old answer to the rather unclear question before the first edit by the author.
The following post answers the question: Which is the next number after a, which is a multiple of all numbers of the list n, if it is not a?
First the least common multiple lcm of the numbers from the list must be determined. For this purpose, the method least_common_multiple is executed for the complete list. The modulo operation then checks whether a is not already a multiple of the numbers. If this is the case, a is output. Otherwise, the next multiple of lcm is output.
from math import gcd
from functools import reduce
n = [3, 6, 12, 24, 36, 48, 60]
a = 311
def least_common_multiple(x, y):
return abs(x * y) // gcd(x, y)
lcm = reduce(least_common_multiple, n)
result = a if a > 0 else 1 # can be change if necessary, see edit
mod = result % lcm
if mod:
result += (lcm - mod)
print('Current number: ' + str(a))
print('The next number divisible by any number from the given list: ' + str(result))
print('Necessary addition: ' + str(result - a))
Output:
Current number: 311
The next number divisible by any number from the given list: 720
Necessary addition: 409
Edit: Changed the code so that 0 is no longer a valid result for a non-positive a.
However, if it is valid, you can change the code at the commented part with: result = a.
New answer for the clarified question:
import math
def f(x, a):
return math.ceil(a / x) * x - a
n = [3, 6, 12, 24, 36, 48, 60]
a = 311
result = [f(x, a) for x in n]
print(result)
Old answer:
I think you're looking for the LCM (lowest common multiple) of all numbers in n. We can get the LCM for two numbers using the GCD (greatest common divisor). We can then use reduce to get the LCM for the whole list. Assuming x can be negative, simply subtract a from the LCM to get your answer. The code could look like this:
import math
from functools import reduce
def lcm(a, b): # lowest common multiple
return a * b // math.gcd(a, b)
n = [3, 6, 12, 24, 36, 48, 60]
smallest_divisible_by_all = reduce(lcm, n)
a = 311
x = smallest_divisible_by_all - a
print(x)
which outputs
409
If speed is not important, you could also do a brute force solution like this:
ns = [3, 6, 12, 24, 36, 48, 60]
a = 311
x = 0
while not all([(a + x) % n == 0 for n in ns]):
x += 1
(assuming that x >= 0)
So I can think of 2 solutions:
First if you want a list which show how much you have to add for the random number to get to a divisible number:
def divisible(numbers,random):
l = []
for number in numbers:
if random % number != 0:
l += [number - (random % number)]
else:
l += [0]
return l
a = 311
n = [3, 6, 12, 24, 36, 48, 60]
print(divisible(n,a))
Output:
[1, 1, 1, 1, 13, 25, 49]
Or if you want to know how far is the smallest number from the random number that everyone shares as divisible. For this take a look how you calculate lcm.
from math import gcd
def divisible_all(numbers, random):
lcm = numbers[0]
for i in numbers[1:]:
lcm = lcm*i//gcd(lcm, i)
tempLcm = lcm
while lcm < random: # in case the lcm is smaller than the random number add lcm until it is bigger (I assume you only allow positive numbers)
lcm += tempLcm
return lcm-random
print(divisible_all(n,a))
Output:
409
You can do:
import math
n = [3, 6, 12, 24, 36, 48, 60]
div_n={el: False for el in n}
a=311
a0=math.ceil(a/max(n)) * max(n)
while not all(div_n.values()):
div_n={el: False for el in n}
# print(a0)
for el in n:
if(a0 % el > 0):
a0=math.ceil(a0/el) * el
break
else:
div_n[el]=True
print(a0-a)
Output:
409
I'm trying to find the avg of list but only when n >= 10 (two digit numbers, my original list is limited to 100).
Here's what I have right now:
# Calculate average of all two-digit numbers (10-99)
grade_list = [10, 11, 12, 13, 14, 15]
def calcAvg(grade_list):
while n > 10:
total = sum(grade_list)
n = total % len(grade_list)
print_list = n
return print_list
I get that I have to find the total sum of the list when n > 10 and then dividing by the length (only > 10, my original list has single digit elements, so I'd like to avoid them).
But when I run it, I get an error saying: local variable 'n' referenced before assignment
Any help on how to structure this function to achieve the end results (sum/total of only 2-digit elements = avg)
Thanks!
I'd either collect the good grades and use sum/len, or use the mean function:
>>> grade_list = [1, 2, 10, 11, 12, 13, 14, 15]
>>> good = [g for g in grade_list if g > 10]
>>> sum(good) / len(good)
13.0
>>> import statistics
>>> statistics.mean(g for g in grade_list if g > 10)
13.0
def calcAvg(grade_list):
my_list = []
total, count = 0,0
for n in grade_list:
if 10 <= n <= 99:
total += n
if not total:
return None
return total/count
Here is a clean way of doing it:
def calc_avg(lst):
filtered_lst = filter(lambda x: 10 < x < 100, lst)
return sum(filtered_lst) / len(filtered_lst)
So you should use a for loop instead of a while loop. Instead of having two for loops and making a new list, you could just account for the sum inside the first for loop. I demonstrate this below.
def calcAvg(grade_list):
sum = 0;
count = 0;
for n in grade_list:
if 10 <= n <= 99:
sum = sum + n
count = count + 1
return sum/count
I think you should manually go over the code step by step and try to understand what is wrong. Meanwhile this may give you some hints
# Calculate average of all two-digit numbers (10-99)
def calcAvg(alist):
count=total=0
for i in alist:
if 9 < i < 100:
total += i
count += 1
return total/count
Since Python 3.4 there is a statistics module.
So you just need to filter out numbers in range <10,100), for example with a list comprehension, and then pass this filtered list to the mean function. Simple as that.
from statistics import mean
numbers = [1, 20, 30, 50]
mean([n for n in numbers if n >= 10 and n < 100])
>>> 33.333333333333336
You could do this fairly simply with a list comprehension
>>> grades = [1, 2, 10, 11, 12, 13, 14, 15, 120, 122, 320]
>>> lst = [v for v in grades if 10 <= v < 100]
>>> sum(lst)/len(lst)
12