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]
Related
I have a list and I'm trying to write a program that finds the highest odd and even number and add them together then print the number.
numbers = [2,3,4,5,6,1,0,7]
def solution(numbers):
lodd = -1
leven = -1
for n in numbers:
n = int(n)
if n % 2 == 0 and n > leven:
leven = n
print(n)
for n in numbers:
n = int(n)
if n % 2 != 0 and n > lodd:
lodd = n
print(n)
solution(numbers)
You could do something like :
odds = [element for element in numbers if element % 2 != 0]
evens = [element for element in numbers if element % 2 == 0]
print(max(odds) + max(evens))
Why use two loops where you could just iterate once?
Iterate and save the max per condition (odd or even), then sum the result.
positive numbers only
numbers = [2,3,4,5,6,1,0,7]
out = {0: 0, 1: 0}
for n in numbers:
if n>out[n%2]:
out[n%2] = n
sum(out.values())
# 13
more generic code to handle negative numbers as well and missing odd/even values
This handles possible missing evens or odds:
numbers = [1,3,1,5,1,-7]
out = {0: None, 1: None}
for n in numbers:
k = n%2
if out[k] is None or n>out[k]:
out[k] = n
sum(v for v in out.values() if v)
# 5
So basically I want python to first wait and let me input stuff and then do whatever it has to for every pair of inputs.
t = int(input())
E = 0
for i in range(0, t):
M, N = [int(M) for M in input(" ").split()]
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The terminal looks somewhat like this,
13 100
X
2 0
Y
I want the 2 0 to be before X but at the same time I want the code to calculate for 13 100 and output X but just after I input the 2nd pair of X, Y.
I also want to know how to remove the spaces before the '2 0' and the 'Y'.
Thanks.
Firstly, the reason you have spaces before 2 0 is because in the line:
M, N = [int(M) for M in input(" ").split()]
your input function has a space within the quotes, so you must remove it and just have an empty string:
M, N = [int(M) for M in input("").split()]
Next, the reason your code is asking for input then generating an output and so on is because the logical operators are within the for loop you have. To fix this you should have your loop to first gather the inputs then, have another loop to perform the logical operators on those inputs as so:
t = 2
E = 0
numList = []
for i in range(0, t):
M, N = [int(M) for M in input("").split()]
numList.append([M, N])
for val in numList:
if E in range(0, t):
if val[0] > 0 and val[1] > 0:
print("X")
if val[0] > 0 and val[1] == 0:
print("Y")
if val[0] == 0 and val[1] > 0:
print("Z")
To simplify things I set t = 2 since we are only talking about 2 pairs of numbers. Furthermore, I created a list to hold each pair of inputs (numList), in which the first for loop appends the values to it as an list. The next for loop looks at each item in numList and since numList is a list of lists I changed M and N to val[0] and val[1] which refer to the first number you inputed (M) and the second one you inputed (N).
Finally,
for i in range(0, t):
should look like:
for i in range(t):
Since the range function automatically just counts from 0 to t and "i += 1" at the end of the loop is also unnecessary and redundant.
My final output:
[1]: https://i.stack.imgur.com/1Bo9U.png
Put all the inputs in a 2-dimensional list before the loop that processes them.
t = int(input())
E = 0
all_inputs = [[int(M) for M in input(" ").split()] for _ in range(t)]
for M, N in all_inputs:
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The space before the 2 0 is the prompt " " in your input(" ") call. If you don't want that, use input() with no prompt.
I don't see any reason for the space before Y.
Hope this help. Its a little cleaned up:
iterations = int(input("How many times? "))
values = []
for i in range(iterations):
values.append([int(M) for M in input(f"{i+1}. Enter two numbers: ").split()])
for M, N in values:
print(M, N, end=' -> ')
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
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))
I was wondering if there is any easier way to achieve what this code is achieving. Now the code creates all 4-digits number in a list (if the number starts with a 0 is doesn't count as a 4-digit, for example 0123) and no digit is repeated within the number. So for example 1231 is not in the list. Preferable I want a code that does what this one is doing but a depending on what argument N is given to the function upon calling it creates this kind of list with all numbers with N digits. I hope this wasn't impossible to understand since Im new to programing.
def guessables():
'''creates a list of all 4 digit numbers wherest every
element has no repeating digits inside of that number+
it doesn't count as a 4 digit number if it starts with a 0'''
guesses=[]
for a in range(1,10):
for b in range(0,10):
if a!=b:
for c in range(0,10):
if b!=c and a!=c:
for d in range(0,10):
if c!=d and d!=b and d!=a:
guesses.append(str(a)+str(b)+str(c)+str(d))
return guesses
This can be expressed more easily.
def all_digits_unique(number):
# `set` will only record unique elements.
# We convert to a string and check if the unique
# elements are the same number as the original elements.
return len(str(number)) == len(set(str(number)))
Edit:
def guesses(N):
return filter(all_digits_unique, range(10**(N-1), 10**N))
print guesses(4)
I'd use itertools for this which is in my opinion the simplest generic answer:
import itertools
def guessables(num):
guesses = []
for p in itertools.permutations(xrange(10),num):
if p[0] != 0:
guesses.append(''.join(map(str, p)))
return guesses
Simply call this function with guessables(4) and get a list with all the numbers you want.
You can do in one line:
print([str(a)+str(b)+str(c)+str(d) for a in range(1,10) for b in range(0,10) if a!=b for c in range(0,10) if b!=c and a!=c for d in range(0,10) if c!=d and d!=b and d!=a])
Try the following:
def guessables(n):
''' Returns an array with the combination of different digits of size "n" '''
if n > 10:
raise ValueError("The maximum number of different digits is 10.")
elif n < 1:
raise ValueError("The minimum number of digits is 1.")
else:
results = []
for i in range(1, 10):
_recursiveDigit([i], n, results)
return results
def _formatDigit(l):
''' Return a formated number from a list of its digits. '''
return "".join(map(str, l))
def _recursiveDigit(l, n, results):
''' Recursive function to calculate the following digit. '''
if len(l) < n:
for i in range(0, 10):
if i not in l:
_recursiveDigit(l + [i], n, results)
else:
results.append(_formatDigit(l))
The functions that are prefixed with an underscore(_) should not be called from outside of this script. If you prefer to have the result as something different than an array of strings, such as an array of ints for example, you can change the _formatDigit() function as follows:
def _formatDigit(l):
''' Return a formated number from a list of its digits. '''
return int("".join(map(str, l)))
c=list(range(10))
print c
def fun(n,k,i,getnum): # function , result in getnum
if n==0:
if k not in getnum and len(set(list(k)))==len(k) and k[0]!='0':
getnum.append(k)
return
if i>=len(c):
return
fun(n-1,k+str(c[i]),0,getnum)
fun(n,k,i+1,getnum)
getnum=[]
d=fun(4,"",0,getnum)
print getnum
These types of problems are easily solved with recursion.
def gen(num, n, saveto):
if len(num) == 1 and num[0] == '0':
return
if len(num) == n:
saveto.append(int(''.join(num)))
return
for i in range(0, 10):
i= str(i)
if i not in num:
gen(num+[i], n, saveto)
saveto= []
# generate 4 digit numbers
gen([], 4, saveto)
print(saveto)
Here I'm using the list num to construct the numbers by placing one digit at each call. When there are four digits added, it stores the number to the saveto list.
Edit: Here's a version of the above function that returns the list of numbers instead of appending them to a list.
def gen(num, n):
if len(num) == 1 and num[0] == '0':
return []
if len(num) == n:
return [int(''.join(num))]
ans = []
for i in range(0, 10):
i= str(i)
if i not in num:
ans.extend(gen(num+[i], n))
return ans
saveto= gen([], 4)
print(saveto)
numPool = []
for i in range(0, 10):
for j in range(0, 10):
for k in range(0,10):
for l in range(0,10):
if i != j and i != k and i != l and j != k and j != l and k != l :
numPool.append(str(i) + str(j) + str(k) + str(l))
This works, but keep in mind that this will also add "0123" or "0234" to the list as well. If you do not want the numbers that are starting with zero, you might want to add "i != 0" to the if query. Hope it helps.
I try to write it clear for absolute beginers ^^ Ofcourse it is possible to make it faster and shorter if you use combianations and advance array methods.
def f(n)
s = list(range(10**(n-1), 10**n))
number_list = []
for ss in s:
test_list = []
a = ss
while ss:
if ss % 10 in test_list:
break
test_list.append(ss % 10)
ss = ss // 10
if len(test_list) == n:
number_list.append(a)
return number_list
print(f(4))
This would sovlve the problem, without repeating digits:
from itertools import permutations
myperm = permutations([0,1,2,3,4,5,6,7,8,9],4)
for digits in list(myperm):
print(digits)
How about this?
def check_count(num):
if isinstance(num, str) == False:
num = str(num) # Convert to str
if len(num) == 1: # If total length number is single, return False
return False
return any(num.count(x) > 1 for x in num) # Check here
Return False if numbers all different, else return True
Usage:
# Get all numbers has all different. (1000-9999)
[x for x in range(1000, 10000) if check_count(x) == False]
I need to make a program in python that generates ten random numbers from 1-100 that stores it in a list using a loop. Then a second loop should display said list, then calculate the sums of the even and odd elements to display them. This is what I have so far, any help is greatly appreciated. Thanks
import random
def main():
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print(numlist)
list_length = len(numlist)
print('The number of elements in the list is', list_length)
More specifically this is the part I'm stuck on. I have to add the sums of the odd and then even elements. Every work around I've tryed has only given me the sum of the total elements.
for x in range(0, 10, 2):
numlist[x] = numlist
print('The Sum of the odd numbers is ', sum(numlist))
main()
import random
nums = [random.randint(1,100) for _ in range(10)]
You can use lambdas and filter
evenSum = sum(filter(lambda i : i%2 == 0, nums))
oddSum = sum(filter(lambda i : i%2, nums))
Or make some quick helper functions
def isEven(x):
return x % 2 == 0
def isOdd(x):
return x % 2 == 1
evenSum = sum(filter(isEven, nums))
oddSum = sum(filter(isOdd, nums))
Using your own code:
def main():
numlist = [] # create empty list to add randints to
for r in range(10):
numlist.append(random.randint(1,100)) # append to the list
list_length = len(numlist)
print('The number of elements in the list is', list_length)
odd = 0
even = 0
for num in numlist:
if num % 2: # if num mod 2 has a remainder, num is odd
odd += num
else: # else num is even
even += num
print('The Sum of the odd numbers is {} and even numbers is {}'.format(odd,even))
You can replace the first loop with a list comp:
numlist = [random.randint(1,100) for _ in range(10)]
Can't Understand the actual problem (hahehehe !)
As far as I have understood, you want to print the sum of odd and even numbers of the list that is generated from randint(). Well I have just edited your code ;)
so here is the simple done code !
Vote If It Helps !
import random
def main():
odd_sum=0
even_sum=0
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print numlist
list_length = len(numlist)
print('The number of elements in the list is', list_length)
for i in numlist:
if (i%2 == 1): #the remainder is 1 if the number is odd
odd_sum = odd_sum + i #add the odd_numbers
elif(i%2 == 0): #the remainder is 0 if the number is even
even_sum = even_sum + i #add the even_numbers
else:
print "No need of this else part !"
print "Odd_sum = ",odd_sum
print "Even_sum = ",even_sum
main()