Issue with maps, for loops and list comprehensions - python

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)]))]

Related

minimum/max function (without built in functions!)

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)]

Write a function which squares a number and then use it to write a function which takes three integers and returns the sum of their squares

Im new to python and cant figure out how to get these functions to call themselves. It asks for an input but no matter what gives 0 as the output. Can someone help debug?
userinput = input("Enter three numbers: ")
userinput = userinput.split(',')
finalsum = 0
finaldata = []
def formatinput(x):
sqrdata = []
for element in x:
sqrdata.append(int(element))
return(sqrdata)
def findsquare(x):
return (x*x)
def sumthesquares(y):
for element in y:
temp = findsquare(element)
finaldata.append(int(temp))
finalsum = finalsum + temp
return finalsum
def findthesquares(userinput):
finalsum = sumthesquares(formatinput(userinput))
print(finalsum)
Have you actually tried running your code? From what you've posted, it looks like you never actually call your functions...
They're defined, but you're missing the actual calls, like formatinput(userinput).
For future reference, if you put something like print("Got here!") into your functions, you can test that they're being called.

Python - Create List from Recursive Loop

I'm trying to create a list from my recursive loop. I know it is able to produce the results I need since I've already checked that by printing the results.
Here's my recursive loop:
def move_forward_occurences(occurrences, firstListDt):
listingResults = []
for x in range(0, occurrences):
firstListDt = firstListDt + relativedelta(bdays=+2)
listingResults.extend(firstListDt)
return listingResults
Alternatively, the problem could be that I'm not checking it correctly:
if occurrences != 0:
listingResult = move_forward_occurences(occurrences, firstListDt)
for result in listingResult:
print(result)
An explanation of parameters if needed (they're pretty self explanatory already):
occurrences = number of times to produce result
firstListDt = start date
Thanks in advance!
Your return is overly indented. You want to defer the return until after the for loop has finished:
def move_forward_occurences(occurrences, firstListDt):
listingResults = []
for x in range(0, occurrences):
firstListDt = firstListDt + relativedelta(bdays=+2)
listingResults.extend(firstListDt)
return listingResults

My functions are not running

Working with random functions and doing 3 things with 3 different functions, the first gives me values from 1,10 randomly displayed in a list of 10 integers. The second gives me a list values 1,10 and squares them. Then last but not least the third singles out numbers that can be divided by three. The problem is my program is not running while on eclipse the program has no errors, yet my program terminates without printing anything. Please help me...
import random
def main():
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
if __name__ == '__main__':
main()
You are just calling main() not any of the functions nested inside main(),
Using if __name__ == '__main__': does not magically call all your functions.
If your main function was like:
def main():
squareint_()
div3()
rand10()
then you would be calling the other functions as it is, main does nothing or returns nothing.
As far as your methods go, squares.append(random.randint(0,10))**2 is not valid, you cannot use ** on a list method.
It needs to be inside the paren squares.append(random.randint(0,10)**2)
Also num is a list so you cannot use if num % 3 == 0:
You could use something like:
def div3():
divlist = []
num = range(1,10)
for n in num: # loop over the list elements
if n % 3 == 0:
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
There are two current problems with the code:
You're defining your functions inside main(), which is allowed but it's not very good coding practice. If you do this, then you can only ever use these functions from inside main().
You're not actually calling any of your functions, you're just defining them. They need to be called with rand10(), squareint_() or div3().
Try this bit of code instead, which fixes both issues:
import random
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
def main():
rand10()
squareint_()
div3()
if __name__ == '__main__':
main()
Of course, if your functions are invalid, then they will need to be fixed on their own. This just solves the issue of nothing happening when you execute your code. Now when you run the project in Eclipse, you'll see some errors and be able to fix them properly.

How to get the max value out of a random list of numbers Python

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]

Categories

Resources