i want to make a function that takes a list as an input and return values when there are two of the same elements.The list is sorted.I can't use any loops or recursions is there any way it is possible?
def continuity(lst):
if len(lst)==1:
return 'no'
elif lst[0]==lst[1]:
return 'yes'
else:
return continuity(lst[1:])
this is what i did but it uses recursion.
def continuity(lst):
if len(lst) > 1
if len(lst) == len(set(lst)):
return 'yes'
else:
return 'no'
else:
return 'no'
Create a set for the same & then compare the length:
def continuity(lst):
lst_set = set(lst)
return 'yes' if len(lst_set) == len(lst) and len(lst) != 1 else 'no'
Using counter:
def continuity(lst):
from collections import Counter
occurrences = list(Counter(x).values())
sum = sum(occurrences)
return 'yes' if sum == len(lst_set) and len(lst) != 1 else 'no'
Related
when i try to print this line:
print(perfect_square(0))
i should get True but instead i get a time limit exceeded error and i dont know how to fix it.
i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error
This is my current code:
def perfect_square(n):
s = 1
while s != n:
if s*s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
def perfect_cube(n):
s = 1
while s != n:
if s*s * s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?
def perfect_cube(n):
if n < 1: return False
# ...
I have a sequence print(lcp(["flower","flow","flight", "dog"])) which should return fl. Currently I can get it to return flowfl.
I can locate the instances where o or w should be removed, and tried different approaches to remove them. However they seem to hit syntax issue, which I cannot seem to resolve by myself.
I would very much appreciate a little guidance to either have the tools to remedy this issue my self, or learn from a working proposed solution.
def lcp(strs):
if not isinstance(strs, list) or len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
original = strs[0]
original_max = len(original)
result = ""
for _, word in enumerate(strs[1:],1):
current_max = len(word)
i = 0
while i < current_max and i < original_max:
copy = "".join(result)
if len(copy) and copy[i-1] not in word:
# result = result.replace(copy[i-1], "")
# result = copy[:i-1]
print(copy[i-1], copy, result.index(copy[i-1]), i, word)
if word[i] == original[i]:
result += word[i]
i += 1
return result
print(lcp(["flower","flow","flight", "dog"])) # returns flowfl should be fl
print(lcp(["dog","car"])) # works
print(lcp(["dog","racecar","car"])) # works
print(lcp([])) # works
print(lcp(["one"])) # works
I worked on an alternative which does not be solve removing inside the same loop, adding a counter at the end. However my instincts suggest it can be solved within the for and while loops without increasing code bloat.
if len(result) > 1:
counter = {char: result.count(char) for char in result}
print(counter)
I have solved this using the below approach.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
N = len(strs)
if N == 1:
return strs[0]
len_of_small_str, small_str = self.get_min_str(strs)
ans = ""
for i in range(len_of_small_str):
ch = small_str[i]
is_qualified = True
for j in range(N):
if strs[j][i] != ch:
is_qualified = False
break
if is_qualified:
ans += ch
else:
break
return ans
def get_min_str(self, A):
min_len = len(A[0])
s = A[0]
for i in range(1, len(A)):
if len(A[i]) < min_len:
min_len = len(A[i])
s = A[i]
return min_len, s
Returns the longest prefix that the set of words have in common.
def lcp(strs):
if len(strs) == 0:
return ""
result = strs[0]
for word in strs[1:]:
for i, (l1, l2) in enumerate(zip(result, word)):
if l1 != l2:
result = result[:i]
break
else:
result = result[:i+1]
return result
Results:
>>> print(lcp(["flower","flow","flight"]))
fl
>>> print(lcp(["flower","flow","flight", "dog"]))
>>> print(lcp(["dog","car"]))
>>> print(lcp(["dog","racecar","car"]))
>>> print(lcp([]))
>>> print(lcp(["one"]))
one
>>> print(lcp(["one", "one"]))
one
You might need to rephrase your goal.
By your description you don't want the longest common prefix, but the prefix that the most words have in common with the first one.
One of your issues is that your tests only test one real case and four edgecases. Make some more real examples.
Here's my proposition: I mostly added the elif to check if we already have a difference on the first letter to then discard the entry.
It also overwrites the original to rebuild the string based on the common prefix with the next word (if there are any)
def lcp(strs):
if not isinstance(strs, list) or len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
original = strs[0]
result = ""
for word in strs[1:]:
i = 0
while i < len(word) and i < len(original) :
if word[i] == original[i]:
result += word[i]
elif i == 0:
result = original
break
i += 1
original = result
result = ""
return original
print(lcp(["flower","flow","flight", "dog"])) # fl
print(lcp(["shift", "shill", "hunter", "shame"])) # sh
print(lcp(["dog","car"])) # dog
print(lcp(["dog","racecar","car"])) # dog
print(lcp(["dog","racecar","dodge"])) # do
print(lcp([])) # [nothing]
print(lcp(["one"])) # one
monotonic_function
input: list
output : returns alist of Booleans(True/False) for example :
sequence_monotonicity([1,2,3,4,5,6]) return [True,True,False,False]
sequence_monotonicity([1,2,2,3]) return [True,False,False,False]
sequence_monotonicity([1,0,-1,1]) return [False,False,False,False]
the rules are :
I cant use all , any / or import anything(like numpy)
if a(n-1) <= a(n) is correct it returns True into the first place of list, else return: False
if (an-1) < a(n) is correct it returns True into the second place of the list, else : returns false
if a(n-1) >=a(n) is correct it returns True into the 3rd place of the list, else: returns: False
if a(n-1) > a(n) is correct it returns True into the 4th place of the list, else : returns False
i tried to do it without numpy "thedumbest" way possible but i dont get correct answers
this is what i tried :
def true_false_checker(x):
if False in x:
return False
else:
return True
def sequence_monotonicity(l):
z =[]
x = []
for i in range(1,len(l)):
if l[i-1] <= l[i]:
x.append(True)
else:
x.append(False)
if true_false_checker(x) == True:
z.append(True)
else:
z.append(False)
if l[i-1] < l[i]:
x.append(True)
else:
x.append(False)
if true_false_checker(x) == True:
z.append(True)
if l[i-1] >= l[i]:
x.append(True)
else:
x.append(False)
if true_false_checker(x) == True:
z.append(True)
if l[i-1] > l[i]:
x.append(True)
else:
x.append(False)
if true_false_checker(x) == True:
z.append(True)
return z
'''
What about this?
def seq_mon(l):
r = [True]*4
for x in [a-b for a,b in zip(l[:-1],l[1:])]:
r[0] &= x<=0
r[1] &= x<0
r[2] &= x>=0
r[3] &= x>0
return r
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Output:
Enter number33
None -> (I want this to be 'True')
Your code reaches no return statement for the break case. You can return from there though:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
return "False"
else:
return "True"
else:
return "False"
This can be simplified as you are returning from every if-block:
def acc_p(num):
if num <= 1:
return "False"
for i in range (2, int(num/2)+1):
if num % i == 0:
return "False"
return "True"
Ultimately you would probably want to return bool values. And with the short-circuiting pattern in your loop, you can use any:
def acc_p(num):
if num <= 1:
return False
return not any(num % i == 0 for i in range (2, int(num/2)+1))
It returns None when the for loop breaks, meaning the else statement will never be met:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break # If it breaks here...
else:
return "True" # This will never be met
else:
return "False" # And of course this one will never be met
x = int(input("Enter number"))
c = acc_p(x)
print(c)
What you'll want to do is return another value under the inner else statement:
def acc_p(num):
if num > 1:
for i in range (2,int(num/2)+1):
if num % i == 0:
break
else:
return "True"
return "False"
else:
return "False"
x = int(input("Enter number"))
c = acc_p(x)
print(c)
Test run:
Enter number7
True
Again:
Enter number33
False
(Note that 33 is not a prime number.)
Write a python function, check_anagram() which accepts two strings and returns True, if one string is an anagram of another string. Otherwise returns False.
The two strings are considered to be an anagram if they contain repeating characters but none of the characters repeat at the same position. The length of the strings should be the same.
Note: Perform case insensitive comparison wherever applicable.
This is my code:
def check_anagram(data1,data2):
first = data1.lower()
second = data2.lower()
d1 = []
d2 = []
for i in range(0, len(first)):
d1.append(first[i])
for i in range(0, len(second)):
d2.append(second[i])
for_check1 = sorted(d1)
for_check2 = sorted(d2)
if (for_check1 != for_check2):
return False
count = 0
if (len(d1) == len(d2)):
for i in d1:
for j in d2:
if(i == j):
a = d1.index(i)
b = d2.index(j)
if(a == b):
return False
else:
count += 1
if(count == len(first)):
return True
else:
return False
print(check_anagram("Schoolmaster", "Theclassroom"))
The output I am getting is "False"
Although this program is giving relevant output for string values like {silent, listen}{Moonstarrer, Astronomer}{apple, mango} but not for the above two strings(in code)
What cases am I missing in this code?? How to rectify this thing?
Your function could be simplified as:
def check_anagram(data1, data2):
data1 = data1.lower()
data2 = data2.lower()
if sorted(data1) != sorted(data2):
return False
return all(data1[i] != data2[i] for i in range(len(data1)))
Which actually works for the case you specified.
your code is correct just write len(second) instead of count.
def check_anagram(data1,data2):
first = data1.lower()
second = data2.lower()
d1 = []
d2 = []
for i in range(0, len(first)):
d1.append(first[i])
for i in range(0, len(second)):
d2.append(second[i])
for_check1 = sorted(d1)
for_check2 = sorted(d2)
if (for_check1 != for_check2):
return False
count = 0
if (len(d1) == len(d2)):
for i in d1:
for j in d2:
if(i == j):
a = d1.index(i)
b = d2.index(j)
if(a == b):
return False
else:
count += 1
if(len(second) == len(first)):
return True
else:
return False
print(check_anagram("Schoolmaster", "Theclassroom"))
This program of mine is clearing all possible test cases.
def check_anagram(data1,data2):
data1=data1.lower()
data2=data2.lower()
if(len(data1)==len(data2)):
if(sorted(data1)!=sorted(data2)):
return False
else:
if(data1[i]!=data2[i] for i in range(len(data1))):
return True
else:
return False
else:
return False
print(check_anagram("eat","tea"))