How to Add all elements of a python list - python

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

Related

Pyhton - trying to create a function that recives a positive number and checking if the number can be created from list numbers (in order)

so for example i have this list: [1,2,3,1,5,7,8,8,0]
i want to check if some integer number can be created from this list by the order of the list.
for example the integer 12358 will print TRUE but the integer 315782 will print False.
i got stuck, thats what i did but i just dont know how to continue
lst = [1,2,3,1,5,7,8,8,0]
lst_lenght = len(lst)
num1 = 0
num2 = 0
index = 0
max_index = 0
flag = True
while (flag == True):
num = int(input('\nEnter Positive integer (0 to stop):'))
num1 = num
num2 = num
if (num <= 0):
print('Finish')
flag = False
else:
for i in range (lst_lenght):
i just dont know how to continue, i've tried to get the last digit every time and to test if the index is higher then the next digits index (num % 10 , num // 10) but i struggle
I would convert everything to a string and then use some built-in methods:
def check(lst, n):
lst = ''.join(map(str, lst))
n = str(n)
pos = 0
for ch in lst:
if pos < len(n) and ch == n[pos]:
pos += 1
return pos == len(n)
Another very smart option using iterators:
def check(lst, n):
lst = ''.join(map(str, lst))
n = str(n)
it = iter(lst)
return all(x in it for x in n)
Examples:
>>> check([1,2,3,1,5,7,8,8,0], 12358)
True
>>> check([1,2,3,1,5,7,8,8,0], 315782)
False
You could convert the integer to a string, then to a list. Then for each element in the new list, check if it is in the number list. If it is, remove the element from both lists, removing just the element in the input number, and removing the element and every element before it on the list. Repeat for every element in the list. If the length of the input string at the end is 0, then you can construct the list
How about taking your input value (num), and converting it into a list of digits? For example, making the number '123' into an array, [1,2,3]. Then check the first member of the array, 1, to see if its in your list '1st'? If it isn't, you fail. If it is, you take note of where in the list '1st' the number one is found, and then search from that index number, in '1st' to the end of '1st' for the second digit. And repeat? If you get to the end of '1st', before you get to the end of the [1,2,3] array, you fail. If you get to the end of the [1,2,3] array before (or equal to) when you arrive at the end of the '1st' array.. you succeed!
I think this code helps you.
lst = [1,2,3,1,5,7,8,8,0]
def check(num):
try:
letter_index = [lst.index(int(a)) for a in str(num)]
except ValueError: # if value not in list return False
return False
result = False
greater = letter_index[0]
for i in letter_index:
if i>=greater:
lesser= i
result =True
else:
return False
return result
num = int(input('\nEnter Positive integer (0 to stop):'))
if check(num):
print('True')
else:
print("False")
You can convert your list into string then find substring in that string like that:
lst = [1,2,3,1,5,7,8,8,0]
list_as_string = ''.join(str(e) for e in lst)
lst_lenght = len(lst)
num1 = 0
num2 = 0
index = 0
max_index = 0
flag = True
while (flag == True):
num = int(input('\nEnter Positive integer (0 to stop):'))
num1 = num
num2 = num
if (num <= 0):
print('Finish')
flag = False
else:
checking_number = input(f"Enter {lst_lenght} number: ")
if len(checking_number) == lst_lenght:
if checking_number in list_as_string:
print(True)
else:
print(False)
else:
print(f"Wrong length: Please! Enter {lst_lenght} number: ")
A couple of other options (besides the already great answers):
Compare lists:
You convert your string number to a list and then check if it's in your starting list of numbers. As they are found, you pop the value from the starting list into a new list. Then check your new list at the end to see if it matches your input string:
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
outlist = []
for num in list(yournumber):
print(num)
if int(num) in yourlist:
outlist.append(str(yourlist.pop(yourlist.index(int(num)))))
print("".join(outlist) == yournumber)
>>>True
You may recognize the pattern (for: if: somelist.append()) that can be converted to list comprehension to shorten your code:
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
outlist = [str(yourlist.pop(yourlist.index(int(x)))) for x in list(yournumber) if int(x) in yourlist]
print("".join(outlist) == yournumber)
>>>True
Use Regex:
Another option here is to use regex. You can split your input string into a list, and then join it back together using .* as a delimiter. Then perform a regex match:
import re
yourlist = [1,2,3,1,5,7,8,8,0]
yournumber = '12358'
#turn `yournumber` into "1.*2.*3.*5.*8" regex string
rex=".*".join(list(yournumber))
#join your starting list into a string and test it with the regex:
print(bool(re.match(rex, "".join(map(str, yourlist)))))
>>>True
Note that if your list elements are more than a single digit or character this can fail:
yourlist = [10, 23, 5, 8]
yournumber = '12358'
This will say "True" even though "10" isn't in the yournumber variable.

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 an element in list using for loop and also without using append and also ask the position in which the number should be added

i somehow used it in for loop to add an element using the user inputed position but i somehow get the last element of the list get deleted,
list1 = [int(item) for item in input("Enter the list(leave space for an element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter the number that should be inserted: "))
pos = int(input("Enter the position of that number should be inserted: "))
for i in range(n-1):
if(pos - 1 == i):
for j in range(n-1, i-1, -1):
list1[j]=list1[j - 1]
list1[i]=add
n += 1
print(list1)
can you guys please help me identify the problem
list1 = [int(item) for item in input("Enter the list (leave space between each element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter number to be inserted: "))
pos = int(input("Enter position to be inserted: "))
pos = pos -1
for i in range(n):
if(pos == i):
list1.insert(pos,add)
print(list1)

How to find even numbers in a string in 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]

finding emrips with python, what am i doing wrong?

An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)

Categories

Resources