Operations with integers in lists - python

I have a task in the course which sounds like this:
Write a program that takes as input a list of numbers in one line. The program should output the sum of its two neighbors for each element of this list. For list elements that are extreme, one of the neighbors is the element located at the opposite end of this list. For example, if the input is the list "1 3 5 6 10", then the output is the list "13 6 9 15 7" (without quotes). If only one number came to the input, you need to display it.
Sample Input 1:
1 3 5 6 10
Sample Output 1:
13 6 9 15 7
Problem occurs when i try to operate with the first number after checking if there is one number. It says 'int' object is not iterable. I tried to edit my code with various constructions with if, while, for. But it is all the same. Would you kindly help me to understand how to operate with integers in the list and add the results of the operations to the new one? Here is the code (result is the supposed output):
user_input = input()
lst = [int(i) for i in user_input.split(' ') if i.isdigit()]
result = []
if len(lst) == 1: #Check if one element
print(lst[0])
if len(lst) > 1:
for lst[0] in range(len(lst)): #For the first index
result += (lst[1] + lst[-1])

Following the code you've pasted, this is the way it should be completed:
user_input = '1 3 5 6 10'
lst = [int(i) for i in user_input.split(' ') if i.isdigit()]
result = []
if len(lst) == 1:
print(lst[0])
elif len(lst) == 2: # What happens if there are 2 elements?
print(lst[1], lst[0])
else:
for index in range(len(lst)): # range(n) returns a generator that yields [0, ..., n - 1]
result.append(lst[index - 1] + lst[(index + 1) % len(lst)])
# result.append(n) adds n to the "result" list
# lst[(index + 1) % len(lst)] we need the modulo (%) because a list of n elements
# won't have an index n, thus you want the sum of elements n - 1 and 0 == n % n

Related

how do you make a list of numbers and then arrange them even first then odd?

"I’m a world-renowned fashion designer and I’m about to screen new models for next month’s Fashion Week. I made them all wear different numbers and what I want you to do is separate the even-numbered models from the odd-numbered ones and make sure they get to go first. I don’t care if they call it number discrimination, I just have a preference for even numbers, okay? It’s not weird!"
An example of the output should look like:
Enter the number of elements: 4
Element #1: 6
Element #2: 5
Element #3: 17
Element #4: 12
Arranged Elements:
Element #1: 6
Element #2: 12
Element #3: 5
Element #4: 17
as you can see the list of elements are arranged, even first, then odd.
This is my current code:
num_list = []
listLength = int(input("Enter the number of elements: "))
num = 1
for i in range(listLength):
el = int(input("Element #%d: " % num))
num += 1
if el % 2 == 0:
num_list.append(el)
elif el % 2 != 0::
num_list.append(el)
print(num_list)
You are on the right track, but you keep appending to the same list, whether it is an even or an odd number. You need two lists:
even_list = []
odd_list = []
listLength = int(input("Enter the number of elements: "))
...
then:
if el % 2 == 0:
even_list.append(el)
elif el % 2 != 0:
odd_list.append(el)
and finally, concatenate the two lists:
num_list = even_list + odd_list
print(num_list)

Create 3 digit numbers that are even and count them

I need to make a program in Python that do this:
Write a program that, for a given sequence of digits, prints the number of different three-digit even numbers that can be formed from the given digits. When forming each three-digit even number, each element of the sequence of digits can be used at most once.
The first line of the standard input contains the number of digits N, such that 3≤N≤50000. In the second row is N digits separated by one space.
Print only one number to the standard output, the requested number of three-digit numbers.
n=int(input())
num=[]
for i in range (n):
num.append ()
Input
4
2 4 2 2
Output
4
Explanation
From the digits 2, 4, 2, 2, 4 different three-digit even numbers can be formed, namely 222, 224, 242, 422.
This is a general solution that checks all permutations of these digits and print even numbers out of them:
from itertools import permutations
k = 3
c = 0
n = int(input())
num = input().strip().split(" ")
perms = set(permutations(num, k))
for perm in perms:
t = int("".join(perm))
if t % 2 == 0 and len(str(t)) == k:
print(t)
c += 1
print(c)
This is another solution if you don't want to use this generalized approach and just want to solve it for 3 digits:
c = 0
n = int(input())
num = [int(x) for x in input().strip().split(" ")]
r = set()
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or i == k or j == k:
continue
t = num[i] * 100 + num[j] * 10 + num[k]
if t % 2 == 0 and len(str(t)) == 3:
r.add(t)
print(r)
print(len(r))
First You should declare which user input u expect and how to handle false input.
Then the inputString is split into a list of Strings aka inputList. Now You can loop through each of those inputItem and check if they fit your expectations (is int and smaller then 10 ). Since You still deal with String Items You can try to cast ( convert them) into Int. That can fail and a unhandled failure could cripple Your script so it has to happen in an try- catch-block. If the casting works You wanna make sure to check your matchList if You allready added a simular number before You add the new Number to Your matchList.You do so again by looping through each item. If there is mo such number yet there is a last check for if the number is uneven or 0. In that case there is one possible combination less for each number that is 0 or uneven so they are counted in the variable minusOneCombi. That will be substrated from the maximum amount of combinations which is the amount of numbers in you matchList multiplied with itself (pow(2)). Be very careful with the Indentations. In Python they are determining the ends of if blocks and loops.
InputString=(input("Enter your number stream eg 1 0 0 5 ( non numeric signs and numbers greater 9 will be ignored): "))
inputList= inputString.split(‘ ’)
matchList=[]
minusOneCombi= 0
for inputItem in inputList:
try:
anInt= int(inputItem)
except ValueError:
# Handle the exception
print(“item is not an integer and therefore ignored”)
NotYetinMatchList= True
for MatchItem in MatchList:
If matchItem == inputItem:
notYetinMatchList= False
Break
If notYetinMatchList:
matchList.append(anInt)
if ((anInt % 2) != 0) OR (anInt ==0):
minusOneCombi++
NumofMatches=matchList.count()
NumOfMatchesPow= pow(NumofMatches,2)
Result=NumOfMatchesPow -minusOneCombi
Print(Result)

Python check list evenness

Is there a pythonic way to find out which number is different in evenness from others ?
E.g.:
input: "2 4 7 8 10" => output: 3 // Third number is odd, while the rest of the numbers are even
input: "1 2 1 1" => 2 // Second number is even, while the rest of the numbers are odd
Bellow is my approach, where numbers is the input as str:
def evenness(numbers):
bool_number = list(map(lambda i: i%2==0, map(lambda i: int(i), numbers.split(" "))))
if bool_number.count(True) == 1:
return bool_number.index(True)+1
else:
return bool_number.index(False)+1
Thanks
If you only ever have one instance of an odd/even discrepancy, you can convert all numbers to 1s (for odds) and 0s (for evens) and check for the first 1 or first 0 depending on whether you have more than one odd:
s = "2 4 7 8 10"
odds = [int(n)&1 for n in s.split()]
index = odds.index(sum(odds)==1)+1
print(index) # 3
You can try this function it will return you the index of the only item that is different then the others and if there will be more then one or zero occurrence then it will return -1
def evenness(numbers):
res = list(filter(lambda x: x.count(0) == len(x) -1, [[i if int(n) % 2 else 0 for i, n in enumerate(numbers.split(" "))], [i if not int(n) % 2 else 0 for i, n in enumerate(numbers.split(" "))]]))
return -1 if len(res) != 1 else sum(res[0])

Using a loop to describe multiple conditions

In the following code, I am trying to extract numbers from a list in which all digits are divisible by 2. The following code works.
l = range(100,401)
n=[]
for i in l:
s =str(i)
if all([int(s[0])%2==0,int(s[1])%2==0,int(s[2])%2==0]):
n.append(s)
print(",".join(n))
I was trying to insert a for loop to avoid writing all three conditions explicitly.
l = range(100,401)
n=[]
ss=[]
for i in l:
s =str(i)
ss.append(s)
for element in ss:
for j in range(3):
if int(element[j])%2==0:
n.append(element)
print(n)
I can't get the desired output. Not only that, the elements of output list 'n' at even index are printed twice. I am unable to figure out WHY?
Thanks.
Generator expression checking if all() elements evaluate to True comes to your rescue:
l = range(100,401)
n=[]
for i in l:
s = str(i)
if all(int(ch) % 2 == 0 for ch in s):
n.append(s)
print(",".join(n))
Now it also works even if you work with more digits.
Thanks for #jpp's advice on generator expression!
And here a faster alternative where you evaluate if any() is not divisable with 2.
l = range(100,401)
n=[]
for i in l:
s = str(i)
if any(int(ch) % 2 != 0 for ch in s):
continue
else:
n.append(s)
print(",".join(n))
You can do this:
l = range(100, 401)
n = []
for i in l:
v = 0
for j in str(i):
if int(j) % 2 == 0:
v += 1
if v == len(str(i)):
n.append(str(i))
print(",".join(n))
Or with some list comprehension:
l = range(100, 401)
n = []
for i in l:
if all(int(j) % 2 == 0 for j in str(i)):
n.append(str(i))
print(",".join(n))
Or with even more list comprehension:
l = range(100, 401)
n = [str(i) for i in l if all(int(j) % 2 == 0 for j in str(i))]
print(",".join(n))
Or with a ridiculous minimizing:
print(",".join([str(i) for i in range(100, 401) if all(int(j) % 2 == 0 for j in str(i))]))
Explaining
OP asked me to explain why his code doesn't work. I'll make it in some steps, also optimizing it:
l = range(100,401)
n = []
ss = []
for i in l: # You don't need this loop, you are just making a new list with string values instead of integers. You could make that on the fly.
s = str(i)
ss.append(s)
for element in ss:
for j in range(3):
if int(element[j]) % 2 == 0: # This only check if the current digit is pair and it append the whole number to the list. You have to check if the 3 numbers are pair AND then append it.
n.append(element)
print(n)
Your code check each digit and if that is true, the number is appended to the result list (n). But you don't want that, you want to check if the 3 digits that make the number are pair, so you have to check the whole group.
For example you could do this:
for element in l:
pairs = 0
for j in range(3):
if int(str(element)[j]) % 2 == 0:
pairs += 1 # Each time a digit of the number is pair, `pairs` variable increase in one
if pairs == 3: # If the 3 digits are true it append your number
n.append(str(element))
That is my first idea of how to improve your code, but instead of element and pairs I use j and v, (also I don't use range(3), I just iterate over the stringed number).
If you are looking for something "better" you could try to use a list comprehension like all(int(j) % 2 == 0 for j in str(i)). That iterate over all the digits to check if the are pair, if all the checks are true (like 222, or 284) it returns true.
Let me know if I should explain something more.
Try this method. You don't need to check all the numbers.
You just need to change the range statement from range(100, 401) to range (100, 401, 2) and add some checks as the Numbers which have first digit as Odd you can skip all the 100 numbers and then in next 10 series you can skip 10 if the tenth digit is odd. It reduces the complexity and decreases your processing time.
l = range(100, 401, 2)
n = []
for i in l:
s = str(i)
if int(s[0]) % 2 == 1:
remainder = i % 100
i = i - remainder + 100 - 1
continue
elif int(s[1])%2 == 1:
remainder = i % 10
i = i - remainder + 10 - 1
continue
n.append(s)
print(",".join(n))

Trying to systematically remove elements from a list, but some elements are left out?

I have tried to create a list of whole numbers under 1000 (aka, 0 to 999), then delete the numbers that don't comply with a certain rule [ex. must be divisible by 7 or 3]. After, I have find the sum of all these numbers. Below is the code I wrote to do so.
number_list = []
for x in range(1000):
number_list.append(x)
index = 0
element = number_list[index]
max = 1000
deleted = 0
while index < max - deleted:
element = number_list[index]
if element % 7 != 0 or element % 3 != 0:
number_list.remove(element)
deleted = deleted + 1
index = index + 1
print(sum(number_list))
This runs without any issues, but it does not return the correct sum. The correct sum is 214216, but this gives me 261832 instead, leading me to believe that more than 40 elements that should have been deleted, have not been deleted.
How can I fix this problem?
This is one way to do it using list comprehensions:
number_list = [i for i in range(1000) if not i % 7 != 0 or not i % 3 != 0 ]
print sum(number_list) #Python2
Output:
214216
Using list comprehension should be simpler for this problem. Anyway, I'll try to fix your implementation.
The condition element % 7 != 0 or element % 3 != 0 should be and
instead of or.
If a number is deleted in the loop iteration, index shouldn't move to the next, because the next element is at this index now.
In summary:
if element % 7 != 0 or element % 3 != 0:
number_list.remove(element)
deleted = deleted + 1
index = index + 1
should be:
if element % 7 != 0 and element % 3 != 0:
number_list.remove(element)
deleted = deleted + 1
else:
index = index + 1
When you remove elements from the list: number_list.remove(element), the meaning of the index changes so that on the next iteration, after incrementing index, element = number_list[index] now references a value other than the index-th item of the original number_list. Thus, some values in the original number_list are never checked.
The solution, in general, is to not mutate a list while iterating over it. Instead, use a list comprehension (or, for memory-efficiency, a generator expression) to build a new list:
In [107]: sum([i for i in range(1000) if (i % 7 == 0) or (i % 3 == 0)])
Out[107]: 214216
or, iterate over index backwards, counting from 999 down to 0, so that removing the index-th item will not affect the indexing of other items when using a smaller index.
Everything is much simpler.
sum=0
for x in range(1000):
if x % 7 == 0 or x % 3 == 0:
sum=sum+x
print sum
Result:
214216

Categories

Resources