I want the largest substring of 1's
inp = input("ENter number")
count = 1
num = []
for i in range(len(inp)):
if (inp[i] == inp[i+1]):
count+=1
num.append(count)
count = 1
print(max(num))
this is the input "10110111", the output must be 3
but there is error
if (inp[i] == inp[i+1]):
IndexError: string index out of range
You can solve it easily. Split() method will split your string input and returns a list and you can simply find the element with the maximum length
inp = input("Enter number")
max_Ones = len(max(inp.split('0'), key=len))
print(max_Ones)
I'd use re.findall and then convert each group to its length:
import re
inp = input("Enter number: ")
result = max(len(x) for x in re.findall('1+', input))
print(result)
Try this below:
inp = input("ENter number")
count = 0
result = 0
for i in range(0, len(inp)):
if inp[i] == '0':
count = 0
elif inp[i] == '1':
count += 1
result = max(result, count)
print(result)
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 have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))
I'm trying to make a lucky number counter where if there is a number containing either a 6 or an 8 between the two inputs the number is lucky, but if there's both a 6 and an 8 the number is unlucky. I'm having an issue where it's double-counting numbers, like 66, 88, etc., and not calling unlucky numbers like 68, 86, etc. Please help fast :\
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
for j in range(len(i)):
if i[j] == '6' or i[j] == '8':
count += 1
print(count)
Try this:
import sys
temp1 = ""
while len(temp1) != 2:
temp1 = input("Enter 2 digits: ")
try:
temp2 = int(temp1)
except ValueError:
print("You did not enter valid input")
sys.exit(1)
lucky = False
if "6" in temp1:
lucky = True
if "8" in temp1:
lucky = True
if ("6" in temp1) and ("8" in temp1):
lucky = False
print("Lucky number: "+str(lucky))
Something like this, probably:
number = ''
while len(number) != 2 or any(ch not in '0123456789' for ch in number):
number = input('Enter a 2-digit positive integer:')
print(f'{number} is {"lucky" if ("6" in number) != ("8" in number) else "not lucky"}')
# or, if you meant to say "exactly one 6 or 8":
print(f'{number} is {"lucky" if len([ch for ch in number if ch in "68"]) == 1 else "not lucky"}')
You could try using the count() method for Strings:
numbers = input().split(' ')
count = 0
for num in numbers:
if num.count('6') > 0:
if num.count('8') > 0:
continue
else:
count += 1
elif num.count('8') > 0:
count += 1
print(count)
this, while not as elegant or efficient, seems to be the correct code for the implied question
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
if ('6' in i and '8' in i):
continue
if i.count('6') > 0 or i.count('8') > 0:
count += 1
print(count)
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)