+ 4
Trouble with Has22 problem.
Problem: Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. E.g: has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False My attempt: (Doesn't pass all conditions) https://code.sololearn.com/clKEVJ4Tgu11/?ref=app What could be the mistake? Also I believe that python has a potential to do this task in one line? So anyone expert in oneliners?
19 Antworten
+ 9
# Created by IQ >= 80; >> False
lst1 = [3,5,5,6]
lst2 = [3,2,2,7]
def func(nums):
for i in range(len(nums)-1):
if nums[i] ==2:
if nums[i] == nums[i+1]:
return True
return False
print(func(lst1))
print(func(lst2))
+ 3
It is wrong solution. Your func return True if it will receive value equal to 2. but you need to find two next to each other. Use indexes of value 2.
+ 3
Or iter list and check for element[i] == element[i+1] == 2
And find a way to avoid indexerror
+ 3
We find only num to or any mun next to each other?
+ 3
def fun(a): return True if a[:2] == [2, 2] else fun(a[1:]) if a[2:] else False
print(fun(a))
+ 1
lst1 = [3,2,7,6]
lst2 = [3,2,2,7]
def func(nums):
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
print(func(lst1))
print(func(lst2))
+ 1
My english not so good. I not understand problem at full.
+ 1
IQ >= 80; >> False No one. It simple and have a lot different solution. Good luck to learn!
+ 1
IQ >= 80; >> False
This is close, but not quite what you need.
I still striggle with one-liners
[print(lst[i]==lst[i+1]) if lst[i]==2 else '' for i in range(len(lst)-1)]
+ 1
IQ >= 80; >> False
Let me know if this works
[print('true') if (lst[i]==2 and lst[i+1]==2) else '' for i in range(len(lst)-1)]
+ 1
Rik Wittkopp Cool. But somehow can you convert it to return statement. Because the test support only function def
+ 1
IQ >= 80; >> False
I will have a think.
🤔
+ 1
IQ >= 80; >> False
I can get the one-liner to work with the def, & I changed the output to reflect True or False.
Is it a neccessity to use return?
Try this instead
def twos(x):
[print (True) if (x[i]==2 and x[i+1]==2) else False for i in range(len(x)-1)]
(twos(lst))
+ 1
Rik Wittkopp website doesn't allow printing.
https://codingbat.com/prob/p119308
+ 1
Valmob101 Thanks buddy, you rock!!
+ 1
def func(nums):
i = 0
while i+1 < len(nums):
if nums[i] == nums[i+1] == 2:
return True
break
else:
i+=1
return False
print(func([4,1,2,2]))
0
Rik Wittkopp Thanks for the solution. I think this passed 90% of the condition. But it doesn't passed some hidden conditions.
0
Rik Wittkopp How to include only 2. This types of arrays didn't passed: [1,5,5,3]
0
Rik Wittkopp thanks, now it works.
But how much brain cells do we need to do this in one line?