Making a for loop print with an index - python

I made a program which displays a user-provided number of the fibonacci series. I wanted to format it into an indexed list, but I don't what could I use to do so. I found the enumerate() function, but seems it only works for premade lists, whereas mine is generated accordingly to the user.
Do I use a for loop to generate a variable along with the series, then put the variable in the for loop that prints the numbers, like so:
print("{0}. {1}".format(index_variable, wee(n)))
or am I going an entirely wrong road here?

def fib(n):
x = 0
y = 1
for i in range(n):
yield y
tmp = x
x = y
y += tmp
def main():
n = input('How many do you want: ')
for i, f in enumerate(fib(n)):
print("{0}. {1}".format(i, f)
Make a generator that yields the values you want and then pass that to enumerate

Related

Output the index of an item in a set in Python/Sage

This is what I have so far.
def f(n):
my_list=[]
while n not in my_list:
my_list.append(n)
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
my_list.append(n)
return my_list
The above code takes any input n and outputs a list e.g. f(2) -> [2, 1, 4, 2]
Now I want to look at any range and output just the highest element in said list.
def f_2(i):
for i in range (1,101):
set_f = set(f(i))
print(max(set_f))
So I converted the list to a set and applied the max command to it. All of this has worked as I had intended it so far.
My problem is with the following issue:
I want to output all the indexes of all the highest Elements in all generated lists.
E.g. for i in range (1,101): The highest Element is 9232. I tried doing it in the above way, but a set does not have any indexes. However max() does not seem to work on a list of generated lists.
My try was:
def f_3(i):
for i in range (1,101):
set_f = set(f(i))
if max(set_f) == 9232:
print(set_f.index(9232))
else:
pass
Here I get the error that set has no index attribute.
def f_3(i):
for i in range (1,101):
if max(f(i)) == 9232:
print(f.index(9232))
else:
pass
Here I get the error that function has no index attribute.
Only the range of 1 to 100 is of interest to me. So I can use 9232 as a value.
Any help would be greatly appreciated, I feel a bit stuck on this one.
There's several things to unpack here, and I feel like the Code Review community would be a better fit.
First of all, why does f_2 have the parameter i? You're just using the i from the loop.
Second, why are you converting the list into a set at all? max works just fine on lists too.
set doesn't support indexing, and that's why you were getting that mistake.
At the other attempt with f_3, you've called index on the function f instead of f(i).
Function f_2 can be rewritten as such.
def f_2():
for i in range (1,101):
lst = f(i)
mx = max(lst)
print(lst.index(mx))
Function f_3 is inefficient, but it too can be fixed like this:
def f_3():
for i in range (1,101):
if max(f(i)) == 9232:
print(f(i).index(9232))

A function that calculates the average of a list and returns the elements that are greater than the mathematical average of the entire list

I'm trying to make a function that would calculate the average of a given list then returns all the elements within that list which are greater than the mathematical average of that list. Example:
if the given list is [1,2,3,4,5,6], the average would be 3.5. So the function should print out the numbers (4,5,6).
I've gotten as far as adding all the numbers up within the list but no matter what I do, I can't figure out how to get the average or get it to print out the numbers that are greater than the mathematical average.
This is what i have so far to add all the elements of any given list:
def accum2(seq):
total = 0
for x in seq:
total += x
return total
print (accum2([1,2,3,4,5,6]))
The expected result of print (accum2([1,2,3,4,5,6])) should be (4,5,6) but so far I just get an answer where it just adds up all the number in the given list.
Any help is greatly appreciated and thank you in advance.
The simplest way to get the average value of a list of numeric values is to use the methods:
average = sum(seq) / len(seq)
From there just use a conditional statement (you might have to sort the list first, if it is unsorted). From there you should be able to build a new list using the built in list methods.
heres some simple code which should work.
I have added comments.
originallist = [1,2,3,4,5,6] #This is your original list
outputlist = [] #This is the list which you can add correct values to
x = sum(originallist) / len(originallist) #This effectively finds you the average
for item in originallist: #Checks which items are greater than average
if item > x:
outputlist.append(item) #If greater, add to the final list
print(outputlist)
There are many correct ways to do this, one of which is shown below (Python 3).
lst = [1,2,3,4,5,6]
avg = sum(lst)/len(lst)
res = list(filter(lambda x: x > avg, lst))
print(res)
will produce
[4,5,6].
I prefer this approach because it's less verbose than loops and also can be more easily translated to a framework like Pandas or an eventual parallel implementation if such a need arises in the future (e.g., using Spark).
This is the extended version of your work:
def accum2(seq):
total = 0
for x in seq:
total += x
L=[]
for x in seq:
if x>total/len(seq):
L.append(x)
return L
print (accum2([1,2,3,4,5,6]))
But you could simply the previous one in this code:
def accum2(seq):
return [x for x in seq if x>(sum(y for y in seq)/len(seq))]
print (accum2([1,2,3,4,5,6]))

Python While Loop Square

I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.

My way of finding the sum of all the multiples of 3 or 5 below 1000

I want to find multiples of 3 or 5 below 1000 using the code below:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(330):
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330):
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(a) + sum(b)
Result- 262355
Result is not right. It should be 233168 . How am I going wrong with the logic here?
You are looping over the wrong ranges and adding multiples of 15 twice.
I believe that this is the smallest change to your program that makes it work:
a=[]
b=[]
def multiples_of_3():
i=1
for i in range(334): # stops at 1 less than the value passed to `range`
m=i*3
if(m<1000):
a.append(m)
def multiples_of_5():
j=1
for j in range(330): # could change to 201 and still work
k=j*5
if(k<1000):
b.append(k)
if __name__ == "__main__":
multiples_of_3()
multiples_of_5()
print sum(set(a+b))
But you should probably rethink your approach. Using global variables is generally a bad idea - looking at the call multiples_of_3(), there is no way to know what the subroutine is doing with those multiples; the variable a is not referenced anywhere, yet before the line and after the line it has two different values. So for starters, I would turn the subroutines into pure functions - have them return the arrays instead of modifying globals.
As minor stylistic points, you also don't need to use different variable names inside the two functions, since they're all local. You don't need to assign anything to i before the loops (the loop will create the variable for you), and you don't need parentheses around the condition in Python's if statement (the colon takes care of delimiting it):
def multiples_of_3():
a = []
for i in range(334):
m = i * 3
if m < 1000:
a.append(m)
return a
def multiples_of_5():
a = []
for i in range(201):
m = i * 5
if m < 1000:
a.append(m)
return a
if __name__ == "__main__":
a = multiples_of_3()
b = multiples_of_5()
print sum(set(a+b))
You could also combine the two multiples_of functions into a single generic one that takes a parameter telling it what to return multiples of:
def multiples_of(k):
result = []
for i in range(1000/k+1):
multiple = i * k
if multiple < 1000:
result.append(multiple)
return result
You could even turn the maximum value into an optional parameter:
def multiples_of(k, under=1000):
result = []
for i in range(under/k+1):
multiple = i * k
if multiple < under:
result.append(multiple)
return result
Either way, your main part becomes this:
a = multiples_of(3)
b = multiples_of(5)
print sum(set(a+b))
Finally, just as a point of reference, it is possible to do the whole thing as a one-liner. Here I've switched from building up the list of multiples by actually doing the multiplication, to just looping over all the numbers under 1000 and testing them for divisibility by either 3 or 5:
print sum([n for n in range(1000) if n%3==0 or n%5==0])
Shouldn't for j in range(330): be for j in range(200): since you're using multiples of 5?

Print the integers from 1 up to n (given number)

so if the function is:
function(n)
what can i do to if i want.
function(5)
to return as
1
2
3
4
5
I'm thinking towards creating an empty list, but i don't know what to append into the list to get the number 1 up to 'n'
You can try
def function(n):
for x in range(0, n):
print x+1
if you want to print the values, or
def function(n):
returnlist = []
for x in range(0, n):
returnlist.append(x+1)
return returnlist
to return a list.
The for x in range(0, n): part of the code is called a for loop. It repeats itself n times, and x is incremented by one each time is repeats. You can then use x to accomplish different tasks within your code. In this case, we're simply taking its value plus one and printing it or appending it to a list. We have to add one to the value because x is zero based, although it doesn't have to be. We could just as easily have written for x in range(1, n+1): and not have had to add one to the x value.
Here is a simple example:
def function(n):
for i in range(1, n+1):
print i

Categories

Resources