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).
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
Question
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should precede B.
Example:
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
My code:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
dict={}
for i in A:
asum+=A[i]
if A[i] in dict:
x=A[i]
else:
dict[i]=1
diff=rsum-asum
return x,x+diff
Your error is simple, you're using for i in A: but you refer to i within the for loop as if you did for i in range(len(A)):. To fix this all you need to do is replace all instances of A[i] in your code with i. It should look something like this:
class Solution:
def repeatedNumber(self, A):
n=len(A)
asum=0
rsum = (n*(n+1))//2
x=0
distinct={}
for i in A:
asum+=i
if i in distinct:
x=i
else:
distinct[i]=1
diff=rsum-asum
return x,x+diff
Note: It doesn't have any functional relevance in this case, but it is generally go practice to name your variables something other than the object name. In this case I just renamed the dict variable to distinct, as it also gives readers a better understanding of what the dictionary is actually used for.
This could be a solution. It runs in O(2n)
my_list = [3, 1, 2, 5, 3]
new_list = []
length = len(my_list)
for x in range(1,length+1):
new_list.append(x)
for x in range(1,length+1):
try:
my_list.remove(x)
except:
missing_number = x
double_number = my_list[0]
print(missing_number)
print(double_number)
Basically, according to your input, you can use the fact that the max value inside the list is the max length. So you create a new list with all the possible values, scan your first list and removing the values from the second list. If you try to remove a value that doesn't exist in the list you got error (that's why the try, except) and at the end you get, in the original list, only the double value (as it has been removed just one time)
EDIT: actually, if you consider the execution time of .remove() function, the overall running time of the function is O(n+n^2)
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 1 year ago.
Improve this question
I'm trying to find the factors of 600851475143. my code isn't working.
def factor(a):
factor = []
for i in range (1, a+1):
if(a%i==0):
factor.append(i)
print(factor)
factor.clear()
factor(600851475143)
You can use return keyword to return a list of factors.
def factor(a):
factor = []
for i in range (1, a + 1):
if a % i == 0:
factor.append(i)
return factor
print(factor(int(input())))
Your code have some problems, first, the if statement in python don't use (), it should be only if a%i == 0:. Your code is not correctly indented, the code bellow the function is not part of it. You made a global variable with the same name as the function name, they overwrite each other.If you want the function to complete:
factorlist = []
def factor(a):
for i in range(1, a + 1):
if a % i == 0:
factorlist.append(i)
factor(input("Fators of: "))
print(factorlist)
factorlist.clear()
If you want to return the end list, use the #Ratery 's code.
First of all the indentation is not correct. You've to indent the inner code of the function correctly. It should come inside the defining statement. The next thing is, you're printing the factor list outside the function which is a local variable and not global variable. If you want to print it, add a print statement inside the function and then call the function. Your corrected code:
def factor(a):
factor_1= []
for i in range (1, a+1):
if(a%i==0):
factor_1.append(i)
print(factor_1)
factor(600851475143)
Also, don't keep your function name and the list name same. It might give error
Your function should return the list of factors (not print it). Because you are going through all potential divisors from 1 to a, it will take along time to produce a result with a very large number such as 600851475143.
To make this run faster, you can extract the factors in pairs so that you only have to look at divisors up to the square root of your number. Every time you find a factor (f) of the number (N), you know there is a corresponding factor which is the result of dividing N by f (N/f). This means that every factor <= √N has a corresponding one that is >= √N so you can get them in pairs and only check the divisors <= √N
def factors(N):
return [f for d in range(1,int(N**0.5)+1) if N%d==0 for f in {d,N//d}]
Output:
print(factor(600851475143))
[1, 600851475143, 8462696833, 71, 716151937, 839, 408464633, 1471,
6857, 87625999, 59569, 10086647, 104441, 5753023, 1234169, 486847]
This question already has answers here:
Understanding this Python code from 2014's new year challenge
(6 answers)
Generator expression evaluation with several ... for ... in ... parts
(2 answers)
Explain python list comprehension technique
(2 answers)
Closed 1 year ago.
def sum_five(l):
return sum(num for num in l if num > 5)
#desired outcome:
#sum_five([1, 5, 20, 30, 4, 9, 18]) ➞ 77
#sum_five([1, 2, 3, 4]) ➞ 0
#sum_five([10, 12, 28, 47, 55, 100]) ➞ 252
gotten this as a solution. The question is to loop through a list and sum up those that are less than 5. This is the cleanest and shortest answer which i really loved to learn. Can anyone explain in very simple English to me what does the num for num in l if num > 5 really means?
And give me more examples to understand that logic so i can next time apply it? PS: i can do the outcome using for loop and if statement already, i just want to learn how to use this one liner. Thanks.
This is known as Generator Expression which gives you another list which means like this:
FOR any element which we call it num, in the list which we call it l, if this element(num) is greater than 5, take it and put it in result list.
For example for [1,2,3,4] there is no number greater than 5, so the result is [] which has the summation equal to zero.
Another example is [1,5,20,30,4,9,18] which has the result equal to [20,30,9,18] which has the summation equal to 20+30+9+18 = 77
The list comprehension -- any list comprehension -- can be written as a for loop remembering that it returns a list (meaning you don't have to write the part that assigns the result to a list which in this case I've called out). That's a good thing because that list you are taking the sum of and returning that result instead.
out = []
def sum_five(l):
for num in l:
if num > 5:
out.append(num)
else:
continue
return sum(out)
The general form a list comprehension is worth going into more. But I'm going to strip out some of the code to this for clarity
for num in l:
if num > 5:
num
Goes to this:
for num in l if num > 5:
num
And then to this:
num for num in l if num > 5:
We don't need that colon at the end and the whole thing gets put in braces because that's what specifies a list is getting returned. That leaves us with:
[num for num in l if num > 5]
You then take the sum of that list:
sum([num for num in l if num > 5])
You'll notice the formatting is a bit different than for the loop. If it was just a long no one would use it.
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 5 years ago.
Improve this question
This seems like an embarrassingly easy concept but I can't understand why this for loop is working the way it is. The question is simply asking "Given a binary array, find the maximum number of consecutive 1s in this array."
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
My question is, why does this for loop work? I expected the loop to print out the total count of 1's.
It just doesn't work.
You can't expect to have the sum of all the 1s because when the loop find a zero it reset the counter (the "else" part).
However, your code doesn't do what it was expected to do, add a zero at the end of the list and you will easily see that the code fails.
To do what you asked, without changing your code too much, try this
def main(nums):
count = maxcount = 0
for num in nums:
if num == 1:
count+=1
else:
maxcount=max(maxcount, count)
count = 0
return maxcount
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1]))
Dave
The difference is that once it sees a zero, it sets the value of count back down to zero, saying that it's seen 0 consecutive ones. This code actually doesn't work—it only gets lucky on this input because the longest sequence is at the very end of the list.
A better practice would be to store both the lengths of the current_group of ones and the highest_total count.
It's probably hard to believe, but could it be that the reason you are wondering why this loop works at all is that you are not familiar with Python ability to iterate over all elements of a list, not needing any counter variable increasing its value?
[1,1,0,1,1,1,0,0,1,1,1,1,1]
is in Python a kind of array storing multiple number of values.
Here some "pseudo-code" for explanatory purpose only demonstrating that "for num in nums" means in Python (in terms of programming in other
languages which don't support iteration over elements of a list/array):
noOfValuesIn_nums = lengthOf/sizeOf(nums)
for i = 0 to noOfValuesIn_nums do:
# get i=th value from 'nums' and put it to a variable named 'num':
num = nums[i]
...
By the way: the loop provided in the question gives the desired result for the provided example:
main([1,1,0,1,1,1,0,0,1,1,1,1,1])
but won't work on another one as demonstrated here:
def main(nums):
count = 0
for num in nums:
if num == 1:
count+=1
else:
count = 0
return count
print( main([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# it prints 1 instead of 6
The task of finding the longest consecutive sequence of ones
solves following code:
def main1(nums):
count = 0
maxOnes = 0
for num in nums:
if num == 1:
count+=1
else:
if count > maxOnes:
maxOnes = count
count = 0
return maxOnes
print( main1([1,1,1,1,1,1,0,0,1,1,1,0,1]) )
# gives 6
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 7 years ago.
Improve this question
def gSubsets(L):
if len(L) == 0:
print '2'
return [[]]
smaller = gSubsets(L[:-1])
extra = L[-1:]
print L
new = []
for small in smaller:
new.append(small+extra)
return smaller+new
print gSubsets([1,2])
I am a beginner in python. I didn't get how actually the return at very last didn't end by getting:
smaller + new =[[][5]]
Break it down into pieces
def gSubsets(L): #recursive function
if len(L) == 0: #when weve reached the last subset we then have to handle an empty list
print '2'
return [[]] #returns a list of lists for the small in smaller
smaller = gSubsets(L[:-1]) #get subsets by recursive call for all elements in the list except the last one
extra = L[-1:] #get the last element in the list not used in this recursive call
print L
new = []
for small in smaller: #loop through list of lists from recursive call
new.append(small+extra) #append all combinations of the last element in the list to every other element in the same list to new
return smaller+new #return subset with new combinations
print gSubsets([1,2])
this outputs
>>> 2
>>> [1]
>>> [1, 2]
>>> [[], [1], [2], [1, 2]]
by the way, in python you should use underscores in your variable and function names (its the preferred syntax) and I would work on your variable names too.. you want them to be very specific so anyone else coming by can understand what it is right away.. this is how I would rename the variables.
def generate_subsets_from_list(input_list):
if len(input_list) == 0:
# print '2' -- not sure why you are printing 2 here?
return [[]]
subsets = generate_subsets_from_list(input_list[:-1])
last_element = L[-1:]
print L
return_list = []
for subset in subsets:
return_list.append(subset+last_element)
return subsets+return_list
initial_list = [1,2]
print generate_subsets_from_list(initial_list)