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 3 years ago.
Improve this question
Since I am new to the python, someone please help me with this problem
here are the few examples how it should work:
input: l([1,4,9])
result=14
input: l(10,11,12,15)
result= 0
According to your question, you can declare a function is_square(n) to check a number whether perfect square or not.
Then, you take a number (i.e. val) from list l using this for val in l:. If number (i.e. val) is perfect square then it will add to the sm otherwise not.
You code will be like following code :
l = [1,4,9]
def is_square(n): # function for checking a number whether perfect square or not.
return n**0.5 == int(n**0.5)
sm = 0
for val in l:
if is_square(val): # if number is perfect square then it will add to the sm otherwise not.
sm += val
print(sm)
If I understood your question right, you are asking how to write a function to loop through all the values in a list, sum the numbers that are perfect squares, and ignore the others.
Here is my code with comments explaining what is going on.
# We need to use the math module in this program.
import math
# Function declaration
def sumSquares(numbers):
# Start by defining the sum as 0
sum = 0
# Loop through each number in the list
for num in numbers:
# Check if number is a square by:
# 1. Taking the integer square root of that number
# 2. Squaring it
# 3. And checking if that is equal to the original number
if num == int(math.sqrt(num)) ** 2:
# If it is a perfect square, add it to the total sum.
sum += num
You can call this function like:
sumSquares([1, 4, 9, 30])
Try this:
list = [4,9,55]
sq = []
for i in list:
if i**0.5 == int(i**0.5):
sq.append(i)
sum = 0
for i in sq:
sum = sum + i
Try This:
import math
a=map(int,input().split())
sum1=0
for i in a:
b=math.sqrt(i)
if math.ceil(b)==math.floor(b):
sum1+=i
print (int(sum1))
Related
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 days ago.
Improve this question
Write a program in Python that exercises the functional higher order functions via Python list comprehensions to determine if a number is perfect or not. Write a function named perfect(num) that returns true/false if the given number is/is not perfect.
Use the built in Python function called range(n) that returns a list of integers between 0 and n-1 inclusive.
Use map implemented as a Python List Comprehension to add one to each element of the list.
Use filter implemented as a Python List Comprehension to generate a list of proper factors of n.
Use the Python reduce to generate a sum of those factors
Not more than 4-5 lines of code
def is_perfect(num):
sum = 0
for x in range(0, num-1):
if num % x == 0:
sum += x
return sum == num
print(Is_perfect(28))
Here you go:
def is_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
if sum == num:
return True
else:
return False
Now to test it:
x = 8
print(is_perfect(x))
This returns False.
x = 28
print(is_perfect(x))
This returns True.
Some correction in your code
You calling not a correct function name Is_perfect(),
There is also error of modulo by zero,
As written you would inclusive (n-1) in your for loop it is running till (n-2) not till (n-1),
Code:
from functools import reduce
def is_perfect(num):
# List comprehension which store all the number which can be divisible.
list_comprehension = [x for x in range(0, num) if x == 0 or num % x == 0]
print(list_comprehension)
# [0, 1, 2, 4, 7, 14] for number 28
# [0, 1, 2, 4] for number 8
# sum of list using reduce.
sum_of_divisible_numbers = reduce(lambda x, y: x + y, list_comprehension)
return sum_of_divisible_numbers == num
print(is_perfect(28)) # True
print(is_perfect(8)) # False
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 10 months ago.
Improve this question
I have this problem and I'm not sure about the solution:
Given an integer array A, calculate the length of its longest odd-even increasing subsequence (LOEIS), that is the length of the longest sequence S of elements in A such that all elements of S are odd or even.
For instance, given: A=[3,9,4,8,6,13,10,26,16,18], because the longest even sequence is made of 5 elements: [4,6,10,16,18] we have LOEIS(A)=5.
How to code such a function?
Thank you!
Here a solution from https://www.geeksforgeeks.org/python-program-for-longest-increasing-subsequence/ that I've adapted to you issue:
import matplotlib.pyplot as plt
import numpy as np
# A naive Python implementation of LIS problem
""" To make use of recursive calls, this function must return
two things:
1) Length of LIS ending with element arr[n-1]. We use
max_ending_here for this purpose
2) Overall maximum as the LIS may end with an element
before arr[n-1] max_ref is used this purpose.
The value of LIS of full array of size n is stored
in * max_ref which is our final result """
# global variable to store the maximum
global maximum
def _lis(arr, n):
# to allow the access of global variable
global maximum
# Base Case
if n == 1:
return 1
# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1
"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is smaller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""
for i in range(1, n):
res = _lis(arr, i)
if arr[i - 1] < arr[n - 1] and res + 1 > maxEndingHere:
maxEndingHere = res + 1
# Compare maxEndingHere with overall maximum. And
# update the overall maximum if needed
maximum = max(maximum, maxEndingHere)
return maxEndingHere
def lis(arr):
# to allow the access of global variable
global maximum
# length of arr
n = len(arr)
# maximum variable holds the result
maximum = 1
# The function _lis() stores its result in maximum
_lis(arr, n)
return maximum
A=np.array([3,9,4,8,6,13,10,26,16,18])
Even = A[A%2==0]
Odd = A[A%2==1]
print(Even,Odd)
print("Length of lis for Even is", lis(Even))
print("Length of lis for Odd is", lis(Odd))
Length of lis for Even is 5
Length of lis for Odd is 3
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to find the factors of 600851475143. my code isn't working.
def factor(a):
factor = []
for i in range (1, a+1):
if(a%i==0):
factor.append(i)
print(factor)
factor.clear()
factor(600851475143)
You can use return keyword to return a list of factors.
def factor(a):
factor = []
for i in range (1, a + 1):
if a % i == 0:
factor.append(i)
return factor
print(factor(int(input())))
Your code have some problems, first, the if statement in python don't use (), it should be only if a%i == 0:. Your code is not correctly indented, the code bellow the function is not part of it. You made a global variable with the same name as the function name, they overwrite each other.If you want the function to complete:
factorlist = []
def factor(a):
for i in range(1, a + 1):
if a % i == 0:
factorlist.append(i)
factor(input("Fators of: "))
print(factorlist)
factorlist.clear()
If you want to return the end list, use the #Ratery 's code.
First of all the indentation is not correct. You've to indent the inner code of the function correctly. It should come inside the defining statement. The next thing is, you're printing the factor list outside the function which is a local variable and not global variable. If you want to print it, add a print statement inside the function and then call the function. Your corrected code:
def factor(a):
factor_1= []
for i in range (1, a+1):
if(a%i==0):
factor_1.append(i)
print(factor_1)
factor(600851475143)
Also, don't keep your function name and the list name same. It might give error
Your function should return the list of factors (not print it). Because you are going through all potential divisors from 1 to a, it will take along time to produce a result with a very large number such as 600851475143.
To make this run faster, you can extract the factors in pairs so that you only have to look at divisors up to the square root of your number. Every time you find a factor (f) of the number (N), you know there is a corresponding factor which is the result of dividing N by f (N/f). This means that every factor <= √N has a corresponding one that is >= √N so you can get them in pairs and only check the divisors <= √N
def factors(N):
return [f for d in range(1,int(N**0.5)+1) if N%d==0 for f in {d,N//d}]
Output:
print(factor(600851475143))
[1, 600851475143, 8462696833, 71, 716151937, 839, 408464633, 1471,
6857, 87625999, 59569, 10086647, 104441, 5753023, 1234169, 486847]
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 5 years ago.
Improve this question
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
My question is, why does this for loop work? I expected the loop to print out the total count of 1's.
It just doesn't work.
You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).
However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.
To do what you asked, without changing your code too much, try this
def main(nums):
count = maxcount = 0
for num in nums:
if num == 1:
count+=1
else:
maxcount=max(maxcount, count)
count = 0
return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
Dave
The difference is that once it sees a zero, it sets the value of count back down to zero, saying that it's seen 0 consecutive ones. This code actually doesn't work—it only gets lucky on this input because the longest sequence is at the very end of the list.
A better practice would be to store both the lengths of the current_group of ones and the highest_total count.
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?
[1,1,0,1,1,1,0,0,1,1,1,1,1]
is in Python a kind of array storing multiple number of values.
Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):
noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
# get i=th value from 'nums' and put it to a variable named 'num':
num = nums[i]
...
By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
return count
print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
The task of finding the longest consecutive sequence of ones
solves following code:
def main1(nums):
count = 0
maxOnes = 0
for num in nums:
if num == 1:
count+=1
else:
if count > maxOnes:
maxOnes = count
count = 0
return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6
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