Can you find the even number problem using with try / except? [closed] - python

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 didn't understand this thing:
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
n%2 == 0
print(n)
except:
pass
The output of the code above shows every number, but I need just even numbers.
What is my mistake?

I suspect you are missing a basic idea somewhere. try / except is used for catching errors. In order to use this in the way you are trying to, you need to cause an error under some condition. One easy way is to assert the number is even. assert n % 2 == 0 says if n is not even, raise an exception. Then you can catch the exception and skip it with a pass
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
assert n % 2 == 0 # cause an error if `n` is not even
print(n)
except AssertionError:
pass

You were missing a condition if
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
if n%2 == 0:
print(n)
except:
pass

Two things. You forgot an if statement before preforming n%2
Second thing is, what is the point of the try and except. You don't need it.
Below is an example of your code in
list comprehension.
list1 = [34,2,1,3,33,100,61,1800]
even = [n for n in list1 if n%2 == 0]
output
[34, 2, 100, 1800]
simplified code
list1 = [34,2,1,3,33,100,61,1800]
even = []
for n in list1:
if n%2 == 0:
even.append(n)
output
[34, 2, 100, 1800]

Related

random.choice() not selecting all possibilities [closed]

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
random.choice() in Python does not work correctly.
I have the following function, but the following happens when called:
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Randomswitch()
When Randomswitch is called it only returns WIN every time it's called.
I am breaking my head trying to figure this out.
Can anyone help me please?
Seems to be working pretty well, have you tried only a few times? Let's try 10,000 times and count the occurrences:
import random
from collections import Counter
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Counter(Randomswitch() for i in range(10000))
output:
Counter({'LOSE': 4980, 'WIN': 5020})
Seems pretty decent ;)
improving the code
That said, you code can be improved, why don't you just pass the values to chose from to random.choice?
def Randomswitch():
return random.choice(['WIN', 'LOSE'])
try this:
import random
def Randomswitch():
range_list = [i for i in range(0, 2)]
thechosenone = random.choice(range_list)
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Try use random.randint(0,1) instead of random.choice(range(0,2))

The first unique integer value in a list in Python [closed]

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

basic question about python for loop and enumerate [closed]

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

Issue with functions: SyntaxError: unexpected EOF while parsing [closed]

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
Just playing around on codewars and came across this problem: https://www.codewars.com/kata/5514e5b77e6b2f38e0000ca9/train/python
Now I built this function (in Sublime):
def up_array(arr):
is_valid = []
if len(arr) > 0:
is_valid.append(1)
else:
is_valid.append(0)
for x in arr:
if x < 0:
is_valid.append(0)
else:
is_valid.append(1)
if 0 not in is_valid:
arr = int(''.join(str(n) for n in arr))
arr += 1
arr = str(arr)
arr = [int(n) for n in arr]
return arr
else:
return None
print(up_array([4,3,2,5])
and I keep getting SyntaxError: unexpected EOF while parsing
BUT when I run the same code outside the function:
arr = [4,3,2,5]
is_valid = []
if len(arr) > 0:
is_valid.append(1)
else:
is_valid.append(0)
for x in arr:
if x < 0:
is_valid.append(0)
else:
is_valid.append(1)
if 0 not in is_valid:
arr = int(''.join(str(n) for n in arr))
arr += 1
arr = str(arr)
arr = [int(n) for n in arr]
print(arr)
else:
print(None)
The code runs great through various tests. Any thoughts as to what the issue with the function is?
I have tried re-tabbing & re-writing but when I put code inside a function. I started getting this parsing error.
I don't want to put too much time into the issue but it will linger in the back of my mind so any thoughts would be greatly appreciated!
SyntaxError: unexpected EOF while parsing error is caused because of missing parenthesis on last line print(up_array([4,3,2,5])
It should be like this:
print(up_array([4,3,2,5]))

Trying to average a list of numbers using functions [closed]

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

Categories

Resources