I am trying to pass the arguments a and b to the local function "isPrimes" to be used as a range - python-3.x

If I try to run the isPrime function on it's own -- replacing n with any integer, it will find if it is a prime number or not; but getting a and b from primes to be used as the range of numbers to check if they are prime is where the issue lies .
def primes(a,b):
pass
def isPrime(n):
# I want to make n take the values of a and b so that the is Prime
# function executes all the prime numbers within the range a to b
if n == 1:
return False
# here I've tried referencing n and (a,b) as the range but neither
# option does anything
for z in range(a, b):
if n % z == 0:
return False
else:
# this is supposed to print the n each time it comes up as a prime
# number but when I run this nothing happens and I'm not sure where
# I'm going wrong
print(n)
return True

Switch the order of your return and print statement. Your program is
ending before your print statement executes
If you want to specify a range for which you are going to test if a
number is prime, you will either have to declare a and b in your
function, or pass it in as a parameter.
In your range statement, for each integer from a to b, but you are returning false whenever n%z = 0. This will occur for when you attempt to use the % operator on a prime with a prime (ex. 17 % 17 would return false). add a statement to compare if n != z.
You return false in your if statement, and true in your else statement. This means your code will only make one comparison before your function will exit. Add your return true statement at the end of your program.
see below:
def isPrime(n):
a = 2
b = 100000
if n == 1:
print("1 is not a prime number.")
return False
for z in range(a,b):
if n%z==0 and n != z:
print(str(n) + " is not a prime number.")
return False
print(str(n) + " is a prime number.")
return True

Related

Automate the Boring Stuff With Python Practice Project: collatz sequence Unknown loop?

The outline:
Write a function named collatz() that has one parameter named number. If the number is even, then collatz() should print number // 2 and return this value. If the number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
my code:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number")
while n != 1:
collatz(int(n))
the output keeps infinitely printing the n value, and I can't figure out why. Please enlighten me
Your loop should update the value of n:
while n != 1:
n = collatz(int(n))
Otherwise, your loop has no progression, hence the infinite loop.
Edit: Here's an explanation as to why this is necessary.
Think about it logically. If you enter the body of the loop, then n must not be equal to 1. The loop continues to execute until n becomes 1. The only way for this to happen is for you to change (i.e. update) n so that it eventually reaches 1 and the loop can terminate.

While loop or If code? Stuck with this function

I'm asked to write a function generate_palindrome() that takes a given positive integer number n and applies the following procedure to it:
(i) Check if the number is palindrome. If it is, then return it otherwise continue with the next step.
(ii) Reverse the number and calculate the sum of the original number with the reversed number.
(iii) Repeat from (i) (until a palindrome is found.)
I wrote this function:
def generate_palindrome(n):
numbers = list(str(n))
for i in range(len(numbers)):
if numbers[i] == numbers[-i-1]:
return n
else:
while numbers[i] != numbers[-i-1]:
rev = list(reversed(numbers))
rev_num = int(''.join(rev))
n = n + rev_num
return n
I don't know for what reason when I try a random number that is not already palindrome, the code doesn't respond, it's still running until an indefinite amount of time. I tried changing it with an if code but it doesn't iterate my function, so I think my only chance is with the while code, but maybe I'm the one who's wrong. What do you think?
I think that you should've added a broken functionality to your while loop so that when a specific condition is achieved it breaks. And I think that the indentation of the last return statement is wrong. :)
Here you go:
#!/usr/bin/env python3
def generate_palindrome(num: int):
if str(num) == str(num)[::-1]:
return num
else:
while str(num) != str(num)[::-1]:
rev = int(str(num)[::-1])
num += rev
return num
if __name__ == '__main__':
print(generate_palindrome(212)) # prints 212
print(generate_palindrome(12)) # prints 33
print(generate_palindrome(43)) # prints 77
This is the best solution:
def generate_palindrome(n):
while True:
number = list(str(n))
num = ''
if number[::-1] == number:
for i in number:
num = num + i
print(num)
break
print(a)
else:
for i in number:
num = num + i
n = int(num) + int(num[::-1])
generate_palindrome()

Polydivisible Calculator Fails, Despite Previous Implementation Working

To begin, a definition:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
1 % 1 == 0
14 % 2 == 0
141 % 3 == 0
I'm working on a recursive polydivisible checker, which, given a number, will check to see if that number is polydivisible, and if not, recursively check every other number after until it reaches a number that is polydivisible.
Unfortunately, my code doesn't work the way I want it to. Interestingly, when I input a number that is already polydivisible, it does its job and outputs that polydivisible number. The problem occurs when I input a non-polydivisible number, such as 13. The next polydivisible number should be 14, yet the program fails to output it. Instead, it gets stuck in an infinite loop until the memory runs out.
Here's the code I have:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
I'm assuming the problem occurs in the else statement inside the while loop, where, if the number fails to be polydivisible, the program resets i to 0, and adds 1 to the original number so it can start checking the new number. However, like I explained, it doesn't work the way I want it to.
Any idea what might be wrong with the code, and how to make sure it stops and outputs the correct polydivisible number when it reaches one (like 14)?
(Also note that this checker is only supposed to accept non-negative numbers, hence the initial if conditional)
The mistake is that you are no updating number after incrementing num.
Here is working code:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
I have a similar answer to #PranavaGande, the reason is I did not find any way to iterate an Int. Probably because there isn't one...Duh !!!
def is_polydivisible(n):
str_n = str(n)
list_2 = []
for i in range(len(str_n)):
list_2.append(len(str_n[:i+1]))
print(list_2)
list_1 = []
new_n = 0
for i in range(len(str_n)):
new_n = int(str_n[:i+1])
list_1.append(new_n)
print(list_1)
products_of_lists = []
for n1, n2 in zip(list_1, list_2):
products_of_lists.append(n1 % n2)
print(products_of_lists)
for val in products_of_lists:
if val != 0:
return False
return True
Now, I apologise for this many lines of code as it has to be smaller. However every integer has to be split individually and then divided by its index [Starting from 1 not 0]. Therefore I found it easier to list both of them and divide them index wise.
There is much shorter code than mine, however I hope this serves the purpose to find if the number is Polydivisible or Not. Of-Course you can tweak the code to find the values, where the quotient goes into decimals, returning a remainder which is Non-zero.

Palindrome rearrangement in Python

I am given a string and I have to determine whether it can be rearranged into a palindrome.
For example: "aabb" is true.
We can rearrange "aabb" to make "abba", which is a palindrome.
I have come up with the code below but it fails in some cases. Where is the problem and how to fix this?
def palindromeRearranging(inputString):
a = sorted(inputString)[::2]
b = sorted(inputString)[1::2]
return b == a[:len(b)]
def palindromeRearranging(inputString):
return sum(map(lambda x: inputString.count(x) % 2, set(inputString))) <= 1
this code counts occurrence for every character in string. in palindromes there is one character with odd occurrence if length of string is odd, if length of string is even then no character has odd occurance.
see here
def palindromeRearranging(inputString):
elements = {c:inputString.count(c) for c in set(inputString)}
even = [e % 2 == 0 for e in elements.values()]
return all(even) or (len(inputString) % 2 == 1 and even.count(False) == 1)
It counts each character number of appearances, and checks whether all elements appear an even number of times or if the length of the input string is odd, checks whether only one character appears an odd number of times.
Python3
def palindromeArrange (string):
string = list(string)
for i in range (len(string)):
"""if the string has even element count"""
if len(string) % 2 == 0 and len(string)/2 == len (set (string)):
return True
"""if the string has odd element count"""
if len(string) - ((len(string)-1)/2) == len (set (string)):
return True
return False
One liner using list comprehension in Python3
return len([x for x in set(inputString) if inputString.count(x) % 2 != 0]) <= 1
Basically counts those characters that have counts that aren't divisible by 2.
For even strings it would be zero, and for odd strings, it would be one.
The solution I can think of right away has time complexity is O(n). The assumption is, palindrome can not be made if there is more than one character with the odd count.
def solution(inputString):
string = list(inputString)
n = len(string)
s_set= set(string)
from collections import Counter
dic = Counter(string)
k =0 #counter for odd characters
for char in s_set:
if dic.get(char)%2!=0:
k+=1
if k>1:
return False
else:
return True

How do you check if a given input is a palindrome?

I need to check if the input is a palindrome.
I converted the input to a string and compared the input with the reverse of the input using list slicing. I want to learn a different way without converting input to a string.
def palindrome(n):
num = str(n)
if num == num[::-1]:
return True
Assuming that n is a number, you can get digits from right to left and build a number with those digits from left to right:
n = 3102
m = n
p = 0
while m:
p = p*10 + m%10 # add the rightmost digit of m to the right of p
m //= 10 # remove the rightmost digit of m
print(p) # 2013
Hence the function:
def palindrome(n):
m = n
p = 0
while m:
p = p*10 + m%10
m //= 10
return p == n
Note that:
if num == num[::-1]:
return True
will return None if num != num[::-1] (end of the function). You should write:
if num == num[::-1]:
return True
else:
return False
Or (shorter and cleaner):
return num == num[::-1]
There can be 2 more approaches to that as follows:
Iterative Method: Run loop from starting to length/2 and check first character to last character of string and second to second last one and so on. If any character mismatches, the string wouldn’t be palindrome.
Sample Code Below:
def isPalindrome(str):
for i in xrange(0, len(str)/2):
if str[i] != str[len(str)-i-1]:
return False
return True
One Extra Variable Method: In this method, user take a character of string one by one and store in a empty variable. After storing all the character user will compare both the string and check whether it is palindrome or not.
Sample Code Below:
def isPalindrome(str):
w = ""
for i in str:
w = i + w
if (str==w):
return True
return False
You can try the following approach:
Extract all the digits from the number n
In each iteration, append the digit to one list (digits) and at that digit at the beginning of another list (reversed_digits)
Once all digits have been extracted, compare both lists
def palindrome(n):
digits = []
reversed_digits = []
while n > 0:
digit = n % 10
digits.append(digit)
reversed_digits.insert(0, digit)
n //= 10
return digits == reversed_digits
Note: this might not be the most efficient way to solve this problem, but I think it is very easy to understand.

Resources