removing numbers form list by python - python

Take 5 integer input from the user.
Remove all numbers less than 9.
Calculate the sum of remaining numbers
python
n = int(input("Enter number of elements : "))
a = list(map(int,input("\nEnter the numbers : "). strip(). split()))
for i in range(len(a)):
if a[i]>9:
a.remove(a[i])
b=sum(a)
print(b)

When you remove from same list, of course the index will be out of range items from list,
BUT you really don't need to remove those items from list, just don't include them in your sum calculation:
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
b = sum([num for num in a if num<= 9])
print(b)

You can use this if you want to remove numbers less than 10 from the list and Calculate the sum of the remaining numbers
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
if len(a) == n:
for num in a:
if num < 9:
a.remove(num)
print('sum',sum(a))
else:
print(f"You must enter {n} number")

Related

a python program that gets a number from a user and sums its characters except for two particular number

for example, the given number is 4211256: I want to sum all the digits without adding 11; the result of the given number addition will be: 19
I wrote the first part of the program code but I couldn't continue it
n=int(input("Enter number: "))
sum=0
for digit in str(n):
sum=sum+int(digit)
while 11:
pass
print("Sum of digits",sum)
Try this:
n = input("Enter number: ")
result = sum(map(int, list(n.replace('11', ''))))
You get rid of '11' by replacing '11' with '' (there's no need to convert n to an integer and then back to a string), and then you sum the remaining digits.
Try this option and calculate the sums in parts:
def get_sum_without_11(s):
s_without11 = s.split("11")
return sum([getSum(n) for n in s_without11])
def get_sum(n):
sum = 0
for digit in str(n):
sum += int(digit)
return sum
n=int(input("Enter number: "))
print(get_sum_without_11(s))

python: How can I print an alphabet from a list, given a number?

Given a number from 1 to 26, I'm trying to return an alphabet in the corresponding position from a list.
Example:
Input = 1
Output = 'a'
I have tried the following:
user_input = int(input("Enter a number from 1 to 26 "))
for item in aplhabet:
print(aplhabet.index(item[aplhabet]))
As expected that returns a type error because there are no integer values in my list.
What can I do to return an element from my list in which its position is equal to the users number input?
Using ASCII conversion from integer to character, you can do it as follows,
n = int(input("Enter the number: "))
if(n > 0 and n < 27):
print(chr(n + 96))
else:
print("Invalid input")
You can index a list by its index:
import string
alphabet = list(string.ascii_lowercase)
user_input = int(input("Enter a number from 1 to 26 "))
if 0 < user_input <= 26:
print(alphabet[user_input - 1])
else:
print("please input a number between 1 and 26")
You can use indexing:
alphabets = 'abcdefghijklmnopqrstuvwxyz'
user_input = int(input("Enter a number from 1 to 26: "))
print(alphabets[user_input - 1])
Note that you need to subtract 1, since Python uses 0-based index.
There are 3 answers. All of them are perfectly working. The answers are already given in ASCII values and string. You can do it another way. Create a dictionary of number key and it's corresponding alphabet as value. Take the input. Print the value of of the input present in the dictionary. Your code:
d={1:"a",2:"b",3:"c",4:"d",5:"e",6:"f",7:"g",8:"h",9:"i",10:"j",11:"k",12:"l",13:"m",14:"n",15:"o",16:"p",17:"q",18:"r",19:"s",20:"t",21:"u",22:"v",23:"w",24:"x",25:"y",26:"z"}
x=int(input("Enter a number between 1 and 26= "))
print(d[x])
List1=['a' ,'b' ,'c' ,'d' ,'e' ,'f' ,'g' ,'h' ,'i' , 'j' ,'k' ,'l','m' ,'n' ,'o' ,'p' ,'q' ,'r' ,'s' ,'t' ,'u' ,'v' ,'w','x','y','z']
inputnumber = int(input("Enter Number"))
for i, number in enumerate(range(len(List1)),start=1):
if i == inputnumber:
print(List1[i])

Please help for it to work for numbers 1st divisible by 2nd

I am trying to write a code in Python where the user is asked to enter the number of numbers in a sequence, then the numbers themselves. And finally, the program outputs the number of pairs of adjacent odd numbers. Here's a sample output:
Enter the length of the sequence:
Enter number 1: 75
Enter number 2: 25
Enter number 3: 10
Enter number 4: 30
Enter number 5: 3
The number of pairs of adjacent where 1st divisible by 2nd is :2
Your question is not clear enough but the below code should work, please feel free to understand some builtin functions like enumerate
seq = int(input("Enter the length of sequence "))
list_num = []
count = 0
for i in range(1, seq+1):
num = int(input(f"Enter number {i} "))
list_num.append(num)
for i1, ele in enumerate(list_num):
if i1 < (len(list_num)-1):
if ((list_num[i1]) % list_num[i1+1]) == 0:
count += 1
else:
break
print("The number of pairs of adjacent where 1st divisible by 2nd is :",count)
This will do what you want:
n = int(input("Enter the length of the sequence: "))
nums = []
for i in range(n):
nums.append(int(input(f"Enter number {i+1}: ")))
divs = 0
for j in range(n-1):
if not nums[j] % nums[j+1]:
divs += 1
print("The number of pairs of adjacent where 1st divisible by 2nd is :", divs)
After getting inputs, I loop from beginning of nums to one left to the last (because there is nothing for last element to be compared to). Then compare every element is list with the one after it; If it was divisible, I add one to total number of divisibles (divs).
You can also use list comprehension:
[nums[j] % nums[j+1] for j in range(n-1)].count(0)

Concatenate the numbers between 1 and N and see if it is divisible by 3

I'm trying to make a program that basically works like this:
I ask for a number, and from that number I must form a number N by concatenating all the numbers between 1 and N. For example, if I enter a 12, the number N will be 123456789101112, or if I enter a 6, the number would be 123456. Once N has been formed, I must return "YES" on the screen in the case that N is divisible by 3 and “NO” in the case that it is not.
This is what I have:
n = int(input("Enter a number:"))
for x in range (n + 1):
if(n%3==0):
print("YES")
else:
print("NO")
I just started using Python and I don't know what I'm doing wrong, if someone can give me a hand I would be very grateful!
The answer will be :
if n%3 != 1:
print("YES")
else:
print("NO")
Reason
Every number is one of the three types (3*k+1), (3*k+2) or (3*k). A number is divisible by 3 if the sum of its digits is divisible by 3 a.k.a. it is a (3*k) type of number.
If input is 1. Then N will be 1 which is a (3*k+1) type of number so it is not divisible by 3.
When input is 2. Then N will be 12 which is divisible by 3.
When input is 3. Then N will be 123 which is divisible by 3.
Similarly, when input is 4. Then N will be 1234 which is not divisible by 3.
If you go one you realise that N will be divisible by 3 whenever the input is not a (3*k+1) type of number.
If you want to do it using the algorithm you describe, then a simple (but not very fast) way of doing it would be so:
n = int(input("Enter a number:")) # get the number
stringNumber = ""
for x in range(1, n+1):
stringNumber += str(x) # join the string version of numbers 1...n into a string
intNumber = int(stringNumber) # convert the string concatenation into an int
if (intNumber % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
You can speed-up the string concatenation by using join() if you wish:
stringNumber = "".join([str(digit) for digit in range(1,n+1)])
the result is the same
However, you might also notice that a number is divisible by 3 if the sum of its digits is divisible by 3, so you can use an algorithm like this:
n = int(input("Enter a number:")) # get the number
sumOfDigits = sum([digit for digit in range(1,n+1)]) # sum numbers 1...n
if (sumOfDigits % 3 == 0): # check if the int is divisible by 3
print("YES")
else:
print("NO")
Here is one possible solution. It shows how you can test n the input and val the concatenated value
n = int(input("enter a number: "))
# This line creates a list of numbers and
# then concatenates them as a new number in string format
val = "".join(str(x) for x in range(1, n + 1))
print(f"Is {n} divisible by 3? ")
print("no" if int(n) % 3 else "yes")
print(f"Is {val} divisible by 3? ")
print("no" if int(val) % 3 else "yes")
You can write a one-line tertiary operation with a list comprehension to do this as well.
def check():
n = int(input("Enter a number:"))
return 'Yes' if int(''.join([str(i) for i in range(1,n+1)]))%3==0 else 'No'
check()
Enter a number:12
'Yes'
Use a range to produce numbers from 1 to N, convert them to strings and concatenate them:
x = 12
N = int("".join(map(str,range(1,x+1))))
div3 = N%3 == 0
print("Is",N,"divisible by 3?",["NO","YES"][div3])
# Is 123456789101112 divisible by 3? YES

Taking the sum of a list without sum()

I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))
numList = []
for i in range(0, xAmount):
numList.append(int(input("Enter a number: ")))
print(numList)
From here
Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))
numList = []
numList_sum = 0
for i in range(0, xAmount):
inputted_number = int(input("Enter a number: "))
numList_sum += inputted_number
numList.append(inputted_number)
print(numList)
print(numList_sum)
You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0
for i in range(0, xAmount):
result = result + int(input("Enter a number: "))
print(result)
To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
num_total += value
You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)

Categories

Resources