number = -5
case number
when number < 0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
end
...
I expected it to return "Please enter a number greater than 0", but instead it returned nil. Why is that? How can I check if the number is less than 0?
When you give a variable to case, it's compared against each when clause with the === method. The first === to return true will be the branch that's executed.
In your case, number < 0 is evaluating to true, and -5 === true is false!
What you want to do is either leave the number off of the case, and make all of the when clauses boolean:
case
when number < 0
return "Please enter a number greater than 0."
when number.between?(0, 1)
return false
when number == 2
return true
end
Or leave the number on, but make all of the whens values that you can compare against:
case number
when -Float::INFINITY..0 # or (-1.0/0)..0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
end
when number < 0 will be the same as when true in this case, because number is indeed less than zero, and the when will not be entered since -5 != true.
You could try
when (-1.0/0)..0 # negative Infinity to 0
Or, if you're using 1.9.2 or above:
when -Float::INFINITY..0
Related
def check_prime(x):
for i in range(2,x):
if x%i==0:
return False
else: return True
Why is this code not working properly. This code returns true even for some non prime numbers. eg:- 9 , 25 ,...
You are returning True right away when you find one number that doesn't divide x, which is wrong. You're supposed to return True when all number greater or equal to 2 and less than x doesn't divide x. To fix this, remove the else code, and return True after the for loop is over.
Here's the full code:
def check_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
I am trying to write a function that returns true or false if a given string has exactly 6 consecutive characters with the same value. If the string has more or less than 6, it will return false:
I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations
Two example runs are shown below:
Enter a string: 367777776
True
Enter a string: 3677777777776
False
Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')
I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I
def consecutive(x):
storage= ' '
acc=0
count=0
for s in x:
storage+= str(ord(s)) + ' '
acc+=ord(s)
if acc == acc:
count+=1
for s in x-1:
return count
My intention is to compare the previous character's ASCII code to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.
Can anyone assist me?
That's a pretty good start!
A few comments:
Variables storage and acc play the same role, and are a little more complicated than they have to be. All you want to know when you arrive at character s is whether or not s is identical to the previous character. So, you only need to store the previously seen character.
Condition acc == acc is always going to be True. I think you meant acc == s?
When you encounter an identical character, you correctly increase the count with count += 1. However, when we change characters, you should reset the count.
With these comments in mind, I fixed your code, then blanked out a few parts for you to fill. I've also renamed storage and acc to previous_char which I think is more explicit.
def has_6_consecutive(x):
previous_char = None
count = 0
for s in x:
if s == previous_char:
???
elif count == 6:
???
else:
???
previous_char = ???
???
You could use recursion. Loop over all the characters and for each one check to see of the next 6 are identical. If so, return true. If you get to the end of the array (or even within 6 characters of the end), return false.
For more info on recursion, check this out: https://www.programiz.com/python-programming/recursion
would something like this be allowed?
def consecF(n):
consec = 1
prev = n[0]
for i in n:
if i==prev:
consec+=1
else:
consec=1
if consec == 6:
return True
prev = i
return False
n = "12111123333221"
print(consecF(n))
You can try a two pointer approach, where the left pointer is fixed at the first instance of some digit and the right one is shifted as long as the digit is seen.
def consecutive(x):
left = 0
while left != len(x):
right = left
while right < len(x) and x[right] == x[left]:
right += 1
length = (right - 1) - left + 1 # from left to right - 1 inclusive, x[left] repeated
if length == 6: # found desired length
return True
left = right
return False # no segment found
tests = [
'3677777777776',
'367777776'
]
for test in tests:
print(f"{test}: {consecutive(test)}")
Output
3677777777776: False
367777776: True
You should store the current sequence of repeated chars.
def consecutive(x):
sequencechar = ' '
repetitions = 0
for ch in x:
if ch != sequencechar:
if repetitions == 6:
break
sequencechar = ch
repetitions = 1
else:
repetitions += 1
return repetitions == 6
If I could, I would not have given the entire solution, but this still is a simple problem. However one has to take care of some points.
As you see the current sequence is stored, and when the sequence is ended and a new starts, on having found a correct sequence it breaks out of the for loop.
Also after the for loop ends normally, the last sequence is checked (which was not done in the loop).
The below method should return true if an integer is a prime number and false if it is not. Can someone please explain to me how the placement of true is correct? I'm having hard time understanding how each closure (end) is closing each block and why placing true in the location it's at is correct.
This was for a lab I am completing for a course. I know the code works, but I'm unsure why.
def prime?(value)
if value <= 1 || value == 0 || value == 1
return false
elsif
(2..value - 1).each do |i|
if value % i == 0
return false
end
end
end
true # <= need explanation
end
prime? should return true for prime integers and false for non-prime integers.
I've reformatted this code to make the end closure in good indent:
def prime?(value)
if value <= 1 || value == 0 || value == 1
return false
elsif
(2..value - 1).each do |i|
if value % i == 0
return false
end
end
end
true # <= need explanation
end
I guess you've familiar with the if part, while having a hard time with elsif and the ending ture.
Ruby methods will return its last expression's value if there is no explicit return. So that the last true will be returned if and only if we missed the if branch and went through the elsif branch without activate return false.
When will this happen? If value is a prime number, of course it will fall into elsif branch first, then check each number less than it, see if it is divisible by any of them.
Once all trials fail, the elsif branch ends, we will meet the last true expression.
How to find prime numbers?
Prime numbers are the numbers that are bigger than one, and are divisible only by themselves and one. One way to determine whether or not a number is a prime number is as follows:
->if the number < 2, then return False
->if the number is 2, then return True
->for each value of i, where i >=2 and i < number:
if the number is divisible by i, then return False
->return True
My current code:
def is_prime(number):
if number == 2:
return True
elif number < 2:
return False
else:
for i in range(2, number):
if number % i == 0:
return False
else:
return True
def main():
print(is_prmie(1))
print(is_prmie(4))
print(is_prmie(7))
Some syntax problems I don't know how to solve.
Can someone please help?
Thanks TA!
I suggest the following:
from math import sqrt
def is_prime(x):
if x < 2:
return False
if x % 2 == 0:
return x == 2
i = 3
while i <= sqrt(x):
if x % i == 0:
return False
i += 2
return True
Things to note:
The only even prime is 2. The loop is restricted to odd numbers.
Only factors up to and including the square root must be tested. Because if x = y * z and y ≥ sqrt(x) then z ≤ sqrt(x)
Only one return statement in the loop. You can exit early on a non prime, but you must complete the loop to be sure the number is prime.
You need to call the main() and write is_prime() correctly.
def is_prime(number):
if number == 2:
return True
elif number < 2:
return False
else:
for i in range(2, number):
if number % i == 0:
return False
else:
return True
def main():
print(is_prime(1))
print(is_prime(4))
print(is_prime(7))
main()
Spelling of is_prime at the time of method call is wrong. Also, you haven't mke a call to the method main at the end.
Small improvement:
for i in range(2, number):
this line can be as below as we don't need to check divisibility of the number after its half:
for i in range(2, (number/2)):
e.g. for checking 24 is prime or not, we need to check only upto 12 because it will never be divisible by number greater than 12.
<?php
// PHP code to check wether a number is prime or Not
// function to check the number is Prime or Not
function primeCheck($number){
if ($number == 1 || $number == 2 || $number % 2 !== 0) {
echo "Prime";
}
else if ($number % 2 == 0)
{
echo "Not Prime";
}
}
echo primeCheck(5);
For instance:
8 > 10 = true, since 8 is divisible by 2 three times and 10 only once.
How can I compare two integers from any range of numbers? Are the modulo and divide operator capable of doing this task?
Use binary caculate to judge it
def devided_by_two(i)
return i.to_s(2).match(/0*$/).to_s.count('0')
end
To make integer divisibility by 2, just transcode it to binary and judge how many zero from end of banary number. The code I provide can be more simple I think.
Yes, they are capable. A number is even if, when you divide it by two, the remainder is zero.
Hence, you can use a loop to continuously divide by two until you get an odd number, keeping a count of how many times you did it.
The (pseudo-code) function for assigning a "divisibility by two, continuously" value to a number would be something like:
def howManyDivByTwo(x):
count = 0
while x % 2 == 0:
count = count + 1
x = x / 2 # make sure integer division
return count
That shouldn't be too hard to turn into Ruby (or any procedural-type language, really), such as:
def howManyDivByTwo(x)
count = 0
while x % 2 == 0
count = count + 1
x = x / 2
end
return count
end
print howManyDivByTwo(4), "\n"
print howManyDivByTwo(10), "\n"
print howManyDivByTwo(11), "\n"
print howManyDivByTwo(65536), "\n"
This outputs the correct:
2
1
0
16
Astute readers will have noticed there's an edge case in that function, you probably don't want to try passing zero to it. If it was production code, you'd need to catch that and act intelligently since you can divide zero by two until the cows come home, without ever reaching an odd number.
What value you return for zero depends on needs you haven't specified in detail. Theoretically (mathematically), you should return infinity but I'll leave that up to you.
Notice that you will likely mess up much of your code if you redefine such basic method. Knowing that, this is how it's done:
class Integer
def <=> other
me = self
return 0 if me.zero? and other.zero?
return -1 if other.zero?
return 1 if me.zero?
while me.even? and other.even?
me /= 2
other /= 2
end
return 0 if me.odd? and other.odd?
return -1 if me.odd?
return 1 if other.odd? # This condition is redundant, but is here for symmetry.
end
end