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
Related
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 4 months ago.
Improve this question
Hi i am new to python and i have a little problems with my code.
def Sumn(mylist):
i = 0
sum = 0
for i in mylist[1]:
sum += mylist[i]
return sum
i+=1
import myFunctions
mylist = [6, 12, 645, 3, -8]
print(myFunctions.Sumn(mylist))
I was expecting that the numbers from the list will add and then the anwser will get printed
Line by line comments:
def Sumn(mylist):
i = 0 # this variable is unused
sum = 0 # variable name overrides builtin 'sum' function
for i in mylist[1]: # this will error because mylist[1] is a single int
sum += mylist[i] # this only works if i is an index of mylist
return sum # returns in first iteration
i+=1 # this variable still isn't used for anything
A correct implementation might look like:
def Sumn(mylist):
total = 0
for i in mylist: # iterate over each value in mylist
total += i # add it to total
return total # return AFTER the entire loop is done
Of course in real life you would just call the builtin sum function:
mylist = [6, 12, 645, 3, -8]
print(sum(mylist)) # 658
There are some errors in your code. In for loop you should use list myList, but you are using element at index 1 of the list myList[1].
Also for loop iterates over elements not indices, so you should add i to the sum instead of myList[i].
Finally, return statement should be after the loop, not inside it. The last line i += 1 is after return so it does nothing (just remove it). Here is fixed code:
def Sumn(mylist):
list_sum = 0
for i in mylist:
list_sum += i
return list_sum
Btw. don't use variables names that are builtins (sum).
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 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
so my function needs to filter a list so that it returns a list of only the values that return a positive value when a function is applied to it without the use of any loops. My code is currently:
def positive_places(f, xs):
"""takes a function f and list xs and returns
a list of the values of xs which satisfy
f>0"""
y = list(map(f, xs))
x = filter(lambda i: i > 0, y)
return x
This currently returns a list of all the positive output values of the function, however I need their corresponding values from the original list xs.
Thanks for any help in advance!
Using a list comprehension:
return [x for x in xs if f(x) > 0]
Without using a list comprehension:
return filter(lambda x: f(x) > 0, xs)
Since you said it should return a list:
return list(filter(lambda x: f(x) > 0, xs))
Two solutions are possible using recursion, which do not use looping or comprehensions - which implement the iteration protocol internally.
Method 1:
lst = list()
def foo(index):
if index < 0 or index >= len(xs):
return
if f(xs[index]) > 0:
lst.append(xs[index])
# print xs[index] or do something else with the value
foo(index + 1)
# call foo with index = 0
Method 2:
lst = list()
def foo(xs):
if len(xs) <= 0:
return
if f(xs[0]) > 0:
lst.append(xs[0])
foo(xs[1:])
# call foo with xs
Both these methods create a new list consisting of the desired values. The second method uses list slicing, which I am not sure whether internally implements iteration protocol or not.
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))
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 need to create a python function that right shifts values in a list by a given value.
For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions.
This is what I have so far
def shift(array, value):
if value < 0:
return
for i in range(len(array)):
arr[i] = arr[(i + shift_amount) % len(arr)]
Usually you can do this with slicing
arr = arr[shift:] + arr[:shift]
Your shifted list is only shift = 1, not 2. You can't get your output by shifting 2 positions.
I make some modifications in your code (If you have to use len and range functions) :
def shift(array, shift_amount):
if shift_amount < 0:
return
ans = []
for i in range(len(array)):
ans.append(array[(i + shift_amount) % len(array)])
print ans
shift([1,2,3,4],2)
Output:
[3, 4, 1, 2]
Note:
Your's logic is correct but your overriding values in same array, So I created another list and append value to it.
If shift value is 1 then output will be [2, 3, 4, 1]. So for value 2 it will be two shifts that's why output should be [3, 4,
1, 2]
value and shift_amount are two different variables in your code, So I use only single variable.
You can use list comprehension (If you want to check in detail about list comprehension see this article Python List Comprehensions: Explained Visually) like
def shift(array, shift_amount):
if shift_amount < 0:
return
length = len(array)
print [array[(i + shift_amount) % length] for i in range(length)]
shift([1,2,3,4],0)