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)
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)
Hey guys I'm new to python and right now I'm stuck in this:
Get user number input like "98751", then multiply them by order and sum the multiplied result like this:
"9^1" + "8^2" + "7^3" + "5^4" + "1^5"
So far I got here without input:
num = 34532
x = [int(a) for a in str(num)]
print(x)
a=1
multilist = [number * a for number in x]
print(multilist)
then print the result.
Thanks in advance
Edit:
final result for whoever needs it, thanks to Jhanzaib Humayun
num = input("Please enter desired number: ")
sumn = 0
for i in range(len(num)):
sumn+=int(num[i])**(i+1)
s = [int(n)*(i+1) for i,n in enumerate(num)]
print("Multiply result by order:")
print(s)
print("Final result:")
print(sumn)
You can use something like this:
num = input("Input a number: ")
sum = 0
for i in range(len(num)):
sum+=int(num[i])**(i+1)
print(sum)
Edit: You can use something like this if you want to use list comprehension
num = "34532"
s = sum([int(n)**(i+1) for i,n in enumerate(num)])
print(s)
By using enumerate, you get the index i and the element n. Which you can use according to your needs, and lastly sum can be used to sum upp all the elements in the array.
If the number is presented as a string then:
num = '34532'
sum_ = sum(int(n)**i for i, n in enumerate(num, 1))
print(sum_)
Output:
257
Alternative:
sum_ = sum(n**i for i, n in enumerate(map(int, num), 1))
I have written a code which finds unique elements from the list of integers.
def Distinct(arr, n):
for i in range(0, n):
d = 0
for j in range(0, i):
if (arr[i] == arr[j]):
d = 1
break
if (d == 0):
print(arr[i], end=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
print(Distinct(arr, n))
if my given input array is [1,2,2,3,4] where n = 5 i get the output as 1,2,3,4,None but i want the output to be 1,2,3,4
can anyone tell how to fix this ?
Your function Distinct has no return statement so it will always return None. When you call print(Distinct(arr, n)) this is printing the None that is returned. You can simply remove the print() like so:
Distinct(arr, n)
To remove the last comma you can't print a comma on the first iteration, then print the commas before the items. This is because you don't know which item will be the last one.
if d == 0 and i == 0:
print(arr[i], end='')
elif d == 0:
print("," + arr[i], end='')
Try something like this:
def Distinct(arr, n):
lst = []
for i in range(0, n):
for j in range(0, i):
if (arr[i] == arr[j]):
lst.append(arr[i])
break
print(*lst, sep=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
Distinct(arr, n)
So first you compute all the numbers, and only at the end you print them
def silly(n):
"""requires: n is an int > 0
Gets n inputs from user
Prints 'Yes' if the inputs are a palindrome; 'No' otherwise"""
assert type(n) == int and n > 0
for i in range(n):
result= []
elem = input('Enter something: ')
result.append(elem)
print(result)
if isPal(result):
print('Is a palindrome')
else:
print('Is not a palindrome')
If you try running this function, with for example, as n = 3, why doesn't the elem append to the result properly? It keeps printing as new list of results. This messages up my isPal function.
The first line of your for loop replaces your result variable with a new list.
result= []
You should do this before the for loop instead.
Swap these lines:
result = []
for i in range(n):
# ...
Or you will be reassigning result in every iteration.
The issue is that you are redefining result each time.
def silly(n):
"""requires: n is an int > 0
Gets n inputs from user
Prints 'Yes' if the inputs are a palindrome; 'No' otherwise"""
assert type(n) == int and n > 0
result= []
for i in range(n):
elem = input('Enter something: ')
result.append(elem)
print(result)
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:')