I am trying to find the max and min of a list of random numbers without using any built in functions. I have this code, but its showing an invalid syntax error on the last line. Can someone help? Using spyder in python 3.7. Also I know that the random number list works, just the min code is not working.
import random
l = []
for i in range(0,50):
x = random.randint(1,10)
l.append(x)
print(l)
def minimum(list):
current_min = list[0]
for num in list:
if num < current_min:
current_min = num
return current_min
print minimum(l)
In python3, you should use print with parenthesis.
Change your last line to be print(minimum(l))
Assuming you are using python 3, then I expect the last line is returning an error because you are missing the brackets on the print statement, it should be
print (minimum(l))
On another note, you can also shorten the initialization of your list into a one-liner
l = [random.randint(1, 10) for x in range(50)]
Related
I'm just starting to learn python and I know what I'm asking is so basic but I'll get to it anyway ,
# adding an If statements grabbing the even numbers
evenNumber = [num for num in range(0,11) if num%2==0]
evenNumber
and now I'm trying to do it the organized way using a for loop but I'm missing something :
#adding an If statements grabbing the even numbers using for loop
evenNumber = []
for num in range(0,11):
evenNumber.append(num if num%2==0)
evenNumber
Appreciate the help and please don't mind my easy question :)
Just to point you to the error in your code, I have only rectified the part in your code which had the issue. Try this:
evenNumber = []
for num in range(0,11):
if num % 2 == 0:
evenNumber.append(num)
print(evenNumber)
However, the best way is to use list comprehension.
And you can use the third (optional) parameter of range(), i.e., step if you start your range with an even number and using a step of 2 ensures that you always get an even number.
evenNumber = [num for num in range(0,11,2)]
Or
Simply,
print(list(range(0,11,2)))
The range function has an optional 'step' Parameter, it defaults to 1 but you can change it to any number you want. e.g:
evenNumber = []
for num in range(0,11,2):
evenNumber.append(num)
print(evenNumber)
I want to get the result of multiplying all the numbers that are into a list, using a for loop written in a single line OR using a Lambda funtion
I've solved it easily using a classic for loop, but I want to simplify the expression. The idea is not to use libraries.
My current code:
num_list = [5,7,3,8]
R = 1;
for num in num_list:
R *= num
print(R)
>>> 840
What I've tried:
R=1
R = [R*=num for num in num_list ]
^
SyntaxError: invalid syntax
I expect to get the same value (=840) when simplify the expression
You could do this with reduce and operator:
from functools import reduce
import operator
num_list = [5,7,3,8]
reduce(operator.mul, num_list)
In Python 3.8 (to be released next year) see here:
Added new function, math.prod(), as analogous function to sum() that
returns the product of a ‘start’ value (default: 1) times an iterable
of numbers. (Contributed by Pablo Galindo in bpo-35606)
so you will be able to do math.prod(num_list)
I'm relatively new to python and I saw this code to check for an even number, specifically tasked to use one line of code when creating a list and sorting even numbers into it.
I'm used to seeing:
for item in list: # etc etc
But why is there another num, in front of the for loop here:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
even_numbers = [num for num in a if num % 2 is 0] # on this line
print(even_numbers)
This isn't actually a for loop, it's a list comprehension. That num in front of the for is the expression that gets used for each element in the new list.
[num for num in a if num % 2 is 0]
In Python this is known as a "list comprehension." Its a short hand way of implementing the following code:
even_numbers = []
for num in a:
if num % 2 == 0:
even_numbers.append(num)
In your simple case, it's a little hard to see why you would want the extra num in there. So let's imagine something slightly more interesting, that you have a list of numbers, positive and negative, and what you want to iterate over the is absolute value of the numbers in the list.
In that case, you could write:
absolutes = [abs(num) for num in a if num % 2 = 0]
That's also a pretty simple case, more typical might be:
names = [company.name for company in companies if company.state = search_state]
In other words, the items produced by the list comprehension do not need to be the same items, or type of items, found in the original list.
Here's another less obvious example. It produces a string of comma-separated question marks that you could use in building a parameterized SQL query using the IN operator:
qmarks = ','.join(['?' for param in param_list])
In this case, the item returned from the list comprehension isn't even derived from the item in the original list.
In a for loop you would say:
mylist = []
for num in a:
if num % 2 is 0:
mylist.append(num)
With the syntax you are seeing the num at the front is synonymous with the 4th line of code.
This syntax is actually a python list comprehension, but it does do something similar to the above for loop.
What is nice about this syntax is it lets you quickly/dynamically create/modify lists in a single line.
Another example that might help you understand why num is at the front is a simple line that converts a list of floats into a list of ints. Notice that in this example there is no if statement at the end and I have wrapped the output float in a int() cast.
floats_list = [1.1, 2.2, 3.3, 4.4, 5.5]
ints_list = [ int(float) for float in floats_list ]
The following line of code,
even_numbers = [num for num in a if num % 2 is 0]
is equivalent to:
even_numbers = []
for num in a:
if num % 2 == 0:
even_numbers.append(num)
So, this part - even_numbers.append(num), is equivalent to:
even_numbers = [num for ...]
So, the numbers num which are in list a and also divisible by 2 are added to the list even_numbers.
kn = input().split(" ")
n = int(kn[0])
k = int(kn[1])
niz = list(map(int, input().split(" ")))
newlis = []
def rad(o):
return sum(niz[num:(num+k+o)])/(k+o)
def posao(k):
return max(list(map(rad, range(0, n-k))))
for num in range(len(niz[0:(n-k+1)])):
newlis.append(max(list(map(rad, range(0, n-num)))))
#newlis = [max(list(map(rad, range(0, n-num)))) for num in range(len(niz[0:(n-k+1)]))]
print(max(newlis))
So I've got this working with a for loop and now I want to use the commented out list comprehension (or even map()) to make it faster. Problem is, it keeps returning that num is not defined when I use either. I'm completely aware the code is very messy and unclean, but if someone could tell me where I'm going wrong with this, I'd appreciate it. I'm only a beginner with python.
def rad(o):
return sum(niz[num:(num+k+o)])/(k+o) // I guess the problem should
// be here... as ^ num is not defined in this function and neither it is a global variable
Try passing num as argument
def rad(o,num):
return sum(niz[num:(num+k+o)])/(k+o)
newlis = [max([rad(x, num) for x in range(0, n-num)]) for num in range(len(niz[0:(n-k+1)]))]
I have this code I'm trying to get to work. I can create a set of random numbers, but I need to make the max value show up. I'm trying not to use python's built in max command, BUT, I will ask for an example if I can't find a solution.
import random
def randomNumbers(number):
myList = []
numbersToCreate = number
while numbersToCreate > 0:
randomNumber = int(random.random() * 100)
myList.append(randomNumber)
numbersToCreate = numbersToCreate -1
return myList
One piece of code I've tried to enter is this:
theList = []
theList.sort()
biggest = theList [-1:][0]
print (theList)
When I try to run that with it I get an error telling me the list isn't defined. Any help would be appreciated.
Here's a solution.
def randomNumbers(number):
theList = []
numbersToCreate = number
while numbersToCreate > 0:
randomNumber = int(random.random() * 100)
theList.append(randomNumber)
numbersToCreate -= 1
return theList
outList = randomNumbers(100)
outList.sort()
print outlist[-1] # No reason to slice the list, which is what you were doing.
You really should use the max() function of Python, at least for readability sake.
If not, you can always check how Python developers have implemented it in Python, since it is open source.
theList = randomNumbers(30)
biggest = max(theList)
print (biggest)
First of all, if you want int for your list, you can use random.randint(min, max) instead of int(random.random()*100).
Second, you need to call your function and pass the return list to theList
def randomNumberList(n):
theList = []
for i in range(n):
theList.append(random.randint(0,100))
return theList
theRealList = randomNumberList(n)
Then you will be able to use the actual list.
theRealList.sort()
theBiggest = theRealList[-1]