I am trying to reuse the newly created list from the Fibonacci sequence, I want to be able to use the answer to iterate through and call just the even numbers.
I can do this on it's own but have no idea how to use the results of my current code.
Any help greatly appreciated. Thank You.
FibStart = int(raw_input('Enter a start number : '))
FibStop = int(raw_input('Enter a stop number : '))
def fib(n):
if n < 2:
return n
else:
return fib(n-2) + fib(n-1)
print map(fib, range(FibStart, FibStop))
# when called will return [0,1,1,2,3,5,8,13,21,34]
Just translate your English text into code:
I want to be able to use the answer
So store it in a variable:
answer = map(fib, range(FibStart, FibStop))
… to iterate through
So iterate through it:
for value in answer:
… and call just the even numbers.
So check if they're even:
if value % 2 == 0:
Or, if you want to make a new list of just the even values to use repeatedly, you can use a list comprehension:
evens = [value for value in answer if value % 2 == 0]
for even in evens:
Related
I'm trying to make a program that finds the perfect number.(Perfect number=The sum of its divisors except itself is a number equal to itself.)And I want to add one more thing. Firstly I want to define an empty list and put the perfect numbers in it.But When I run the programm I didn't take the right throughput.How can I solve this problem.
My cods
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total
perfect_number_set = []
for i in range(1,1001)
if perfect(i):
perfect_number_set += [perfect(i)]
print(perfect_number_set)
print(i)
The output of the codes I wrote
[True]
6
[True,True]
28
[True,True,True]
You have following issues in your code:
Your implementation of perfect method is incorrect. You need to return True/False if a number is perfect. You are returning the total which is not correct.
Missing colon : in the for loop
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total == number
perfect_number_list = []
for i in range(1,1001):
if perfect(i):
print(i)
perfect_number_list.append(i)
print(perfect_number_list)
There is a difference between set and a list in python. You have used a list.
Set contains only unique entries.
Best practice tip:
defining a list use :
list_name = list()
Better way of adding items to as list by using it's method
list_name.append(list_item_to_add)
Another thing is that returning a number and checking it in if without any condition is not readable. Change it to:
if perfect(i) != 0:
(Altho Yours implementation work, because python if treats 0 like False and any other value as True)
The positive_numbers function should return a list containing numbers that are non-negative (>=0).
However, currently, it returns only the [3] instead of a list of values.
I tried different ways to make this work I'm currently a beginner in python and I don't have anyone to ask that's why I'm sorry if this is too basic for you just want to learn and see my mistake
def positive_numbers(numbers):
for number in numbers:
result = []
result = result + [number]
if number < 0:
continue
return result
Expected: The function should return a list of numbers
Actual: returns list with the only value being 3
Error: The call positive_numbers([1, 2, 3]) should return [1, 2, 3], but it returned [3]
You reset the list each iteration of the loop because of result = [].
Try this:
def positive_numbers(numbers):
result = []
for number in numbers:
if number > 0:
result = result + [number]
return result
Also, debugging would make this very clear. Try to debug your code to get a better understanding of it.
You have to declare result outside of your for loop.
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result.append(number)
return result
As already stated, you are setting results no a new empty string at every iteration of your for loop. Also, the if statement does not make any change, since by the time is evaluated, the new number is appended to the result.
So the minimal working change is:
def positive_numbers(numbers):
result = []
for number in numbers:
if number 0:
continue
result = result + [number]
return result
Besides, note that you could use a list comprehension for that:
positive_numbers = [number for number in numbers if number >= 0]
Or using filter:
positive_numbers = list(filter(lambda num: num>=0, numbers))
Note that in the latter case, if you don't need your output to be a list but an iterable, you can remove the list(...) part
You have all of the pieces, just not necessarily in the right order. Here is an amended version:
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result = result + [number]
return result
With result = [] inside the for loop as you had it, you were emptying the result on each iteration. Then you were unconditionally adding the number to the list instead of checking if it is negative first. In this amended first, the loop skips to the next number if the current number is not non-negative.
I'm trying to write a function that takes the inputs and puts them into a list, then sorts the list, and finds the greatest number. I keep getting errors and I'm not really sure what's wrong. I'll post the current code that I have typed up already. Any help or advice would be greatly appreciated, thank you.
Code:
def findMax3():
y = list(lst)
y.sort(lst)
y[0] == y[-1]
lst = int(input())
print(findMax3())
You need to pass in a variable - lst maybe?
You need to return value if you want your main to print something.
You need a constant input format for integer arrays, I will suggest 1 2 3 4 5 (space separated), that can be reversed to list using map(int, input().split())
Use the built-in max.
Do you want to limit yourself to 3 number arrays? if yes, use assertion.
That should be enough:
def findMax3(lst):
assert len(lst) == 3
lst.sort()
return max(lst)
lst = map(int, input().split())
print(findMax3(lst))
This is the corrected code:
def findMax3(lst):
y = lst[:]
y.sort()
return y[-1]
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I'd say findMax() would be a better name as this could find the maximum of lists of any length.
Bear in mind the following does the same thing:
lst = [int(x) for x in input().split()]
print(max(lst))
Put the numbers in a list, then use max() function to get the maximum value in a list, like this:
#create an empty numbers list
lst=[]
#loop for getting input numbers
for i in range(1,4):
try:
#here we get the input number
my_new_number=int(raw_input("Please input the number "+str(i)+"/3 :\n"))
except:
#in case of it is not a number raise an alert
print "not regular integer number"
#here we check that number not exist
if my_new_number not in lst:
#add the current input number to the list
lst.append(my_new_number)
else:
print "the number",my_new_number,"already exist in this list"
#show the maximum number of the list
print "The maximum number is",max(lst)
You might be interested in typing your list items one by one instead of using split() function to split your input. Also, to retrieve your list max, you have already a built-in max() function that you can use:
>>> num_list = []
>>>
>>> for i in range(3):
... num = input("Enter number {}: ".format(i + 1))
... num_list.append(int(num))
...
Enter number 1: 3
Enter number 2: 6
Enter number 3: 2
>>>
>>> max_num = max(num_list)
>>> print(max_num)
6
First off, Ebe Isaac gave a good explanation and you should look at his solution and understand why it works.
There's a few issues with your code.
lst = int(input())
print(findMax3())
You're inputting a list of numbers that need to be separated by some non-numeric character, so you cannot use int() on your input value.
lst = [int(x) for x in input().split()]
should give you what you want (with default separator being blank space). To learn more about this format, see list comprehensions.
Next, you call findMax3() but this function does not return a value so it will not have anything to print (see below). Additionally, it would be better to send it your list as an argument, this will save you from another line copying it later (see below).
lst = input().split()
print(findMax3(lst))
Now for your function:
def findMax3():
y = list(lst)
You should probably send an argument (the inputted list) to the function. This argument can be renamed whatever you put in the parentheses after the name of the function. You are using y here so we can rewrite it as:
def findMax3(y):
and delete the y = list(lst) line.
y.sort(lst)
When using a method or function, it's a good idea to look up the documentation to identify what arguments it takes. You'll see that sort can take two arguments (key and reverse) neither are needed here so we can fix this line by changing it to:
y.sort()
The next line:
y[0] == y[-1]
is a Boolean expression and returns either True or False if the first element of the sorted list (y[0]) is equal to the last element of the sorted list (y[-1]). To be honest, I'm not really sure what you were trying to do here. Since the function is designed to find the max value of the list, it needs to return that value so we need to use return(). The max value will be the last of the list so you can do:
return(y[-1])
So if you want to keep the flow of your original code, it can work by changing it to:
def findMax3(y):
y.sort()
return(y[-1])
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I hope this helps. Best of luck.
As many have mentioned, you need to let your function know what list to find the max of. To do that, you need to put the name of the list in the parameter list of the function i.e. findMax3(lst).
Your function will still not work because you are not returning anything from it. You need to use the return keyword followed by what to return in order to have the function give you a response. For example, return 1 will return the value of 1 to anyone who called this function. Using that example, you need to decide what to return to the caller.
My version of findMax3 without any other function calls:
def findMax3(*args):
max3 = args[0]
for n in args[1:3]:
if n > max3:
max3 = n
return max3
This is pretty close to what the built in max function will do given those same 3 inputs
If you already have a list then you can simply use the max function to get the highest number among 3 numbers in the list.
lst = [5, 2, 9]
print(max(lst))
# output
9
Or I assume you have three different numbers as input and then you can pass them to your desired method to get the highest number.
# function to get max among 3 integers
find_max(x, y, z):
return max([x, y, z])
# take input
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
num3 = int(input("enter num3: "))
# call your function
print(find_max(num1, num2, num3))
If we do not want to use the built in function for solving the problem we could always follow the below simple approach.
Using max() to find maximum of numbers is already shown in above few solutions.
Posting a sample solution without use of max()
num1=51
num2=6
num3=72
def find_max(num1,num2,num3):
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
return largest
print(find_max(num1,num2,num3))
Title pretty much says it all. This is the code I wrote that I've been tinkering around with.
def sum_evens(tup):
for num in tup:
if num % 2 ==0:
total = num+num
print(total)
I'm pretty lost here, any ideas on what I can do?
Thank you in advance!
you need to start total at 0 and add to it when you find matching numbers
def sum_evens(tup):
total = 0
for num in tup:
if num % 2 ==0:
total = total+num
return total
finally you need to return the total to whatever called it so it can be used
there are lots of better ways to do this ... but I just edited your function to work
print sum_evens([1,2,3,4,5,6,7]) # 2+4+6 = 12
You need to learn about list comprehensions. Basically, they are backwards for loops such that you can define a new list by iterating over an old list. You can also add a conditional clause to pick and choose.
In this scenario, we loop through an existing tuple and look for the individual members with a remainder of zero when divided by two. We then construct a list with these members and find a sum.
print sum([x for x in my_tuple if x % 2 == 0])
I am new to Python and need some help writing a function that takes a list as an argument.
I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.
My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:
def sum(list):
It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.
Thanks in anticipation!
EDIT: I am looking for something like this (thanks, "irrenhaus"):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.
Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
The top three lines are kind of ugly. You can combine them:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
But that's kind of ugly too. How about:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
The for loop in Python is exceptionally easy to use. For your application, something like this works:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
Edit: Aye, I am slow. The other answer is probably way more helpful. ;)
This will work for python 3.x, It is similar to the Adam Smith solution
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
for my_sum([1, 2, [1, 2, [1, 2]]])
the output will be 9.
If you used standard buildin function sum for this task it would raise an TypeError.
This is a somewhat slow version but it works wonders
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
This should work nicely
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
print sumTo(15)
#outputs 120
If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper):
sumlist=0
for x in arr:
sumlist+=x
return sumlist
Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
Output:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33