def solution(l):
for x in (range(len(l))):
sum_l = sum(l)
num = l[x]
y = sum_l%3
l.sort()
if len(l) == 1 and l[0]%3 != 0:
return 0
elif ((num%3) == y and y != 0) :
l.remove(num)
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
elif y == 0:
l.sort(reverse=True)
strings = [str(number) for number in l]
l_string = ''.join(strings)
l_int = int(l_string)
return l_int
else:
return 0
Here is the code. Basically, I am asked to find the largest number that can be made by the integers in the list divisible by 3. It passes all the test cases except one (blind case), and I have literally no idea what the issue is. I've tried every possible type of list, meaning, 1 digit, 2 digits, etc. The list can have numbers 0-9, with 1-9 numbers in it. Can I get some help as to what I might be missing?
Here is how you can find the largest number that can be made by the integers in the list divisible by 3:
from itertools import permutations
def solution(l):
p1 = [s for i in range(2,len(l)+1) for s in permutations(l,i)] # List of tuples with all possible combinations of numbers
p2 = [str(t) for t in p1 if not sum(t)%3] # List of tuples with elements adding together divisable by 3
return int(''.join([n for n in max(p2) if n.isdigit()])) # Return greatest tuple converted to number form
print(solution([4,6,9,1,3,3,2,4]))
Output:
9644331
The best way to find whether a number is divisible by 3 with only its digits is by adding up all the digits. If the answer is divisible by three, then so is any number made up of the combination of all the digits.
from itertools import permutations
def solution(l):
if not l:
return 0
if len(l) == 1 and l[0] % 3 == 0:
return l[0]
if len(l) == 1 and l[0] % 3 != 0:
return 0
p1 = [s for i in range(2, len(l) + 1) for s in
permutations(l, i)]
p2 = []
for each in p1:
num = ""
for i in each:
num += str(i)
if int(num) % 3 == 0:
p2.append(int(num))
x = sorted(list(set(p2)))
ans = 0
if len(x) != 0:
ans = max(x)
if ans != 0:
return ans
return 0
def cozum(list):
a=[]
for i in range(1,len(list)):
p = permutations(list,i)
for pe in p:
a.append(pe)
toplamlar=[ tup for tup in a if sum(tup)%3 == 0 ]
if toplamlar:
res = max([ int(''.join(map(str, sayi))) for sayi in toplamlar])
return res
else:
return "No number divisible by 3"
Related
split the number where RHS multiplication is equal to LHS input by the user.
if there is no split available return -1
if multiple return least split
input
142811
output
1*4*2 =8*1*1
>>>3
input
301501
output
3*0=1*5*0*1
>>>2
i could just convert the number to the list
a=int(input("enter a number="))
res = [int(x) for x in str(a)]
and after that i could not know possible algorithm for it
Try this:
# Your code to get the number in a list
a=int(input("enter a number="))
res = [int(x) for x in str(a)]
# Define function to get the product of a list of numbers
def product(nums):
ret = 1
for n in nums:
ret *= n
return ret
# Iterate through numbers
for i in range(len(res)):
# Check if the products match
if product(res[:i]) == product(res[i:]):
# If they do, output and break
print('*'.join(str(x) for x in res[:i]), '=', '*'.join(str(y) for y in res[i:]))
break
else:
# If no break occurred, output 'Not found.'
print('Not found.')
Output:
enter a number=142811
1*4*2 = 8*1*1
try this;
def code(a):
cnt = 1
for i in range(1,len(a)):
list_lhs = a[:i]
list_rhs = a[i:]
left,right = 1,1
for n in list_lhs:
left = left*int(n)
for n in list_rhs:
right = right*int(n)
if left == right:
cnt = 0
print("Found Split at",i,":",list_lhs, "and", list_rhs)
break
if cnt == 1:
print("-1")
code(a = "301501")
# Found Split at 2 : 30 and 1501
from math import prod
def base10list(n: int) -> list[int]:
return [int(s) for s in str(n)]
def split_mul(n: int) -> int:
numbers = base10list(n)
for i in range(len(numbers)):
if prod(numbers[:i]) == prod(numbers[i:]):
return i
return -1
def main() -> None:
a = int(input("Enter an integer: "))
print("Split index:", split_mul(a))
if __name__ == '__main__':
main()
Result:
enter an integer: 142811
Split index: 3
Try this code -
#multiply elements of list
def mul(nl):
product = 1
for n in nl:
product = product*n
return product
def calculate_split_point(numList):
for i in range(1, len(numList)):
if mul(numList[:i]) == mul(numList[i:]):
numList = [str(n) for n in numList]
print(f'{"*".join(numList[:i])} = {"*".join(numList[i:])}')
return i
return -1
num = input("Enter a number :: ")
numList = [int(n) for n in num] # List of numbers
calculate_split_point(numList)
Very interesting and unique problem, loved solving it!
def multiply(num):
total = 1
for n in num: total*=int(n)
return total
def equ(num, split):
t1 = multiply(num[:split])
t2 = multiply(num[-(len(num)-split):])
ret_value = split if split <= len(num)-split else len(num) - split
if t2 == t1: return ret_value
else: return False
inp = input("Enter a number:")
p_splits = len(inp) - 1
splits = []
for i in range(p_splits):
val = equ(inp, i+1)
if not val == False:
splits.append(val)
splits.sort()
try: print(splits[0])
except IndexError: print("-1")
If you like try this:
def get_split(usr_input_str):
lst_digits = [digit for digit in usr_input_str]
for i in range(1,len(lst_digits)):
str_expr = '*'.join(lst_digits[0:i])+'=='+'*'.join(lst_digits[i:])
if eval(str_expr):
print(str_expr)
return
print(-1)
get_split("142811")
Here how it works:
for i in range(1,len(lst_digits)-1): start with a split position after the first digit (therefore the 1, in range) and check all positions until the last digit (therefore ,len(lst_digits))
build a string inserting "==" at the split position i and "*" in all other positions (done by str_expr =)
check if the string (fo example "1*4*2==8*1*1" evaluates to True and print the string if it does
if the loop over all split positions did not print anything print(-1)
I tried writing a Python program to accept a list of integers starting with 0 and ending with 20 from the user. Each integer of the said list either differs from the previous one by two or is four times the previous one. Return true or false
Can someone correct the condition which I have written
lst = []
n = int(input("Enter the no of elements in the list :"))
for i in range (0,n):
elem = int(input("Enter the elements between 0 and 20 : "))
lst.append(elem)
if elem >= 0 and elem <=20:
print(lst)
for i in elem:
if (i+1) >= 2(i) or 4(i+1) == i:
print(True)
else:
print(False)
You can use zip to pair up items with their successors. This will let you compare them and check your condition using any() or all() depending on your requirement:
if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # at least one number pair meets the criteria
else:
print(False)
or
if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # all numbers meets the criteria
else:
print(False)
arr_len = int(input("Input a length for list: "))
nums = [0] * arr_len
res = [False] * arr_len
for i in range(len(nums)):
num = -1
while not(num >= 0 and num <= 20):
num = input("Enter the elements between 0 and 20 : ")
num = nums[i] = int(num)
if num >= 0 and num <= 20:
print('appended')
else:
print('that number is not between 0 and 20')
for i in range(1, len(res)):
num = nums[i]
prev_num = nums[i-1]
if abs(num-prev_num) == 2 or prev_num == 4*num:
res[i] = True
for i in range(len(nums)):
print('i is: ', i, 'nums[i], ', nums[i],
', is allowed in array: ', res[i])
res = dict(zip(nums, res))
print(res)
How do I print sum of primes in a list in Python?
I'm a new to Python, therefore I might be making a terrible mistake.
Please help out.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
l1 = []
l = len(l1)
i = 0
sum = 0
for i in range(0,l):
if(prime(l1[i]) is True):
sum = sum +l1[i]
print(sum)
l1 = [3,4,5,6]
print(sumprimes(l1))
Output should be equal to 8.
def prime(n):
i = 2
c = 0
for i in range(1,n+1):
if(n%i == 0):
c = c+1
if(c == 2):
return True
else:
return False
def sumprimes(l1):
sum=0
for x in l1:
if prime(x):
sum += x
return sum
l1 = [3,4,5,6]
print(sumprimes(l1))
Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.
You can do it using below code too.
lst = [1,2,5,7,9,10,12]
def isPrime(x):
if x == 1:
return False
for i in range(2,x-1):
if x%i == 0:
return False
return True
def getPrimeSum(l):
l = [i for i in l if isPrime(i)]
return sum(l)
print(getPrimeSum(lst))
#Check and add into the list of primeval numbers (all primeval number under a specific number)
H = int(input("What the maxium number?: "))
RangeFinding = list(range(3, H+1))
import math
Prime = [2]
for a in RangeFinding:
x = True
y = 2
while x:
NCanA = math.floor(math.sqrt(a))
if a %y == 0:
print(f'{a} is not prime')
x = False
else:
if y > NCanA:
print(f'{a} is prime')
Prime.append(a)
x = False
else:
y = y + 1
x = True
print(Prime)
#**this function will check weather number is prime or not**
def prime(k):
i = 2
j = 0
for i in range(1,k+1):
if(k % i == 0):
j = j + 1
if(j == 2):
return True
else:
return False
#**this function will add all prime numbers**
def sumOfPrimes(l1):
sum=0
for y in l1:
if prime(y):
sum += y
return sum
list1 = [3,4,5,6]
print(sumOfPrimes(list1))
**You Will get output as 8**
Explain
I have created a function prime() that will check whether numbers are prime or not.
I have created a function sumOfPrime() that will add all the prime numbers.
list1
4)Called the function sumOfPrime(list1)
I have shared a Screenshot of the code and outputProgram and Output
Non-prime numbers are being printed because it checks only from '2-10' for prime numbers. How can I change the code to check for all numbers upto x?
N = eval(input("Enter the starting point N: \n"))
M = eval(input("Enter the ending point M: \n"))
n = str(N)
i = 0
for j in range(N, M):
if (n[i] == n[len(n)-1]):
x = N
N = N + 1
if not((x % 2 == 0) or (x % 3 == 0) or (x % 4 == 0) or (x % 5 == 0) or (x % 6 == 0) or (x % 7 == 0) or (x % 8 == 0) or (x % 9 == 0) or (x % 10 == 0)):
print(x)
n = str(N)
else:
N = N + 1
n = str(N)
Here's an implementation of the Sieve of Eratosthenes that I wrote. It pretty efficiently finds all the prime numbers less than the number you pass it. I would explain it to you, but Wikipedia (linked above) does a much better job than I could. Use it to generate the prime numbers and then iterate through the list it returns to check if those numbers are palindromes.
def primeslt(n):
"""Finds all primes less than n"""
if n < 3:
return []
A = [True] * n
A[0], A[1] = False, False
for i in range(2, int(n**0.5)+1):
if A[i]:
j = i**2
while j < n:
A[j] = False
j += i
return [num for num in range(n) if A[num]]
Heres a palindrome snippet
low_range = input()
high_range = input()
string_convertor = str
for num in range(int(low_range), int(high_range)):
num_to_string = string_convertor(num)
reverse = num_to_string[::-1]
if num_to_string == reverse:
print("Palindrome")
print(num_to_string)
I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.