Find the max number in a list - python

I wrote some functions to find the maximum number of a list. If my list contains numbers and other types it gets only the numbers and finds the maximum, if my list is empty then it returns None. My only problem is that it always returns the number 7 instead of the 32 which is bigger than 7
#gets the numbers
def getint( l ):
result=[]
x=0
if not l:
print('The list is empty')
else:
while x!=len(l):
if l[x].isdigit() == True:
result.append(l[x])
x += 1
return result
#returns true or false
def all_ints( l ):
result=[]
x=0
y=0
for i in range(len(l)):
if l[i].isdigit() == True:
continue
else:
y=1
if(y==1):
result.append(False)
else:
result.append(True)
return result
#get the maximum
def max_int( l ):
x=0
if not l:
max='none'
else:
max = l[0]
while x!=len(l):
if l[x] > max:
max = l[x]
x+=1
return max
#return true or false if its empty
def isEmpty( l ):
if not l:
return True
else:
return False
def check( l ):
max=0
val=isEmpty(l)
if(val==True):
max='None'
elif(all_ints(l)==True):
max=max_int(l)
else:
new_l=getint(l)
max=max_int(new_l)
return max
print(check(['4','5','6','7', '32']))

In your max_int function, you compare two strings instead of numbers. The problem is, that 32 > 7 == True, but '32' > '7' == False. More on comparing strings.
Also, I would suggest that you just convert to integer and check for errors and then look for maximal number.
def max_num(l):
int_arr = []
for i in l:
try:
int_arr.append(int(i))
except:
pass
return max(int_arr)
print(max_num(['4','5','6','7', '32']))

The error is that you are defining the numbers as characters, and in reality the first character is compared, if you put them as numbers really, your code will result in 32
Fix this
print(check(['4','5','6','7', '32']))
for
print(check([4,5,6,7,32]))

Related

My function does not return anything no matter what I try

def iq_test(numbers):
i = 0
length = len(numbers)
numbers = numbers.split()
ints = []
even = []
odd = []
try:
for i in range(i, length, i + 1):
number = int(numbers[i])
ints.append(number)
if ints[i] % 2 == 0:
even.append(ints[i])
else:
odd.append(ints[i])
except:
pass
if len(even) > len(odd):
return i
else:
return i
iq_test("1 2 2")
No matter how many times or ways I try to fix this it doesn't seem to return i. Whenever I do print(i) it gives me the exact thing I wanted and the function works well, but when it's return i I get nothing, how can I fix this?
Edit: this function is supposed to take in some numbers (in string format), one of those numbers will be different in evenness (one is even and the rest are odd and vice versa), I want to return the index of that number.
I have modified your code and it's working :
def iq_test(numbers):
i = 0
numbers = list(map(int,numbers.split()))
even = []
odd = []
try:
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
even.append(i)
else:
odd.append(i)
except:
pass
finally:
if len(even) > len(odd):
return odd[0]
else:
return even[0]
print(iq_test("1 1 2"))
Points I have modified :
instead of creating another list for converting list elements to an integer you could just use the map function
you should store the index of the even and odd value instead of the value itself
And if there is something in the code that is necessary to do even if the error occurs you could use the finally block
def iq_test(numbers):
numbers = numbers.split()
length = len(numbers)
ints = []
even = []
odd = []
try:
for i in range(0, length):
number = int(numbers[i])
ints.append(number)
if ints[i] % 2 == 0:
even.append(ints[i])
else:
odd.append(ints[i])
if len(even) > len(odd):
return even[0]
else:
return odd[0]
except:
pass
ReturnedNumber = iq_test("1 2 2")
print("Returned number from function:",ReturnedNumber)

Returning a string in python and only getting an empty array

I am trying to return an array of a number's divisors. If the number is prime I want to return the string, '(integer) is prime'. Instead of returning this string my function returns an empty array.
Code:
def divisors(num):
i = 2
array = []
while i < num:
if num % i == 0:
array.append(i)
i += 1
print(array)
if len(array) > 0:
return array
else:
prime = '%i is prime' %num
return prime
divisors(3)
Thank you for the help!
What you are seeing is the empty array that you print when your function executes. Your function is correctly returning the string because 3 is prime, but you just haven't assigned the return value of the function to any variable. This should accomplish what you want.
def divisors(num):
i = 2
array = []
while i < num:
if num % i == 0:
array.append(i)
i += 1
# print(array)
if len(array) > 0:
return array
else:
prime = '%i is prime' %num
return prime
value = divisors(3)
print(value)
Output:
'3 is prime'
Your function does returns the string, the empty array you see is a result of the print(array) statement in the middle of your code, which I assume you added for debugging. Consider removing it.
Use print(divisors(3)) to actually show the resulting string (otherwise it wouldn't show, as it does now).

How to find the majority integer that is divisible by the integer 10?

I'm writing a function "most_of" that takes a list of numbers as a argument. The objective of the function is to take the list, iterate over it and find out if the majority of the list integers are divisible by 10.
So for example, if I had passed the argument:
[1,10,10,50,5]
The output would be:
True
Because 3/5 of the integers are divisible by 10. However, if I had passed:
[1,2,55,77,6]
The output would be:
False
Because 4/5 of the list integers are not divisible by 10.
Here is what I have tried:
def most_of(lst):
for i in lst:
if lst[i] % 10 == 0:
lst == True
else:
lst == False
I'm basically stuck at this point because this doesn't check if the majority of the numbers are divisible by ten, it just divides.
Thanks for the help!
Count how many integers are divisible by ten, and test whether that number is "the majority" - that is, if it's greater than or equal to half the lists' length. Like this:
def most_of(lst):
num = sum(1 for n in lst if n % 10 == 0)
return num >= len(lst) / 2.0
For example:
>>> most_of([1,10,10,50,5])
True
>>> most_of([1,2,55,77,6])
False
The objective of the function is to take the list, iterate over it and
find out if the majority of the list integers are divisible by 10.
Your list will contain two kind of integers: those that are divisible by 10 and those that aren't. You need to find the number of integers in each of the two categories, compare those numbers and return True or False accordingly. So, your function would look like this:
def most_of(lst):
divisible_counter = 0
non_divisible_counter = 0
for element in lst:
if element % 10 == 0:
divisible_counter +=1
else:
non_divisible_counter += 1
if divisible_counter > non_divisible_counter:
return True
else:
return False
Of course, all the above code could be reduced a lot. But I wanted to show an algorithm that would be easier to understand for Python beginners.
A slight modification of the answer by Oscar:
def most_of(lst):
return sum(1 if n % 10 == 0 else -1 for n in lst) >= 0
with the same results of course
lst1 = [1,10,10,50,5]
lst2 = [1,2,55,77,6]
print(most_of(lst1)) # True
print(most_of(lst2)) # False
you assign your list a bool after you test your first number, but you have to count all numbers which can divide by ten without rest and all other numbers and then compare this counters:
def most_of(lst):
divideByTen = 0
otherNumbers = 0
for i in lst:
if i % 10 == 0:
divideByTen+=1
else:
otherNumbers+=1
if(divideByTen > otherNumbers):
return True
else:
return False
a = [1,10,10,50,5]
b = [1,2,55,77,6]
print(most_of(a))
print(most_of(b))

python - finding circular prime number

I am trying trying to find the number of circular primes from a given limit. The prime(x) will return whether a number is a prime or not. The rotations() will return a list of rotated numbers. Lastly, prime_count() will output the total amount of circular primes based on the given limit. Both prime() and rotations() gave me the correct output; however, prime_count() is not incrementing like it should. Any ideas on what i did wrong?
def prime(number): #return true or false
return all(number% i for i in range(2,number))
def rotations(num): #rotating number and return list
list = []
m = str(num)
counter = 0
while counter < len(str(num)):
m=m[1:] + m[0]
list.append(int(m))
counter+=1
list1=sorted(list,key=int)
return list1
def prime_count(limit): #return numbers of circular primes from given limit
counter = 0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j):
counter+=1
return counter
print(prime_count(100))
There are a few problems with your code:
Your prime function has a bug:
In [8]: prime(1)
Out[8]: True
It erroneously returns True for any number less than 2 due to range(2, n) being empty and any([]) == True.
prime_count should be counting the total number of circular primes below limit. prime(j) returns a boolean, but you check j == prime(j), which can only be true if j is zero or one, which definitely isn't what you want. Try creating an is_circular_prime function that takes in an integer n and returns whether or not the prime is circular. Then, prime_count becomes easy to write.
This is the heart of the problem:
a=rotations(i)
for j in a:
if j == prime(j):
counter+=1
You're counting the wrong thing (e.g. 13 counts twice independent of 31 counting twice) and you're comparing the wrong thing (numbers against booleans.) The problem is simpler than you're making it. Rearranging your code:
def prime(number):
return number > 1 and all(number % i != 0 for i in range(2, number))
def rotations(num):
rotated = []
m = str(num)
for _ in m:
rotated.append(int(m))
m = m[1:] + m[0]
return rotated
def prime_count(limit):
counter = 0
for number in range(1, limit + 1):
if all(prime(rotation) for rotation in rotations(number)):
counter += 1
return counter
print(prime_count(100))
Note that you don't need to sort the rotations for this purpose. Also list, or any other Python built-in function, is a bad name for a variable.
Problem may be here:
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if j == prime(j): # Prime will return True or False, comapring with J will cause it False ,except when J = 1
counter+=1
Changing it to prime(j)
for i in range(2,number//2):
if(number%i==0):
return False
return True
def rotations(num):
count=0
rotation_lst=[]
num=str(num)
while(count<len(num)):
num=num[1:]+num[0]
count+=1
rotation_lst.append(int(num))
rotation_lst1=sorted(rotation_lst,key=int)
return rotation_lst1
def get_circular_prime_count(limit):
count=0
for i in range(1,limit+1):
a=rotations(i)
for j in a:
if(check_prime(j)):
count+=1
return count
print(get_circular_prime_count(1000) ```

Python: Create a list of all four digits numbers with all different digits within it

I was wondering if there is any easier way to achieve what this code is achieving. Now the code creates all 4-digits number in a list (if the number starts with a 0 is doesn't count as a 4-digit, for example 0123) and no digit is repeated within the number. So for example 1231 is not in the list. Preferable I want a code that does what this one is doing but a depending on what argument N is given to the function upon calling it creates this kind of list with all numbers with N digits. I hope this wasn't impossible to understand since Im new to programing.
def guessables():
'''creates a list of all 4 digit numbers wherest every
element has no repeating digits inside of that number+
it doesn't count as a 4 digit number if it starts with a 0'''
guesses=[]
for a in range(1,10):
for b in range(0,10):
if a!=b:
for c in range(0,10):
if b!=c and a!=c:
for d in range(0,10):
if c!=d and d!=b and d!=a:
guesses.append(str(a)+str(b)+str(c)+str(d))
return guesses
This can be expressed more easily.
def all_digits_unique(number):
# `set` will only record unique elements.
# We convert to a string and check if the unique
# elements are the same number as the original elements.
return len(str(number)) == len(set(str(number)))
Edit:
def guesses(N):
return filter(all_digits_unique, range(10**(N-1), 10**N))
print guesses(4)
I'd use itertools for this which is in my opinion the simplest generic answer:
import itertools
def guessables(num):
guesses = []
for p in itertools.permutations(xrange(10),num):
if p[0] != 0:
guesses.append(''.join(map(str, p)))
return guesses
Simply call this function with guessables(4) and get a list with all the numbers you want.
You can do in one line:
print([str(a)+str(b)+str(c)+str(d) for a in range(1,10) for b in range(0,10) if a!=b for c in range(0,10) if b!=c and a!=c for d in range(0,10) if c!=d and d!=b and d!=a])
Try the following:
def guessables(n):
''' Returns an array with the combination of different digits of size "n" '''
if n > 10:
raise ValueError("The maximum number of different digits is 10.")
elif n < 1:
raise ValueError("The minimum number of digits is 1.")
else:
results = []
for i in range(1, 10):
_recursiveDigit([i], n, results)
return results
def _formatDigit(l):
''' Return a formated number from a list of its digits. '''
return "".join(map(str, l))
def _recursiveDigit(l, n, results):
''' Recursive function to calculate the following digit. '''
if len(l) < n:
for i in range(0, 10):
if i not in l:
_recursiveDigit(l + [i], n, results)
else:
results.append(_formatDigit(l))
The functions that are prefixed with an underscore(_) should not be called from outside of this script. If you prefer to have the result as something different than an array of strings, such as an array of ints for example, you can change the _formatDigit() function as follows:
def _formatDigit(l):
''' Return a formated number from a list of its digits. '''
return int("".join(map(str, l)))
c=list(range(10))
print c
def fun(n,k,i,getnum): # function , result in getnum
if n==0:
if k not in getnum and len(set(list(k)))==len(k) and k[0]!='0':
getnum.append(k)
return
if i>=len(c):
return
fun(n-1,k+str(c[i]),0,getnum)
fun(n,k,i+1,getnum)
getnum=[]
d=fun(4,"",0,getnum)
print getnum
These types of problems are easily solved with recursion.
def gen(num, n, saveto):
if len(num) == 1 and num[0] == '0':
return
if len(num) == n:
saveto.append(int(''.join(num)))
return
for i in range(0, 10):
i= str(i)
if i not in num:
gen(num+[i], n, saveto)
saveto= []
# generate 4 digit numbers
gen([], 4, saveto)
print(saveto)
Here I'm using the list num to construct the numbers by placing one digit at each call. When there are four digits added, it stores the number to the saveto list.
Edit: Here's a version of the above function that returns the list of numbers instead of appending them to a list.
def gen(num, n):
if len(num) == 1 and num[0] == '0':
return []
if len(num) == n:
return [int(''.join(num))]
ans = []
for i in range(0, 10):
i= str(i)
if i not in num:
ans.extend(gen(num+[i], n))
return ans
saveto= gen([], 4)
print(saveto)
numPool = []
for i in range(0, 10):
for j in range(0, 10):
for k in range(0,10):
for l in range(0,10):
if i != j and i != k and i != l and j != k and j != l and k != l :
numPool.append(str(i) + str(j) + str(k) + str(l))
This works, but keep in mind that this will also add "0123" or "0234" to the list as well. If you do not want the numbers that are starting with zero, you might want to add "i != 0" to the if query. Hope it helps.
I try to write it clear for absolute beginers ^^ Ofcourse it is possible to make it faster and shorter if you use combianations and advance array methods.
def f(n)
s = list(range(10**(n-1), 10**n))
number_list = []
for ss in s:
test_list = []
a = ss
while ss:
if ss % 10 in test_list:
break
test_list.append(ss % 10)
ss = ss // 10
if len(test_list) == n:
number_list.append(a)
return number_list
print(f(4))
This would sovlve the problem, without repeating digits:
from itertools import permutations
myperm = permutations([0,1,2,3,4,5,6,7,8,9],4)
for digits in list(myperm):
print(digits)
How about this?
def check_count(num):
if isinstance(num, str) == False:
num = str(num) # Convert to str
if len(num) == 1: # If total length number is single, return False
return False
return any(num.count(x) > 1 for x in num) # Check here
Return False if numbers all different, else return True
Usage:
# Get all numbers has all different. (1000-9999)
[x for x in range(1000, 10000) if check_count(x) == False]

Categories

Resources