Appending into a list - python

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)

Related

split the number given by user so RHS= LHS

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)

Finding unique elements from the list of given numbers

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

How to add user input integers to array?

Declare an empty array
Let the user add integers to this array, over and over
Stop when the user enters -1
Do not add -1 to the array
Print the array
So far my code below:
A=[]
while True:
B = int(input("Input a continuous amount of integers"))
A = [B]
print(A)
if B == -1:
break
else:
continue
In Python, we call the this [] datatype as list. To append item into a list, you can do A.append(B)
A = []
while True:
B = int(input("Input a continuous amount of integers"))
if B == -1:
break
else:
A.append(B) # modify this line
print(A)
You need to check if user input is -1 before appending it to the array and print it in the if block, append it in the else block.
A=[]
while True:
B = int(input("Input a continuous amount of integers"))
if B == -1:
print(A)
break
else:
A.append(B)

Why do I get correct output for palindromes but no output for regular numbers?

I'm trying to check if a number is a palindrome or not. To do that I'm counting the number of times the kth element is equal to the (n-k)th element. If that number is equal to the length of the string , then it is a palindrome. I do get correct output for palindromes but absolutely no output(k) when the number is not a palindrome. Code for reference :
T = int(raw_input())
L = []
for i in range(0,T):
alpha = int(raw_input())
L.append(alpha)
print L
for i in range(0,len(L)):
L[i] = str(L[i])
print L
for i in range(0,len(L)):
k = 0
while k < len(L[i]) :
if L[i][k] == L[i][len(L[i])-(k)-1]:
k = k + 1
print k
Don't use such complex logic. Use simple pythonic [::-1] to reverse the string.
In [1]: a = 1234554321
In [2]: def pal(a):
...: if a == a[::-1]:
...: return True
...: else:
...: return False
...:
In [3]: pal(str(a))
Out[3]: True
Maybe you can try something more succint. How about this:
def is_palindrome(n):
return str(n) == str(n)[::-1]
n = int(raw_input("Enter a number: "))
print(is_palindrome(n))
You should listen to the advice from the other answers on how to properly solve this.
However, no one answered the actual question you asked: Why do I get correct output for palindromes but no output for regular numbers?
Take a look at this while loop:
k = 0
while k < len(L[i]) :
if L[i][k] == L[i][len(L[i])-(k)-1]:
k = k + 1
If L is not a palindrome, the condition in the if sentence evaluates to false, and k is never incremented. So k remains zero, and the condition in the while loop is always true.
You've got yourself an infinite while loop!
My advice for you is to go through the basics of python first. Moreover, have a look on python3. It's so easy. Your algorithm is not bad and its implementation is not done properly. Here is what you want to do. (it's in python3)
L = input('Enter a word: ')
print ('Your word is:', L)
# As per your algorithm
count = 0
size = len(L)
for i in enumerate(L):
# since if the size is 7, then the last index will be 6(= 7-1)
if L[i] == L[size -1 -i]:
count += 1
if count == size:
print(L, 'is palindrome')
else:
print(L, 'is not palindrome')

Linear Search Code in python

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)

Categories