Adding the highest odd and even in a list - python

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

Related

Why is my list comprehension only grabbing 0s?

LINE 11: List comprehension is only getting 0s?
please answer with the solution and nothing unrelated.
SUM_OF_DIVISORS = 0 # SUM OF THE DIVISORS OF (N)
def DIVISORS_SUM(N = 0):
global SUM_OF_DIVISORS
SUM_OF_DIVISORS -= N # MAKING SURE THAT N ITSELF IS EXCLUDED
if N != 0:
NUMBER = N
try:
DIVISORS = [X for X in range(0, N) if X%NUMBER == 0] # LIST COMPREHENSION (QUICK WAY OF FINDING DIVISORS)
X: int
for X in DIVISORS: # CREATING A FOR LOOP TO ADD TO SUM.
SUM_OF_DIVISORS += X
print(SUM_OF_DIVISORS)
except:
print("CAN'T CREATE SUM OF DIVISORS WITH 0.")
DIVISORS_SUM(0) # RETURNS ERROR BECAUSE N ITSELF MUST BE EXCLUDED
DIVISORS_SUM(3) # RETURNS 1 BECAUSE SUM OF DIVISORS WITH N EXCLUDED ADDS UP TO 1
DIVISORS_SUM(36) # RETURNS 36 BECAUSE SUM OF DIVISORS WITH N EXCLUDED ADDS UP TO 1
DIVISORS_SUM(102) # RETURNS 102 BECAUSE SUM OF DIVISORS WITH N EXCLUDED ADDS UP TO 1
Change:
DIVISORS = [X for X in range(0, N) if X%NUMBER == 0]
to:
DIVISORS = [X for X in range(1, N) if (NUMBER % X) == 0]
Note the 1 not zero to avoid ZeroDivisionError: integer division or modulo by zero

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]

Largest palindrome which is product of two n-digit numbers (Python)

This is my implementation, but it not efficient when given 6 digit number.
Input : n = 2
Output : 9009
9009 is the largest number which is product of two
2-digit numbers. 9009 = 91*99.
def isPali(x):
n = str(x)
for i in range(len(n)):
if not n[i] == n[-i-1]:
return False
return True
def isProduct(x,A):
counter = A
while counter > 1:
if x // counter <= A and x % counter == 0:
return True
else:
counter-=1
return False
def largestProduct(A):
for i in range(A*A,1,-1):
if isPali(i) and isProduct(i,A):
return i
return False
largestProduct(999999)
Let x and y be the two n-digit factors of the palindrome number.
You can iterate over them in a descending number.
Key is to stop as soon as possible, which mean, once a first solution has been found, you don't check any product below that solution.
def get_max_palindrome(n):
res = 0
for x in range(10 ** n - 1, 1, -1):
for y in range(10 ** n - 1, 1, -1):
p = x * y
if res > p:
break
if str(p) == str(p)[::-1]:
res = p
break
if (x - 1) ** 2 < res:
break
return res
print(get_max_palindrome(6))
Exec in 0.378s on my laptop.
Codewise, this is not too difficult:
n = 999999
max_pali =0
t = ()
for i in range(1,n+1):
for j in range(i,n+1):
m = i*j
s = str(m)
if s == s[::-1] and m > max_pali:
max_pali = m
t = (i,j)
print(max_pali,t)
However, this is a brute force approach. For numbers with 6 digits, this will not terminate in a reasonable amount of time. Even if it will, I could ask you the same question for 7 or 42 digits. I suggest you look for some structure, or property, of those numbers whose multiple is a palindrome. Could such a pair be any pair of numbers? Is the case 91*99 = 9009 a mere coincidence, or is there a pattern?

Printing the number with the highest prime number of occurences

I'm trying to print the number with the highest number of prime occurrences. but it is printing the number an the times is printed.
#checking for the highest number
import collections
a= [11,11,11,23,37,53,37,37,2,11,23,21,17,12,17,17,17,17,19,19,11,11,33,33]
counter=collections.Counter(a)
print counter.most_common(1)
#checking the number that occurs prime times
for n in a:
times=a.count(n)
root=times**0.5
i=2
while i<= root:
if times% i != 0:
print n
i+=1
How about this:
a = [11,11,11,23,37,53,37,37,2,11,23,21,17,12,17,17,17,17,19,19,11,11,33,33]
def is_prime(n):
from math import sqrt
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(sqrt(n)) + 1, 2))
counter = {k: a.count(k) for k in set(a)}
from operator import itemgetter
while True:
maximum = max(counter.items(), key=itemgetter(1))
if is_prime(maximum[1]):
break
else:
counter.pop(maximum[0])
print(maximum) # (17, 5)
print(maximum[0]) # 17
is_prime function from here
In this case, 11 with 6 appearances is the most common but 6 is not a prime, so it gets disregarded. The second most common is 17 with 5 appearances. Since 5 is a prime, 17 is the answer.
Note that the check on whether the count is prime is performed on the element with the max count only to minimize the checks. If it is not, the element gets poped and the next one follows.
For a solution without modules you can substitute the following part of the code in:
while True:
maximum = max(counter.items(), key=lambda x: x[1])
if is_prime(maximum[1]):
break
else:
counter.pop(maximum[0])
You can use a comprehension list to make it all easier to read
primes = [x for x in set(your_list) if all(x % y != 0 for y in range (2, x))]
max = 0
nr = -1
for x in primes:
if primes.count(x) > max:
max = primes.count(x)
nr = x

Prime factorization - list

I am trying to implement a function primeFac() that takes as input a positive integer n and returns a list containing all the numbers in the prime factorization of n.
I have gotten this far but I think it would be better to use recursion here, not sure how to create a recursive code here, what would be the base case? to start with.
My code:
def primes(n):
primfac = []
d = 2
while (n > 1):
if n%d==0:
primfac.append(d)
# how do I continue from here... ?
A simple trial division:
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
with O(sqrt(n)) complexity (worst case). You can easily improve it by special-casing 2 and looping only over odd d (or special-casing more small primes and looping over fewer possible divisors).
The primefac module does factorizations with all the fancy techniques mathematicians have developed over the centuries:
#!python
import primefac
import sys
n = int( sys.argv[1] )
factors = list( primefac.primefac(n) )
print '\n'.join(map(str, factors))
This is a comprehension based solution, it might be the closest you can get to a recursive solution in Python while being possible to use for large numbers.
You can get proper divisors with one line:
divisors = [ d for d in xrange(2,int(math.sqrt(n))) if n % d == 0 ]
then we can test for a number in divisors to be prime:
def isprime(d): return all( d % od != 0 for od in divisors if od != d )
which tests that no other divisors divides d.
Then we can filter prime divisors:
prime_divisors = [ d for d in divisors if isprime(d) ]
Of course, it can be combined in a single function:
def primes(n):
divisors = [ d for d in range(2,n//2+1) if n % d == 0 ]
return [ d for d in divisors if \
all( d % od != 0 for od in divisors if od != d ) ]
Here, the \ is there to break the line without messing with Python indentation.
I've tweaked #user448810's answer to use iterators from itertools (and python3.4, but it should be back-portable). The solution is about 15% faster.
import itertools
def factors(n):
f = 2
increments = itertools.chain([1,2,2], itertools.cycle([4,2,4,2,4,6,2,6]))
for incr in increments:
if f*f > n:
break
while n % f == 0:
yield f
n //= f
f += incr
if n > 1:
yield n
Note that this returns an iterable, not a list. Wrap it in list() if that's what you want.
Most of the above solutions appear somewhat incomplete. A prime factorization would repeat each prime factor of the number (e.g. 9 = [3 3]).
Also, the above solutions could be written as lazy functions for implementation convenience.
The use sieve Of Eratosthenes to find primes to test is optimal, but; the above implementation used more memory than necessary.
I'm not certain if/how "wheel factorization" would be superior to applying only prime factors, for division tests of n.
While these solution are indeed helpful, I'd suggest the following two functions -
Function-1 :
def primes(n):
if n < 2: return
yield 2
plist = [2]
for i in range(3,n):
test = True
for j in plist:
if j>n**0.5:
break
if i%j==0:
test = False
break
if test:
plist.append(i)
yield i
Function-2 :
def pfactors(n):
for p in primes(n):
while n%p==0:
yield p
n=n//p
if n==1: return
list(pfactors(99999))
[3, 3, 41, 271]
3*3*41*271
99999
list(pfactors(13290059))
[3119, 4261]
3119*4261
13290059
Here is my version of factorization by trial division, which incorporates the optimization of dividing only by two and the odd integers proposed by Daniel Fischer:
def factors(n):
f, fs = 3, []
while n % 2 == 0:
fs.append(2)
n /= 2
while f * f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += 2
if n > 1: fs.append(n)
return fs
An improvement on trial division by two and the odd numbers is wheel factorization, which uses a cyclic set of gaps between potential primes to greatly reduce the number of trial divisions. Here we use a 2,3,5-wheel:
def factors(n):
gaps = [1,2,2,4,2,4,2,4,6,2,6]
length, cycle = 11, 3
f, fs, nxt = 2, [], 0
while f * f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += gaps[nxt]
nxt += 1
if nxt == length:
nxt = cycle
if n > 1: fs.append(n)
return fs
Thus, print factors(13290059) will output [3119, 4261]. Factoring wheels have the same O(sqrt(n)) time complexity as normal trial division, but will be two or three times faster in practice.
I've done a lot of work with prime numbers at my blog. Please feel free to visit and study.
def get_prime_factors(number):
"""
Return prime factor list for a given number
number - an integer number
Example: get_prime_factors(8) --> [2, 2, 2].
"""
if number == 1:
return []
# We have to begin with 2 instead of 1 or 0
# to avoid the calls infinite or the division by 0
for i in xrange(2, number):
# Get remainder and quotient
rd, qt = divmod(number, i)
if not qt: # if equal to zero
return [i] + get_prime_factors(rd)
return [number]
Most of the answer are making things too complex. We can do this
def prime_factors(n):
num = []
#add 2 to list or prime factors and remove all even numbers(like sieve of ertosthenes)
while(n%2 == 0):
num.append(2)
n /= 2
#divide by odd numbers and remove all of their multiples increment by 2 if no perfectlly devides add it
for i in xrange(3, int(sqrt(n))+1, 2):
while (n%i == 0):
num.append(i)
n /= i
#if no is > 2 i.e no is a prime number that is only divisible by itself add it
if n>2:
num.append(n)
print (num)
Algorithm from GeeksforGeeks
prime factors of a number:
def primefactors(x):
factorlist=[]
loop=2
while loop<=x:
if x%loop==0:
x//=loop
factorlist.append(loop)
else:
loop+=1
return factorlist
x = int(input())
alist=primefactors(x)
print(alist)
You'll get the list.
If you want to get the pairs of prime factors of a number try this:
http://pythonplanet.blogspot.in/2015/09/list-of-all-unique-pairs-of-prime.html
def factorize(n):
for f in range(2,n//2+1):
while n%f == 0:
n //= f
yield f
It's slow but dead simple. If you want to create a command-line utility, you could do:
import sys
[print(i) for i in factorize(int(sys.argv[1]))]
Here is an efficient way to accomplish what you need:
def prime_factors(n):
l = []
if n < 2: return l
if n&1==0:
l.append(2)
while n&1==0: n>>=1
i = 3
m = int(math.sqrt(n))+1
while i < m:
if n%i==0:
l.append(i)
while n%i==0: n//=i
i+= 2
m = int(math.sqrt(n))+1
if n>2: l.append(n)
return l
prime_factors(198765430488765430290) = [2, 3, 5, 7, 11, 13, 19, 23, 3607, 3803, 52579]
You can use sieve Of Eratosthenes to generate all the primes up to (n/2) + 1 and then use a list comprehension to get all the prime factors:
def rwh_primes2(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
def primeFacs(n):
primes = rwh_primes2((n/2)+1)
return [x for x in primes if n%x == 0]
print primeFacs(99999)
#[3, 41, 271]
from sets import Set
# this function generates all the possible factors of a required number x
def factors_mult(X):
L = []
[L.append(i) for i in range(2,X) if X % i == 0]
return L
# this function generates list containing prime numbers upto the required number x
def prime_range(X):
l = [2]
for i in range(3,X+1):
for j in range(2,i):
if i % j == 0:
break
else:
l.append(i)
return l
# This function computes the intersection of the two lists by invoking Set from the sets module
def prime_factors(X):
y = Set(prime_range(X))
z = Set(factors_mult(X))
k = list(y & z)
k = sorted(k)
print "The prime factors of " + str(X) + " is ", k
# for eg
prime_factors(356)
Simple way to get the desired solution
def Factor(n):
d = 2
factors = []
while n >= d*d:
if n % d == 0:
n//=d
# print(d,end = " ")
factors.append(d)
else:
d = d+1
if n>1:
# print(int(n))
factors.append(n)
return factors
This is the code I made. It works fine for numbers with small primes, but it takes a while for numbers with primes in the millions.
def pfactor(num):
div = 2
pflist = []
while div <= num:
if num % div == 0:
pflist.append(div)
num /= div
else:
div += 1
# The stuff afterwards is just to convert the list of primes into an expression
pfex = ''
for item in list(set(pflist)):
pfex += str(item) + '^' + str(pflist.count(item)) + ' * '
pfex = pfex[0:-3]
return pfex
I would like to share my code for finding the prime factors of number given input by the user:
a = int(input("Enter a number: "))
def prime(a):
b = list()
i = 1
while i<=a:
if a%i ==0 and i!=1 and i!=a:
b.append(i)
i+=1
return b
c = list()
for x in prime(a):
if len(prime(x)) == 0:
c.append(x)
print(c)
def prime_factors(num, dd=2):
while dd <= num and num>1:
if num % dd == 0:
num //= dd
yield dd
dd +=1
Lot of answers above fail on small primes, e.g. 3, 5 and 7. The above is succinct and fast enough for ordinary use.
print list(prime_factors(3))
[3]

Categories

Resources