lucky sevens, sum of 3 consecutive numbers in array == 7 - python

Write a function lucky_sevens(numbers), which takes in an array of
integers and returns true if any three consecutive elements sum to 7.
Why isn't this producing an output of True? The last 3 values sum = 7.
def lucky_sevens(numbers):
x, y = 0, 3
sum_of_numbers = sum(numbers[x:y])
while (sum_of_numbers != 7) and (y < len(numbers)):
x = x + 1
y = y + 1
if sum_of_numbers == 7:
return True
else:
return False
print(lucky_sevens([1,2,3,4,5,1,1]))

The problem that when the function first gets called the sum_of_numbers variable gets assigned the value of the sum of the first 3 values in the list, and never gets updated with the new x,y values, you'd probably want to create a callback function to achieve that behavior.
As it stands, you'll need to move the sum statement into the while loop so the sum gets updated with the new x,y values:
def lucky_sevens(numbers):
result = False
x, y = 0, 3
while (y <= len(numbers)):
if sum(numbers[x:y]) == 7:
result = True
break
x += 1
y += 1
return result
print(lucky_sevens([1,2,3,4,5,1,1]))

How about something as simple as
def lucky_sevens(numbers):
for x in range(len(numbers) - 2):
if sum(numbers[x:x+3]) == 7:
return True
return False
Or with your original code, just cleaned up a little bit.
def lucky_sevens(numbers):
if len(numbers) < 3:
return False
x, y = 0, 3
sum_of_numbers = sum(numbers[x: y])
while sum_of_numbers != 7 and y < len(numbers):
x += 1
y += 1
sum_of_numbers = sum(numbers[x: y])
if sum_of_numbers == 7:
return True
return False
Your error came in your while loop. As you were looping, sum_of_numbers was staying constant. Instead, you have to update it for every new x and y within the while loop.
Also some repetitive stuff like else: return False, can be simplified to return False, as it can only get to that line if sum_of_numbers == 7 is False.
Finally x = x + 1 can be written in the more common shorthand x += 1, the same going with y = y + 1.

This ought to do the trick:
def lucky_sevens(numbers):
if len(numbers) < 3:
return False
return 7 in [sum(numbers[i:i+3]) for i in range(0, len(numbers)-2)]
print(lucky_sevens([1,2,3,4,5,1,1]))
# True
The list comprehension will move through your list 3 numbers at a time and compute the sum of each set of three integers. If 7 is in that list, then there are 3 consecutive numbers that sum to 7. Otherwise, there isn't.
The one caveat is that doing this sort of list comprehension requires that the list have more than 3 elements in it. That's why the if statement is there.
If you wanted to use your original code though, you just have to make a few adjustments. Your logic was all there, just needs a little cleaning.
def lucky_sevens(numbers):
x, y = 0, 3
sum_of_numbers = sum(numbers[x:y])
while (sum_of_numbers != 7) and (y < len(numbers)):
x = x + 1
y = y + 1
sum_of_numbers = sum(numbers[x:y])
if sum_of_numbers == 7:
return True
else:
return False
You simply needed to redo the sum within your while loop. That way, sum_of_numbers updates with each loop and each new selection of indices.

This code returns the consecutive elements in the Array whose sum is 7 and index of initial element.
function lucky_seven(arr){
let i=0;
let lastIndex = 0;
if(arr.length < 3){
return false;
}
while(i <= lastIndex){
let sum = 0;
lastIndex = i + 3;
let subArr = arr.slice(i,lastIndex);
if(subArr.length === 3) {
sum = subArr.reduce((acc, cur) => acc + cur);
if(sum === 7){
return {
subArr: subArr,
index: i
};
}
i++;
} else{
return false;
}
}
}
lucky_seven([3,2,1,4,2])

I just used this:
def lucky_sevens(numbers):
x = 0
y = False
for i in numbers:
if i == 7:
x += 7
if x == 21:
y = True
else:
x = 0
return y

There are some very interesting responses here. Thought I will share my work as well.
def lucky_seven(num_list):
if len(num_list) < 3: return False
return any([True if sum(num_list[i:i+3]) == 7 else False for i in range(len(num_list)-2)])
print ('lucky seven for [1,2,3] is :',lucky_seven([1,2,3]))
print ('lucky seven for [3,4] is :',lucky_seven([3,4]))
print ('lucky seven for [3,4,0] is :',lucky_seven([3,4,0]))
print ('lucky seven for [1,2,3,4,5,1,1] is :',lucky_seven([1,2,3,4,5,1,1]))
print ('lucky seven for [1,2,3,4,-2,5,1] is :',lucky_seven([1,2,3,4,-2,5,1]))
The output of this will be:
lucky seven for [1,2,3] is : False
lucky seven for [3,4] is : False
lucky seven for [3,4,0] is : True
lucky seven for [1,2,3,4,5,1,1] is : True
lucky seven for [1,2,3,4,-2,5,1] is : True

def f(l):
if len(l) < 3:
return False
for i in range(len(l)):
if i+3 <= len(l):
if sum(l[i:i+3]) == 7:
return True
continue
else:
return False

Related

Palindrome number in python (leetcode)

class Solution:
def isPalindrome(self, x: int) -> bool:
# If x is a negative number it is not a palindrome
# If x % 10 = 0, in order for it to be a palindrome the first digit should also be 0
if x < 0 and x%10 == 0):
return False
reversedNum = 0
while x > reversedNum:
reversedNum = reversedNum * 10 + x % 10
x = x // 10
# If x is equal to reversed number then it is a palindrome
# If x has odd number of digits, dicard the middle digit before comparing with x
# Example, if x = 23132, at the end of for loop x = 23 and reversedNum = 231
# So, reversedNum/10 = 23, which is equal to x
return True if (x == reversedNum or x == reversedNum // 10) else False
This is my code which is giving wrong output for 660,
Expected output : False
My output : True
Can someone tell me how to correct this.
reversedNum = 0
Num=x
while x > 0:
reversedNum = reversedNum * 10 + x % 10
x = x // 10
return True if (Num == reversedNum) else False
You don't really need an explicit check for a negative number because the while loop (in the following code) will not be entered and the return value will be an equality test between zero and some negative number - which is obviously False.
So:
def ispalindrome(x):
n = x
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r == x
if you convert the number to a string is very simple. you only need to check that the string written backwards is the same
def ispalindrome(x):
return str(x) == str(x)[::-1]
ispalindrome(23132)
>>> True

Palindrome tester gives False for 11 but returns True for 121

Here is my code:
def isPalindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
rev = (rev*10 + x % 10)
x /= 10
return x == rev or x == rev/10
x = 11
print(isPalindrome(x))
Why does this code not give the desired results for all positive integer inputs?
Your code has two problems.
The first is that x /= 10 performs a floating point divide, so 11 /= 10 is 1.1, not 1. Integer divide in Python is //.
The second is that you don't want to keep looping while x > rev but rather while x > 0 because you want to reverse every digit of your number. When x > 0, you still have digits in x that you haven't added to the reversed value. The accumulated portion of the reversed value being greater than the part of the answer still to be processed doesn't mean anything.
So here's a working version of your code, at least for your two test cases and a few more I did. I didn't do an exhaustive test.
def isPalindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
y = x
while y > 0:
rev = (rev*10 + y % 10)
y //= 10
return x == rev or x == rev/10

Check if a number is a palindrome without changing it into string

I'm having trouble with this problem that simply return True of False if a number n, is a palindrome.
Note: wherever I have a ____ indicates where there is a blank that needs to be filled in. There are 2 blank spaces.
def is_palindrome(n):
x, y = n, 0
f = lambda: ____
while x > 0:
x, y = ____ , f()
return y == n
I've spent about an hour on this. I've found out that putting x//10 in the second blank space will allow the function to iterate over the number of digits in n. It then comes down to the function f.
Ideally, every time it is called, it should add the last digit in n to a new number, y. Thus, if n = 235, the while loop will iterate 3 times, and each time f() is called, it should add 5, 3, and 2, to the value y.
Here's the logic: (y * 10) + x % 10
def is_palindrome(n):
x, y = n, 0
f = lambda: (y * 10) + x % 10
while x > 0:
x, y = x//10 , f()
return y == n
print(is_palindrome(123454321))
# True
print(is_palindrome(12))
# False
y*10 moves the current y to the left by 1 digit, and x%10 adds the last digit.
print(is_palindrome(235))
# False
Pre-iteration: x = 235, y = 0
First iteration: x = 23, y = 5
Second iteration: x = 2, y = 53
Third iteration: x = 0, y = 532
Excellent solution, mate! Maybe one little suggestion. Your solution iterates over all n digits, but you have only to iterate n/2 digits. Moreover, you can handle negative values directly because they aren't palindromes.
def is_palindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
head, tail = x, 0
while head > tail:
head, tail = head // 10, tail * 10 + head % 10
# When the length is an odd number, we can get rid of the middle digit by tail // 10
return head == tail or head == tail // 10
Time complexity: O(log(n)) because we divided 10 in every iteration
Space complexity: O(1)
Below is the code which has 11510 leetcode test cases and it is accepted
check a number is palindrome without converting it into string
var isPalindrome = function(x) {
let list=[]
if(x<0){
return false
}
while(x>0){
if(x<10){
list.push(parseInt(x))
break;
}
let num=parseInt( x%10)
list.push(num)
x=parseInt( x/10)
}
for(var i=0;i<list.length/2;i++){
if(list[i]!=list[list.length-(i+1)]){
return false
}
}
return true
};
thanks,

Function to evaluate validity of numerical palindrome for floating point numbers using Python

So there are plenty of algorithms to evaluate whether an int is a palindrome, i.e.
def ReverseNumber(n, partial=0):
if n == 0:
return partial
return ReverseNumber(n // 10, partial * 10 + n % 10)
or this one:
def isPalindrome(x):
if (x < 0):
return False
div = 1
while (x / div >= 10):
div *= 10
while (x != 0):
l = x / div
r = x % 10
if (l != r):
return False
x = (x % div) / 10
div /= 100
return True
However what I'd like to do is assess whether a number such as 1.01 or 22.22 and so on, whether such numbers are themselves palindromes.
How could either of those algorithms above be adapted to function for floats in addition to ints?
This is the code I'm using to call it:
import sys
# This method determines whether or not the number is a Palindrome
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True
if '__main__' == __name__:
trial = int(sys.argv[1])
# check whether we have a Palindrome
if isPalindrome(trial):
print("It's a Palindrome!")
The simplest thing to do is just convert the number to a string, then compare characters from the ends to the middle. The string conversion is less expensive than repeated multiplications and divisions.
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True

Integer Spacing (python)

I'm trying to do is determine if the inputs(integers) have even difference between them
Example if my inputs are:
1
3
5
it will then print True
This is my current code:
x = int(raw_input (""))
y = int(raw_input (""))
z = int(raw_input (""))
x = int(x)
y = int(y)
z = int(z)
list_a = [x,y,z]
if list_a[1] == list_a[0]+2 and \
list_a[2] == list_a[1]+2:
print True
else:
print 'False'
is there an easier way that i can cover all even range
ex: if the inputs are 5, 10 and 15 or 10, 20, 30?
you can compare the difference between the items in the list.
For a list with 3 items:
if list_a[2] - list_a[1] == list_a[1] - list_a[0]:
print True
else:
print False
If the list has more items:
function isEvenlyDistributed(list){
for(idx = 2; idx < list.size; idx++):
if(list[idx] - list[idx-1] != list[idx-1] - list[idx-2])
return false;
return true; /* never returned false, so true at the end */
}
edit: python tag was added. This is pseude-code, so you should convert it to python :)

Categories