How to find even numbers in a string in Python - python

I tried to find even numbers in a string
s = "75,41,14,8,73,45,-16"
evenNumbers = []
for number in s.split(","):
if int(number) % 2 == 0 and int(number) > 0:
evenNumbers += number
evenNumbers = ','.join(evenNumbers)
print("Even Numbers : \"{}\"".format(evenNumbers))
and its output is like
Even Numbers : "1,4,8"
I want to make it like
Even Numbers : "14,8"

You can append the number to the list. Something like this:
s = "75,41,14,8,73,45,-16"
evenNumbers = []
for number in s.split(","):
if int(number) % 2 == 0 and int(number) > 0:
evenNumbers.append(number)
print("Even Numbers : \"{}\"".format(evenNumbers))
"['14', '8']"

You need to add numbers, not strings to the list
evenNumbers += int(number)
Then join strings
evenNumbers = ','.join(map(str, evenNumbers))
Otherwise, do evenNumbers.append(number)
Or do it all on one line
evenNumbers = ','.join(filter(lambda x: int(x) % 2 == 0 and int(x) > 0, "75,41,14,8,73,45,-16".split(",")))

You will take expected output with this. All you need to do to replace evenNumbers += number with evenNumbers.append(int_num).
s = "75,41,14,8,73,45,-16"
evenNumbers = []
for number in s.split(","):
int_num = int(number)
if int_num % 2 == 0 and int_num > 0:
evenNumbers.append(int_num)
print("Even Numbers : \"{}\"".format(evenNumbers))

you could also do a list comprehensions
even_numbers = [n for n in s.split(',') if int(n) % 2 == 0]

Related

The code is for returning the outlying even or odd number, everything works except for my numbers are returning with brackets, thanks

example of a problem would be [2,4,6,8,9]
the code should return 9, instead it returns [9]
def find_outlier(integers):
even, odd = 0, 0
outlier = []
for num in integers:
if num % 2 == 0:
even += 1
else:
odd +=1
if even > odd:
for num in integers:
if num % 2 != 0:
outlier.append(num)
return outlier
else:
if odd > even:
for num in integers:
if num % 2 == 0:
outlier.append(num)
return outlier
You are returning the list and printing the list. That's the reason
you can returning the num instead of the outlier list
def find_outlier(integers):
even, odd = 0, 0
outlier = []
for num in integers:
if num % 2 == 0:
even += 1
else:
odd +=1
if even > odd:
for num in integers:
if num % 2 != 0:
outlier.append(num)
return num
else:
if odd > even:
for num in integers:
if num % 2 == 0:
outlier.append(num)
return num
print(find_outlier([2,4,6,8,9]))
But still your code is fully mess. It's not gonna return more than one odd or even. I exactly don't know what you wanted to mean by this code. But this shortened code may help
def CheckEvenOrOdd(integers):
even, odd= 0,0
Evenlist=[]
OddList=[]
for num in integers:
if num % 2 == 0:
Evenlist.append(num)
even += 1
else:
OddList.append(num)
odd +=1
if even > odd:
return OddList
else:
return Evenlist
print(CheckEvenOrOdd([2,4,6,8,9,11]))
It's gonna return list so there is no problem with that

Binary to Decimal Number Converter

Today my professor asked us to do a binary converter using python, and I did it quickly with my friend assigning a variable to the length and decreasing it by 1 in the for loop. And then we decided to do it the opposite way.
We tried to do it converting the number into a list, reversing the list, using the index position to match the required exponent number. But we found 2 main problems with that code:
1.The exponent will never be able to be bigger than 1, because it's not in the list.
2.The number 1 and 0 are going to repeat a lot of times in the list, so there's gonna be a problem when we try to access the index value.
Is there any way to fix it or we should just stick to the other method? Here's the code so you can take a look:
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res) + 1
counter = 0
for x in range (0, length):
if res[x] == 1:
counter += res[x]**res.index(x)
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in decimal is : {counter}')
Your method is fine. Two errors in your code:
Do not add 1 to the length as it is already the correct value. If you have a, say, 8 digit binary number the range should be from 0 to 7.
You should simply add 2**x to the counter when the digit is 1. I don't know why you tried to use the .index()
Here is a working version:
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res)
counter = 0
for x in range(length):
if res[x] == 1:
counter += 2 ** x
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in binary is : {counter}')
...or a one-liner just for some Python fun:
print(sum(int(x) * 2**i for i, x in enumerate(reversed(num))))
For determining the correct value of the exponent you can use enumerated. Also, there is no point in converting the each digit to an integer, you can just compare the string.
num = input('Insert the binary number: ')
result = 0
for i, digit in enumerate(reversed(num)):
if digit == "1":
result += 2 ** i
elif digit != "0":
print('The number is not binary')
break
else:
print(f'Your number in decimal is : {result}')
Just a little fix and your program will work. Modified length = len(res), added enumerate to find index, and changed the counter formula.
num = input ('Insert the binary number: ')
res = [int(x) for x in num]
res.reverse()
length = len(res)
counter = 0
for index,x in enumerate(range(length)):
if res[x] == 1:
counter += res[x]* 2**index
elif res[x] == 0:
pass
else:
print ('The number is not binary')
break
print (f'Your number in decimal is : {counter}')

How to Add all elements of a python list

So basically I have a List inputed by the user, I check if all the elements are positive I output all positive, if they are all negative i output all negative, but if they are both pos and negative i need to sum them all up and I dont know how to do this last step, This is my code until now
stop = "0"
Numbers = []
number = ""
while number != stop:
number = input("enter a number ")
Numbers.append(number)
print(Numbers)
if all(int(element) >= 0 for element in Numbers):
print("allpos")
if all(int(element) <= 0 for element in Numbers):
print("all neg")
Use sum.
print(sum(numbers))
Also, use lowercase characters for variable names.
stop="0"
number =""
numbers=[]
while number != stop:
number = input("enter a number ")
numbers.append(int(number))
print(numbers)
if all(element > 0 for element in numbers):
print("allpos")
elif all(element < 0 for element in numbers):
print("all neg")
else:
print(sum(numbers))
Or clearer approach:
numbers = [int(x) for x in input("enter list of numbers, separated by space: ").split()]
print(numbers)
if all(element > 0 for element in numbers):
print("allpos")
elif all(element < 0 for element in numbers):
print("all neg")
else:
print(sum(numbers))
Refer to this:
list_ = [1, 2, -3]
if all(int(element) >= 0 for element in list_):
print("allpos")
elif all(int(element) <= 0 for element in list_):
print("all neg")
else:
print('sum', sum(list_))

REMOVING REPEATED NUMBER FROM LIST, not working

I have written this code to remove repeating numbers from the list and output the max number. However, it is not removing the number which is repeated on the 4th index value. please help.
array = input()
nums = (array.split())
num = [int(i) for i in nums]
n = 0
for j in num:
for q in num:
if q == j:
n += 1
if n > 1:
while j in num:
num.remove(j)
n = 0
print(num)
print(max(num))
pythons build in function set() does this for you.
_list = [1,2,3,4,5,6,7,8,9,1,2]
print(set(_list))
outputs:
[1,2,3,4,5,6,7,8,9]

Python: Create two lists from loop and sum both

I'm working on a credit project of CS50 and I have some problem with the verification of the credit card.
Here the function I create:
def main():
while True :
cardnumber = input("Please enter a credit card number: ")
if cardnumber.isdecimal() and int(cardnumber) > 0 :
break
count = len(cardnumber)
if count != 13 and count != 15 and count != 16:
print("INVALID")
else:
check(count, cardnumber)
def check(length, number):
lenght_max = 15
if length == 15 and int(number[0]) == 3 and (int(number[1]) == 4 or int(number[1]) == 7):
if validator(number):
print("AMEX")
elif length == 16 and int(number[0]) == 5 and int(number[1]) <= 5:
if validator(number):
print("MASTERCARD")
elif length == 16 or length == 13 and int(number[0]) == 4:
if validator(number):
print("VISA")
else:
print("INVALID")
return number
def validator(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)]
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(validator(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
return True
else:
print("INVALID")
main()
I found the way to print the evens and the odds(multiply also time 2) but now I have to sum booth and check if the remainder is 0
Here the complete instruction:
http://docs.cs50.net/problems/credit/credit.html
Write a helper function to sum your digits. You'll need to use it extensively.
def dig_sum(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
num = '378282246310005' # your credit card number
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)] # these two remain the same
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(dig_sum(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
print('Valid') #valid!
sum(dig_sum(x) for x in odd) will get the digit sum for each number in your odd list and sum(...) that finds the resultant sum.
Input:
'378282246310005'
Output:
Valid
A first problem with your function is that you do not store the even/odd digits somewhere: you construct a list with one element each time, and print that element.
Now since two times a digit, can only result in a two digit number, we can use:
def sum2(x):
return (2*x)//10 + (2*x)%10
You can construct a list of all the digits at odd index with:
odd = [int(number[i]) for i in range(1,length,2)]
The same for digits at even index:
even = [int(number[i]) for i in range(0,length,2)]
Now we can simply use the sum(..) builtin function to sum up the digits:
total = sum(sum2(oddi) for oddi in odd) + sum(even)
and check if it is a multiple of 10:
return total%10 == 0
Or putting it all together:
def validator(number, length):
odd = [int(number[i]) for i in range(1,length,2)]
even = [int(number[i]) for i in range(0,length,2)]
total = sum(sum2(oddi) for oddi in odd) + sum(even)
return total%10 == 0
Or we can use a the following one liner for experts:
from itertools import zip_longest
def validator(number,length):
numbi = iter(numbi)
return sum(x+sum2(y) for x,y in zip_longest(numbi,numbi,fillvalue=0))%10 == 0

Categories

Resources