Checking if a number has any repeated elements - python

I have been working on spliting integers into the digits they are comprised of and then checking whether there are any repeated numbers in the list. However the code seems to always say there are no repeated numbers, even if there are.
My Code:
def repeatCheck(myList, repeatedNumber):
seen = set()
for number in myList:
if number in seen:
repeatedNumber = True
seen.add(number)
return repeatedNumber
def numberWorks(number, finalNumber):
digits = [int(n) for n in str(number)]
repeatedNumber = False
repeatCheck(digits, repeatedNumber)
if repeatedNumber == False:
print(number, "succeeded repeatedNumber")
found = True
else:
print(number, "failed repeatedNumber")
pass
return number
number = 1000000000
while found == False:
numberWorks(number, finalNumber)
number += 1
print(finalNumber)
With input number 1000000000, the output should be 1023456789
Please let me know of anything that could be done to solve it, or if the code I have given is not enough.
Thank you.

When you call the function repeatCheck() you don't pass a reference to the variable repeatedNumber, so any changes to the variable do not affect the original definition of repeatedNumber. Therefore, the repeatedNumber defined in numberWorks() is never updated.
what you could do instead is assign the return value of repeatCheck to repeatedNumber.
repeatedNumber = False
repeatedNumber = repeatCheck(digits)
and rewrite repeatCheck to return True or False upon seeing a repeat:
def repeatCheck(myList):
seen = set()
for number in myList:
if number in seen:
return True
seen.add(number)
return False
This way you circumvent the ambiguity of reusing the variable name repeatedNumber

If you would like to check for repeated digits inside a number here's a quick way to do it that returns a boolean.
def noRepeatedDigits(number:int) -> bool:
return all([str(number).count(i) == 1 for i in set(str(number))])
print(noRepeatedDigits(12344))
print(noRepeatedDigits(1234))
False #indicates it failed the check
True #indicates it passed the check

I would simply delete all your code and do this.
def repeatCheck(repeatedNumber):
numbersdub = list(str(repeatedNumber))
numbers = set(numbersdub)
for num in numbers:
numbersdub.remove(num)
return set(numbersdub)
print(repeatCheck(78788))
This will give you a set of all dubbels.

Alternative one-line solution:
finalNumber = next(n for n in range(1000000000, 2000000000) if len(set(s := str(n))) == len(s))
print(finalNumber)
# 1023456789
Explanation: len(str(n)) is the number of digits of n, whereas len(set(str(n))) is the number of unique digits of n. These two quantities are equal if an only if n doesn't have repeated digits.
The whole thing is wrapped in an iterator, and next( ) returns the first value of the iterator.

Related

PYTHON3: indentation of return values

This is working fine but I just don't get it why this works in this way. I think the return of True value should be inside the for loop but when I run this program it works in the opposite way.
Can someone point out what i am misunderstanding about the indentation of return values?
Even though the solution was even shorter I wanted to know exactly about my way of coding. Please help!
# My attempt
def palindrome(s):
mylist = list(s)
j = -1
for i in range(0,len(mylist)-1):
if mylist[i] == mylist[j]:
i+=1
j-=1
continue
return False
return True
# Solution answer:
def palindrome(s):
return s == s[::-1]
When a function is called, the function can return only once.
This kind of return pattern is very frequently found across various programming languages. It is intuitive and efficient.
Let's say you have to check if a list of 1000 values contain only even numbers. You loop through the list and check if each element is even. Once you find an odd number, you do not need to go further. So you efficiently and immediately return and exit from the loop.
Here is hopefully a little bit more intuitive version of your code:
def palindrome(s):
l, r = -1, 0 # left, right
for _ in range(0, len(s) // 2 + 1): # more efficient
l += 1
r -= 1
if s[l] != s[r]:
return False
return True
Once you know the input is not palindrome, you do not need to go further.
If you did not need to stop, it is palindrome.
They follow the exact same rules as any other statement. What you have written means
def palindrome(s) {
mylist = list(s)
j = -1
for i in range(0,len(mylist)-1) {
if mylist[i] == mylist[j] {
i+=1
j-=1
continue
}
return False
}
return True
}
# My attempt
def palindrome(s):
mylist = list(s)
j = -1
for i in range(0,len(mylist)-1):
if mylist[i] == mylist[j]:
i+=1
j-=1
continue
return False
return True
In the above code what happens is inside the for loop each time it checks if there is a mismatch in the values by comparing values by iterating over the list forwards using variable "i" and backwards using variable "j". and returns false immediately if any one letter mismatches and so exits from the loop. And true is returned only once the for loop is completed which means no mismatch was found in the loop
Note: i=0 gives first index, i+=1 iterates forward and j=-1 gives last index, j-=1 iterates backward
Basically, when you index an array in numpy, you do it the way:
a[start:end:step]
,for every dimension. If step is negative, you return the values in inverse order. So, if step is -1, the array a[::-1] is the inverted array of a[::].
a[::-1] = a[::]
Then, if a sequence is the same as its inverse, by definition, it is a palindrome.
See:
https://www.geeksforgeeks.org/numpy-indexing/

I cant see if my list has repeated numbers in it

I'm trying to generate 20 random numbers in my list. Next I want to see if there are any repeated numbers in it.
I generated the random numbers. Next I did an insertion sort in order to arrange the list in a growing order. To see if I had any repeated numbers, I iterated over the list and if the previous number was equal to the next number, then my list had repeated numbers in it.
import random
random_array=[]
def array():
for i in range(0,20):
random_element=random.randint(1,35)
random_array.append(random_element)
return random_array
print(array())
# function to order the list
def insertion_sort():
for i in range(1,len(random_array)):
while i>0 and random_array[i-1]>random_array[i]:
random_array[i-1],random_array[i]=random_array[i],random_array[i-1]
i=i-1
return random_array
print(insertion_sort())
def verification():
for i in random_array:
insertion_sort()
if i-1==i:
return True
else:
return False
print(verification())
My program always returns false independent of the generated list.
Issues in your code:
You are iterating on the elements and subtracting them and comparing, instead you should iterate on the indexes and use them to compare consecutive elements
You are calling insertion_sort() within your for loop, I assume by mistake
You want to break the for loop on the first match you found, and in the end return a boolean which tells if the match has happened or not
So your code will look like
def verification():
#Flag to keep track of matches
flag = False
#Iterate over list via indexes
for i in range(len(random_array)):
#If consecutive elements match, set flag to true and break loop
if random_array[i-1]==random_array[i]:
flag = True
break
#Return flag value
return flag
You can do it with much shorter code using itertools.Counter:
import random
from collections import Counter
# Generate a random array
random_array = [random.randint(1, 35) for _ in range(20)]
nums = [
n # A number
for (n, count) in Counter(random_array).items() # From countered items
if count > 1 # If the count of this number is more than one
]
print(nums)
You have two options here: If you don't care about the order, you can use set which is a data type that can only have unique elements. If you need to keep your original order of numbers, you need to use OrderedDict from collections
See this stack answer: https://stackoverflow.com/a/7961393/11323304
Your verification function is wrong. You are comparing the value of element i to the value of element i - 1, which is never going to be true. Try this:
insertion_sort()
for i in range(1,len(random_array - 1)):
if random_arry[i] == random_array[i-1]:
return True
return False # If you get through every element without finding a match, return False
your loop in def verification(): is exiting after first iteration because if else: return False (it's exiting)
use simple flag:
import random
random_array=[]
def array():
for i in range(0,20):
random_element=random.randint(1,35)
random_array.append(random_element)
return random_array
print(array())
# function to order the list
def insertion_sort():
for i in range(1,len(random_array)):
while i>0 and random_array[i-1]>random_array[i]:
random_array[i-1],random_array[i]=random_array[i],random_array[i-1]
i=i-1
return random_array
print(insertion_sort())
def verification():
#for i in random_array:
status = False # <----
for i in range(len(random_array)-1): # <------
insertion_sort()
#if i-1==i:
if random_array[i] == random_array[i+1]: # Iterate over list by indexes
status = True
break
return status
print(verification())

Why does this recursive function exceed maximum length in python?

#finds length of a list recursively, don't understand why it exceeds maximum length, can someone please explain?
def lengtho(xs):
if(xs == None):
return 0
return 1 + lengtho(xs[1:])
lengtho([1,2,3,4,1,4,1,4,1,1])
When the code reaches the end of the list (the base case), xs will be equal to [] (the empty list), not None. Since [][1:] simply returns [], the function will call itself until the stack overflows.
The correct way to write this function in python would be:
def lengthof(xs):
"""Recursively calculate the length of xs.
Pre-condition: xs is a list"""
if (xs == []):
return 0
else:
return 1+ lengthof(xs[1:])
Your base case of recursion will never get to True value, xs == None will be always False if you are talking about lists, probably you want to change it to xs == [] or just if not xs

Sum of all arguments

This is a codewars challenge where you have to return the sum of the given arguments.
Instructions:
Calculate the sum of all the arguments passed to a function.
Note: If any of the arguments is not a finite number the function should return false/False instead of the sum of the arguments.
Here's my code:
def sum_all(*args):
sum = 0
for str(num) in args:
if not num.isdigit():
return False
else:
int(sum) += num
return sum
Currently I'm getting this error:
File "", line 9
SyntaxError: can't assign to function call
That error message is actually happening in two places:
Here:
for str(num) in args:
and here:
int(sum) += num
You cannot cast to string and int the way you are attempting to.
What you should do instead, is keep your iteration as:
for num in args:
Then, you can check if digit by doing this:
if not str(num).isdigit():
Finally, when you get to summing everything, simply cast num to int(num) to handle the case if you pass something like [1, 2, '3', 4] (not the 3 as a string):
sum += num
So, with that in mind, your code will look like this:
def sum_all(*args):
sum = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum += int(num)
return sum
However, as you pointed out in your comment, there is a test case for negative numbers. This is where the above code breaks. Because, negative numbers as a string:
"-343"
Do not pass isdigit.
If you put this in your interpreter, it will return False:
"-343".isdigit()
So, with all this in mind, you can actually further simplify your code when you remove that to just have this:
def sum_all(*args):
try:
return sum(int(i) for i in args)
except:
return False
Demo:
print(sum_all(1,2,3,4,5))
Outputs:
15
First of all, don't overwrite existing functions such as sum. Use a different variable name (e.g. sum_). Second, your problem is on the for str(num) in args line. This needs to be for num in args:, with a modification of the following line for str(num).
def sum_all(*args):
sum_ = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum_ += float(num)
return sum_
>>> sum_all('a', 2)
False
>>> sum_all(1, 2)
3.0
>>> sum_all(1, 2, '4')
7.0
Here is an alternative approach to coding the function that uses a generator comprehension to try and sum the arguments but returns False if it fails:
def sum_all2(*args):
try:
return sum(i for i in args)
except:
return False
>>> sum_all2(1, 2, '4.5')
False
>>> sum_all2(1, 2, '4') # I argue that '4' is a string, not a finite number.
False
>>> sum_all2(1, 2)
3
>>> sum_all2(1, 2, 3.5)
6.5
>>> sum_all2(1, 2, -3.5)
-0.5
You're overthinking this. There are two parts to this to note:
sum is a function that already takes in a collection and gives you its sum.
You want to reject the collection if none of them are numeric types.
Here's a start: this particular method will reject if none of the values are int. I leave expanding this out to float types as an exercise for the reader.
def sum_or_reject(li):
return sum(li) if all([isinstance(i, int) for i in li]) else False
The minimal change to make your logic run is:
def sum_all(*args):
sum = 0
for s in args:
num = str(s)
if not num.isdigit():
return False
else:
sum += int(num)
return sum
The line number in the question is misleading, and there are two issues: First, you need a variable for the iteration. Second, you need a variable for the += assignment. In both cases you try to apply a cast, bust the result of that would not longer be a variable and thus cannot be used as target for the assignment.
Likewise a minimal change to your code:
def sum_all(*args):
try:
return sum(int(i) for i in args)
except:
return False
print(sum_all(10,'-1',10))

How can I use recursion to find palindromes using Python?

I've just started exploring the wonders of programming. I'm trying to write a code to identify numeric palindromes. Just looking at numbers and not texts. I'm trying to learn to use recursion here. But I'm just not getting anywhere and I can't figure out what's wrong with it.
My idea was to check first string vs the last, then delete these two if they match, and repeat. Eventually there'll be nothing left (implying it is a palindrome) or there will be a couple that doesn't match (implying the reverse).
I know there are better codes to finding palindromes in but I just wanted to try my hand at recursion.
So what's wrong?
def f(n):
global li
li=list(str(n))
if (len(li)==(1 or 0)):
return True
elif li[len(li)-1]==li[0]:
del li[0]
del li[len(li)-1]
if len(li)==0:
return True
if len(li)>0:
global x
x=''.join(li)
str(x)
f(x)
else:
return False
Thanks in advance!
A few comments
Why are x and li globals? In recursion, all variables should be local.
Why are you converting back and forth between str and list? You can subscript both of them
You need to return the result of your recursive call: return f(x)
Try these suggestions, and see how it works out.
Before looking into it too much, if (len(li)==(1 or 0)): doesn't do what you're expecting it to do. (1 or 0) will always evaluate to 1.
You probably want:
if len(li) in (1, 0):
There are a couple of problems with your solution. Let me analyse them line by line.
You don't need global statements if you don't intend to change variables outside of function scope. Thus, I removed two lines with global from your code.
li=list(str(n)): casting a string to a list is unnecessary, as a string in Python has a similar interface to an immutable list. So a simple li = str(n) will suffice.
if (len(li)==(1 or 0)):: although it looks OK, it is in fact an incorrect way to compare a value to a few other values. The or operator returns the first "true" value from its left or right operand, so in this case it always returns 1. Instead, you can use the in operator, which checks whether the left operand is an element of a right operand. If we make the right operand a tuple (1, 0), all will be well. Furthermore, you don't need parentheses around the if statement. You should write: if len(li) in (1, 0):
elif li[len(li)-1]==li[0]: is fine, but we can write this shorter in Python, because it supports negative list indexing: elif li[-1] == li[0]:
Because we don't use lists (mutable sequences) because of point 2., we can't do del li[0] on them. And anyway, removing the first element of a list is very inefficient in Python (the whole list must be copied). From the very same reason, we can't do del li[len(li)-1]. Instead, we can use the "splicing" operator to extract a substring from the string: li = li[1:-1]
if len(li)==0: is unnecessary long. In Python, empty strings and lists resolve to False if tested by an if. So you can write if not li:
if len(li)>0:: You don't have to check again if li is not empty -- you checked it in point 6. So a simple else: would suffice. Or even better, remove this line completely and unindent the rest of the function, because the body of the if in 6. contains a return. So if we didn't enter the if, we are in the else without writing it at all.
x=''.join(li): We don't need to convert our string to a string, because of the decision made in 2. Remove this line.
str(x): This line didn't do anything useful in your code, because str() doesn't modify its argument in place, but returns a new value (so x = str(x) would have more sense). You can also remove it.
f(x): This is a valid way to call a recursive function in Python, but you have to do something with its value. Return it perhaps? We'll change it to: return f(li) (as we don't have an x variable any more).
We end up with the following code:
def f(n):
li = str(n)
if len(li) in (1, 0):
return True
elif li[-1] == li[0]:
li = li[1:-1]
if not li:
return True
return f(li)
else:
return False
It's almost what we need, but still a little refinement can be made. If you look at the lines if not li: return True, you'll see that they are not necessary. If we remove them, then f will be called with an empty string as the argument, len(li) will equal 0 and True will be returned anyway. So we'll go ahead and remove these lines:
def f(n):
li = str(n)
if len(li) in (1, 0):
return True
elif li[-1] == li[0]:
li = li[1:-1]
return f(li)
else:
return False
And that's it! Good luck on your way to becoming a successful programmer!
Split the whole show out into a list, then just:
def fun(yourList):
if yourList.pop(0) == yourList.pop(-1):
if len(yourList) < 2:
return True # We're a palindrome
else:
return fun(yourList)
else:
return False # We're not a palindrome
print "1234321"
print fun(list("1234321")) # True
print "6234321"
print fun(list("6234321")) # False
def palindrome(n):
return n == n[::-1]
It's hard to tell what you intend to do from your code, but I wrote a simpler (also recursive) example that might make it easier for you to understand:
def is_palindrome(num):
s = str(num)
if s[0] != s[-1]:
return False
elif not s[1:-1]:
return True
else:
return is_palindrome(int(s[1:-1]))
number = int(raw_input("Enter a number: "))
rev = 0
neg = number
original = number
if (number < 0):
number = number * -1
else:
number = number
while ( number > 0 ):
k = number % 10
number = number / 10
rev = k + ( rev * 10 )
if (number < 1):
break
if ( neg < 0 ):
rev = ( rev * -1)
else:
rev = (rev)
if ( rev == original):
print "The number you entered is a palindrome number"
else:
print "The number you entered is not a palindrome number"
This code even works for the negative numbers i am new to programming in case of any errors
dont mind.

Categories

Resources