Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Why am I getting a MemoryError when my code is only 13 lines long? Could it be because I could potentially be getting a very long list?
I am trying to return a list of a sequence of numbers here (the list will be x and then the numbers obtained until 1). The sequence will be complete when the variable val reaches 1.
def sequence(x):
my_list = [x]
val = 0
while (val!= 1) and (x != 1):
if x % 2 == 0:
val = x / 2
my_list.append(val)
else:
val = 3 * x + 1
my_list.append(val)
return my_list
print(sequence(6))
This is the error message I'm getting:
Traceback (most recent call last):
File ******, line 12, in <module>
print(sequence(6))
File ******, line 7, in sequence
my_list.append(val)
MemoryError
How can I get rid of this error?
In your code, you are not manipulating x. So, x will always be 6.
And as x will always 6, your val will never be equal to 1 in both cases
val=x/2 #will result in val=3
And also
val=3*x+1 #will result in val=19
So, both conditions ( val != 1 ) and ( x != 1 ) will always True and your loop will not terminate at all.
This infinite loop goes on filling your list and eventually you will get memory error.
Hope you got it.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I'm getting the syntax error, that return is outside the func. I have rewritten the code but the problem persists. What am I doing wrong?
def prime_1(mn):
if mn < 2:
return 0
prime_in = [2]
x = 3
while x <= mn:
for y in prime_in:
if x % y == 0:
x += 2
break
else:
prime_in.append(x)
x += 2
print(prime_in)
return len(prime_in)
I'm voting to close this question, but since the edit queue is full...your issue is simply syntax. Format your code correctly and you are done:
def prime_1(mn):
if mn < 2:
return 0
prime_in = [2]
x = 3
while x <= mn:
for y in prime_in:
if x % y == 0:
x += 2
break
else:
prime_in.append(x)
x += 2
print(prime_in)
# returns in function now
return len(prime_in)
Check the indentation of your return statement. The first statement has too much whitespaces in front of it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want find the first unique number in a list, but I have a error.
My code:
s=[1,2,1,2,3,5]
mydict={}
for i in s:
if(i in mydict):
mydict[i]=mydict[i]+1
else:
mydict=1
for key in mydict:
if (mydict[key]==1):
print(key)
Error:
Traceback (most recent call last):
File "C:/Users/abdul_saboor/PycharmProjects/sleneiumpythonsession/Selenium sessions/firstuniquenumber.py", line 4, in <module>
if(i in mydict):
TypeError: argument of type 'int' is not iterable
You missed the [i] at line 7.
This is what propably what throws the error.
You could also make this faster with numpy.
mydict = {num: count for num, count in zip(np.unique(s))}
This is exactly what you want to do.
Then to find the first unique number you can do:
for num in s:
if mydict[num] == 1:
break
num is afterwards the first occuring unique number.
You can find the answer for your problem by looking for counting occurrences in lists.
Anyway, here are a couple ways for you to get it:
1 (using a For Loop)
# Stops at the first unique number
s = [1,2,1,2,3,5]
for n in s:
r = s.count(n)
if r == 1:
print(f'{n} is unique')
break
2 (using Comprehension List)
# Without stopping at the first unique
s = [1,2,1,2,3,5]
[ print(f'{n} is unique') for n in s if s.count(n) == 1 ]
3 (using Comprehension List)
# Stopping at the first unique number and exit the program
import sys
s = [1,2,1,2,3,5]
[ [ print(f'{n} is unique'), sys.exit() ] for n in s if s.count(n) == 1 ]
4 (the most elegant way)
# This doesn't stop the loop and doesn't exit the program
print(f'{[ n for n in s if s.count(n) == 1 ][0]} is unique')
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to build a function that will return the sum of the first item in the data list and every tenth item after, so I write the script below, however, the result is always the first data in my list. How should I modify my code and fix it?
def Sum10th(data):
sum=0
for i,d in enumerate(data):
if (i % 10 == 0): sum = sum+d
return sum
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(Sum10th(p))
The desired result should be 31, however the computer only returns the value of 1.
You can try
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def Sum10th(data):
return sum([v for i, v in enumerate(p) if (i + 1) % 10 == 0 or i == 0])
print(Sum10th(p))
Output
31
By using the list comprehension with an if, at the end of it, you can get all the first item with the tenth item following it from a list.
Try this way:
def sum10thdata(data):
sum = 0
l = len(data)
for i in range(0,l,10):
sum+=data[i]
return sum
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Building a stock data scraper for Finviz. I am using Spyder3 installed via Anaconda for Python 3.7.
My code is below. When I execute the x = 0, and then x = x+1 code line by line in the terminal, it works just fine. When I run entire script, I getthe same error if I use x += 1 or x = x + 1.
def finviz_query(tickerlist):
'''Get's source code from FinViz and Creates a List of Lists for Export '''
url="https://finviz.com/screener.ashx?v=140&t=" + str(stocks)
response = requests.get(url)
source=response.text
soup = bs4.BeautifulSoup(source)
priceLST = [i.get_text() for i in soup.find_all('a')]
del priceLST[0:37]
del priceLST[len(priceLST)-2:len(priceLST)]
stockLST = re.split(',',stocks)
stock_outputLST = []
while len(priceLST) > 0:
if priceLST[0] in stockLST:
stock_outputLST.append([priceLST[0:16]])
del priceLST[0:16]
if len(priceLST) < 1:
break
x = 0
while x < len(stock_outputLST):
if x < len(stock_outputLST):
stock_outputLST[x][0].append(time.strftime("%Y-%m-%d;%H:%M")
x = x + 1
else:
break
stock_outputLST[len(stock_outputLST)-1][0].append('0')
stock_outputLST[len(stock_outputLST)-1][0].append(time.strftime("%Y-%m-%d;%H:%M"))
The error output is here:
...:stock_outputLST[len(stock_outputLST)-1][0].append(time.strftime("%Y-%m-%d;%H:%M"))
...: return print('finviz_query complete')
File "<ipython-input-114-81b306b1a6de>", line 22
x = x + 1
^
SyntaxError: invalid syntax
Thanks in advance!
Whenever you get an error like this that doesn't quite make sense, look at the line above:
stock_outputLST[x][0].append(time.strftime("%Y-%m-%d;%H:%M")
You're missing a closing parenthesis ) at the end.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
First and foremost, I am new to python. As of such, I only know for loops, range, lens, and sum to do this problem. I am having difficulty trying to make a function that can average list of numbers.
This is my code so far:
def ave(L):
L = list(range(len(L))
for a in range(len(L)):
if len(L) == 0: return 0
else: return float((sum(L))/len(L))
So far, I am getting a syntax error on my third line with range(L).
All you need to do is return the sum of L divided by the length of L:
def ave(L):
if not L:
return 0
return sum(L) / len(L)
No range() or float() or for required.
In Python 3, / always produces a floating point number. sum() will do all the looping for you. The only thing you need to take care of, is returning 0 if the list is empty.
Following line is missing a ):
L = list(range(len(L)))
^
Because average of empty list is undefined, you should rather return None instead of '0'.
And instead checking for length, it is better to catch potential error, according to EAFP principle. It makes also more clear what are you doing, as error is self-descriptive.
def ave(L):
try:
return sum(L) / len(L)
except ZeroDivisionError:
return None