Finding Cyclops Numbers in Python - python

I am working on a problem in which I need to return True or False after checking to see whether a number is a cyclops number or not. A cyclops number is made up of odd number of digits, consists of only one zero and that zero is located in the middle. Here's what I have so far:
def is_cyclops(n):
strNum = str(n)
for i, el in enumerate(strNum):
if(len(strNum) % 2 == 0):
return False
else:
# find middle number is zero
# no other zeros exist
# return True
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False
How can I find the median number (without using numpy) & ensure it is a zero, and it is the only zero that exists in that number?

This worked for me:
def is_cyclops(num: int) -> bool:
str_ = str(num)
if not len(str_) % 2:
return False
if not str_.count('0') == 1:
return False
mid_index = len(str_) // 2
if str_[mid_index] == '0':
return True
return False
print(
is_cyclops(0),
is_cyclops(101),
is_cyclops(1056),
is_cyclops(675409820)
)
Output:
True True False False

As it looks like you've had a good attempt here, I'll help out.
def is_cyclops(n):
strNum = str(n)
if(len(strNum) % 2 == 0):
return False
else:
middle_index = len(strNum)//2
if strNum[middle_index] != "0": return False # find middle number is zero
if strNum.count("0") > 1: return False # no other zeros exist
return True
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False

Related

CS50P PSETS 2, Vanity plates

I'm having some issues with the psets 2 of cs50p, precisely I'm talking about the "Vanity Plates" problem, where I fulfilled all requests except one, which said:
“Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.” Can you help me? Thank's
this is the code I wrote so far:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s.isalnum() | s[:2].isalpha() | 2 < len(s) < 6 | :
else:
return False
main()
you have to consider all the cases one by one, this is how I solved it:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if len(s) < 2 or len(s) > 6:
return False
elif not s[0].isalpha() or not s[1].isalpha():
return False
elif checkFirstZero(s):
return False
elif checkMiddleZero(s):
return False
elif last(s):
return False
elif worng(s):
return False
return True
def last(s):
isAlp = False
isNum = False
for w in s:
if not w.isalpha():
isNum = True
else:
if isNum:
return True
return False
def checkCuntuNNumber(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
def checkMiddleZero(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
else:
return False
def checkFirstZero(s):
for w in s:
if not w.isalpha():
if int(w) == 0:
return True
else:
return False
def worng(s):
for w in s:
if w in [" ", ".", ","]:
return True
return False
main()
This is how I did it. I am sure there is an easier way to do it out there but hopefully this helps :)
characters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numbers = ['1','2','3','4','5','6','7','8','9','0']
def main ():
plate = (input ("Plate: ")).upper()
if is_valid(plate):
print ('Valid')
else:
print ('Invalid')
def is_valid (s):
#Check whether length is between 2 and 6 included
if len(s) < 2 or len(s) > 6:
return False
elif char_check(s):
return False
elif char_start(s):
return False
elif zero_check(s):
return False
elif alpha_follow_check (s):
return False
else:
return True
#Check for valid characters
def char_check(s):
for i in s:
if not (i in characters or i in numbers):
return True
#Check whether first two are letters
def char_start (s):
for i in s[:2]:
if not i in characters:
return True
#Check if zero is first number listed
def zero_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_present = 0
zero_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i == '0':
zero_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [0:zero_position]:
if i in numbers:
number_present = 1
if number_present == 0:
return True
else:
return False
#Check alphabet follows numbers
def alpha_follow_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i in numbers:
number_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [number_position:length_string]:
if i in characters:
return True
else:
return False
main ()
idk if will help, but the part that i've had the most difficulty in this problem was: "Numbers cannot be used in the middle of a plate; they must come at the end, AAA22A would not be acceptable", then i learned that you can create a full list from the plate that the user inputed, and how to actually use it, with the:
ls = list(s)
for i in range(len(ls)):
After that, we check when the first number appears. "if == '0'" ,then returns False to the function.
After that, if the first number isn't a 0, the program checks if the next item in that list is letter, and, if it is, also return False.
i < len(ls) -1 => this part guarantee that the program will not run in the last item of the list
ls[i+1].isalpha() => and this part check that, if the item on the list was a number, and then the next item is a letter, it returns False
I hope it helps someone, i've spend a lot of time trying to figure it out what to do, and then reached this solution: "for i in range(len(ls))".
Now my code is complete and working.
My code:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if not s.isalnum():
return False
elif len(s) < 4 or len(s) > 7:
return False
elif s[0].isdigit()or s[1].isdigit():
return False
elif s[-1].isalpha() or s[-2].isalpha():
return False
else:
ls = list(s)
for i in range(len(ls)):
if ls[i].isdigit():
if ls[i] == '0':
return False
elif i < len(ls) -1 and ls[i+1].isalpha():
return False
else:
return True
main()

Python: Why donnot I get a result in the terminal

Python: Why don't I get a result in the terminal
def is_even(number):
if number % 2 == 0:
return True
return False
is_even(10)
You need to print the output of the function. You also need to create the function.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(10)) #True
print(is_even(7)) #False

Python Perfect Number

In this Python Question, I should get False if the the number is not perfect. instead, I'm getting "None". What should I change?
def perfect(number):
sum = 0
is_perfect = False
if number < 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
print(perfect(8))
You should return False at the End otherwise None is getting returned implicitly:
def perfect(number):
...
for i in range(1, number):
...
return False
Hi your problem is that you have no return when you don't match if (sum == number):..
so, the simplest solution is to add an return False at the end. But also your sum condition is inside the for that's not fine because you can encounter a fake perfect
like 24... so be carefull about that condition
edit 0 is not a perfect number so add the condition to first if
def perfect(number):
sum = 0
is_perfect = False
if number <= 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
return False
I would totally reshape your code to make it a litle more clear:
def is_perfect(number):
acum= 0
if number <= 0:
return False
for i in range(1, number):
if(number % i == 0):
acum += i
return (acum == number) #return true if the condition match, False if not
#just to check function
print([(i,is_perfect(i)) for i in range(1,100) if is_perfect(i)])
#output
[(6, True), (28, True)]

Python - function returns true when a given number is a prime number or else false

Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)

Writing a function which accepts two strings and returns True in python 3

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"))

Categories

Resources