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)
Related
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"
I am trying to use the modulo operator in this function that prints the highest even number in a list, but I always get this error:
TypeError: not all arguments converted during string formatting
Code:
def largest_even():
"""
-------------------------------------------------------
Returns the largest even number.
Use: result = largest_even()
-------------------------------------------------------
Preconditions:
Postconditions:
returns
result - largest even number
-------------------------------------------------------
"""
num = int(input('Enter a number:'))
n_list = []
while num != "":
n_list.append(num)
num = input('Next number:')
print(n_list)
n = 0
e_list = []
while n < len(n_list):
a = (n_list[n]) % 2
if a == 0:
e_list.append(n_list[n])
n = n + 1
print(n)
print(e_list)
if len(e_list) == 0:
result = 'False'
result = e_list[0]
n = 0
while n < len(e_list):
if e_list[n] > result:
result = e_list[n]
print("{} is the largest even number in that list.".format(result))
You only add one number to the list; inside the loop, you are adding strings.
num = input('Enter a number:')
n_list = []
while num != "":
n_list.append(int(num))
num = input('Next number:')
This is linear search code but it is not working can anyone help me out!!
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
def lSearch(data, s):
for j in range(len(data)):
if data[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(data, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)
s is an integer, but your list will be full of strings since you append x to it.
x = raw_input('Enter the numbers into the array: ')
See here x is a string. You have not converted this to an int (unlike at other places)
If this is actually Python 3 and not Python 2 (as it says in your tags), then you should be using input() not raw_input() (raw_input doesn't actually exist in Python 3). input() will return a string in Python 3 (unlike in python2, where it might return an integer).
thanks to everyone.Now , my code is running by a simple change raw_input to input().
data = []
n = int(input('Enter how many elements you want: '))
for i in range(0, n):
x = input('Enter the numbers into the array: ')
data.append(x)
k = sorted(data)
print(k)
def lSearch(k, s):
for j in range(len(k)):
if k[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(k, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)
I am beginner in programming, So can you please tell me what's wrong with my code?
I want to print next palindrome number if the number entered by the user (n) is not palindrome
n = int(input("Enter any number :- "))
reverse = 0
temp = n
while (n!=0):
reverse = reverse * 10
reverse = reverse + n%10
n=n//10
if(temp==reverse):
print ("Already palindrome:: ")
if(temp != reverse):
new_temp = temp
new_reverse = 0
for i in range(new_temp,new_temp+10):
while(temp != 0):
new_reverse = new_reverse * 10
new_reverse = new_reverse + temp%10
temp = temp//10
if(new_temp==new_reverse):
print ("Next pallindrome is :- ",new_temp)
break
if(new_temp != new_reverse):
temp = new_temp+1
There are two problems with your code.
1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value.
You do
new_temp = temp
for i in range(new_temp,new_temp+10):
[SNIP]
if(new_temp != new_reverse):
temp = new_temp+1 #this value never changes.
So you're making 10 iterations with one and the same value.
2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.
Working code:
def reverse(num):
reverse= 0
while num:
reverse= reverse*10 + num%10
num= num//10
return reverse
num= int(input("Enter any number :- "))
if num==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if num==reverse(num):
print ("Next palindrome is : %s"%num)
break
To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.
>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False
Use this to your advantage, and create a function:
def is_palindrome(foo):
return str(foo) == str(foo)[::-1]
Next, to find the next palindrome, simply increment the number till your palindrome check is true.
Combine all that, and you have:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = raw_input('Enter a number: ')
if is_palindrome(n):
print('Congratulations! {0} is a palindrome.'.format(n))
else:
n1 = n
while not is_palindrome(n1):
n1 = int(n1)+1
print('You entered {0}, but the next palindrome is {1}'.format(n, n1))
Here is how it works:
$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:
def next_palin_number(number):
number+=1
# Convert the number to a list of its digits.
number = list(str(number))
# Initialize two indices for comparing symmetric digits.
i = 0
j = len(number) - 1
while i < j:
# If the digits are different:
if number[i] != number[j]:
# If the lower-power digit is greater than the higher-power digit:
if int(number[j]) > int(number[i]):
if number[j-1]!='9':
number[j - 1] = str(int(number[j - 1]) + 1)
number[j] = number[i]
else:
number = list(str(int(''.join(number[:j]))+1))+number[j:]
else:
number[j] = number[i]
i += 1
j -= 1
# Concatenate and return the result.
return "".join(number)
This problem has a wonderful number of ways to solve them.
One of them is
def nearest_palindrome(number):
#start writitng your code here
while True:
number+=1
if str(number) == str(number)[::-1]:
return number
number=12300
print(nearest_palindrome(number))
Thanks for your time to read my answer : )
I have written this for finding next pallindrome number given a pallindrome number.
def palindrome(num):
bol=False
#x=len(str(num))
num=num+1
while(bol==False):
if(check_palindrome(num)):
bol=True
else:
num=num+1
return num
def check_palindrome(n):
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
return True
b=palindrome(8)
print(b)
def next_palin_drome(n):
while True:
n+=1
if str(n) == str(n)[::-1]:
return n
n=12231
print(next_palin_drome(n))
output:12321
def nearest_palindrome(number):
for i in range(1,number):
number=number+1
tem=str(number)
tem1=tem[-1::-1]
if(tem==tem1):
return number
else:
continue
number=12997979797979797
print(nearest_palindrome(number))
def nearest_palindrome(number):
n = len(str(number))//2
if(len(str(number)) % 2 == 0):
#number like 1221
number_1 = int((str(number))[:n]) #12
number_2 = int((str(number))[n:]) #21
if(number_1 < number_2):
number_1 += 1
number_2 = int(str(number_1)[::-1])
else:
number_2 = int(str(number_1)[::-1])
# if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(number_1)[::-1]
#combining the both parts
ans = int(str(number_1) + str(number_2))
return ans
else:
#numer like 12510 n=2
nu = int((str(number))[:n+1]) #add in this number
number_1 = int((str(number))[:n]) # 12
number_2 = int((str(number))[n+1:]) # 21
if (number_1 < number_2):
nu += 1
number_2 = int((str(nu))[::-1][1:])
else:
number_2 = int((str(nu))[::-1][1:])
#if last half part is zero then just reverse the first number
if number_2 == 0:
number_2 = str(nu)[::-1]
number_2 = number_2[1:]
#combinning both parts
ans = int(str(nu) + str(number_2))
return ans
number=12331
print(nearest_palindrome(number))
If a definite range is given:
# function to check if the number is a palindrome
def palin(x):
s=str(x)
if s==s[::-1]:
return True
else:
return False
n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
if palin(i) is True:
print(i)
break
A brute force method:
def math(n):
while not var:
n += 1
if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.
This solution has O(n) time if you look at the length of the number
beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1)
length = len(string)
number= [int(x) for x in list(string)]
for i in range(length//2):
if (number[i] != number[length-1-i]):
if (number[i]<number[length-1-i]):
number[length-2-i] += 1
number[length-1-i] = number[i]
print("".join([str(x) for x in number]))
I have written this for finding next pallindrome number given a pallindrome number..
#given a pallindrome number ..find next pallindrome number
input=999
inputstr=str(input)
inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
if(length%2==0):
#take left part and reverse it(which is equal as the right part )
temp=inputstr[:length/2]
temp=temp[::-1]
#take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
for j,i in enumerate(temp):
#if number is not 9 then increment it and end loop
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now you have right hand side...mirror it and append left and right part
output=temp[::-1]+temp
#if the length is odd
if(length%2!=0 ):
#take the left part with the mid number(if length is 5 take 3 digits
temp=inputstr[:halflength+1]
#reverse it
temp=temp[::-1]
#apply same algoritm as in above
#if 9 then make it 0 and move on
#else increment number and break the loop
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
#now the msb is the middle element so skip it and copy the rest
temp2=temp[1:]
#this is the right part mirror it to get left part then left+middle+right isoutput
temp2=temp2[::-1]
output=temp2+temp
print(output)
similarly for this problem take the left part of given number ...reverse it..store it in temp
inputstr=str(number)
if(inputstr==inputstr[::-1])
print("Pallindrome")
else:
temp=inputstr[:length/2]
temp=temp[::-1]
for j,i in enumerate(temp):
if(i!="9"):
substi=int(i)+1
temp=temp[:j]+str(substi)+temp[j+1:]
break;
else:
temp=temp[:j]+"0"+temp[j+1:]
now depending on length of your number odd or even generate the output..as in the code
if even then output=temp[::-1]+temp
if odd then temp2=temp1[1:]
output=temp2[::-1]+temp
I am not sure about this solution..but hope it helps
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.