Find the biggest digit in number - python

So, I have to input a number and find the biggest digit in that number, so if the number is 2314 I want to get 4, my code so far:
a = input()
for x in a:
i = int(x)

If your input is a number, you will want to first convert your input to a string and then convert each character back into an integer and take the max. You can easily use a generator expression to convert all characters to integers using int and then apply max.
maximum = max(int(x) for x in str(a))
For the sake of an example:
maximum = max(int(x) for x in str(415023)) # 5
If on the other hand, your input is a string, then just skip the conversion to a string.
maximum = max(int(x) for x in a)
A More Robust Solution
All of these examples assume that you don't have any decimal points or negative signs in your number. If you do then you can explicitly ignore those.
maximum = max(int(x) for x in str(a) if x not in '.-')
As an example:
a = -15.93
maximum = max(int(x) for x in str(a) if x not in '.-') # 9

Convert to a string, then get the max
a = 2314
max(str(a))
# output 4

Since this is a homework, here is another simple answer. Since you are a beginner, didn't use max().
a = input("number: ")
print (sorted(list(a))[-1])
Converted the input to a list first, then sorted it. Last number is the max. That [-1] is the last index of the list.

A reduce in python2 might also work.
maximum = reduce(lambda acc, n: acc if acc > int(n) else int(n), "123131891", 0)

Related

IQ test function in Python not working as intended

I'm having trouble with this code below.
My task is to create a function, that among the given numbers finds one that is different in evenness, and returns a position of that number. The numbers are given as a string. So far I have managed to convert the string into an integer list, then using for loop to iterate through each number.
The problem I'm encountering is that I've managed to return only the position of an odd number among the even numbers, and I can't continue on with the code for vice versa action, because it only returns the position of the odd number.
Here is the code:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into int
num_map = map(int, num_split)
# converting the object into list
list_num = list(num_map)
for n in list_num:
if not n%2 == 0:
return list_num.index(n) + 1
Your problem is, that you are assuming, that you are searching for the first even number. What you have to do, is to first decide, what you are searching for. You could for example simply first count the number of even numbers. If it is one, then you are looking for an even number, otherwise, you are looking for an odd. As you don't care for the actual numbers, I would map all of them to their value mod 2 as so:
num_map = list(map(lambda x: int(x) % 2, num_split))
Then, the rest is simple. For example like this:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into even (0) or odd (1)
num_map = list(map(lambda x: int(x) % 2, num_split))
# return the correct position based on if even or odd is in search
evens = num_map.count(0)
if evens == 1:
return num_map.index(0) + 1
else:
return num_map.index(1) + 1
I came up with a similar and a little bit shorter solution
def iq_test(numbers):
# first check what im looking for "even" or "odd", map a lambda function that basically does it for me, using the numbers argument as a list type and afterwards cast it into a list so i can iterate later on
num_map = list(map(lambda x: 'e' if int(x) % 2 == 0 else 'o', numbers.split()))
# search for even numbers numbers
if num_map.count('e') == 1:
return num_map.index('e') + 1
# search for odd numbers numbers
return num_map.index('o') + 1
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into int
num_map = map(int, num_split)
# converting the object into list
list_num = list(num_map)
for n in list_num:
if not n%2 == 0:
return list_num.index(n) + 1

Python- Expanded form of a number raised to the power of ten

I'm pretty new to coding and I am trying to write a python script where a user enters an integer and it displays that integer in expanded form raised to the power of 10's.
Example: A user enters 643541 and the script outputs 643541 = (6x10^5 )+(4x10^4)+(3x10^3)+(5x10^2)+(4x10^1)+(1x10^0)
This is my code
A = [7000, 400, 70,1]
cond = True
y = 0
i = 0
sizeArray = len(A)
for i in range(0, sizeArray-1):
while cond == True:
if A[i]%10 == 0:
A[i] = A[i]/10
y += 1
else:
cond = False
print(y)
I tried working with a sample array to test the number of zero's but I don't know how i will be able to output the result as above.
How can I accomplish this?
You can transform your input integer 643541 to an array of digits [6,4,3,5,4,1]. Then maintain a variable for the exponent. It will be decremented for each digit in the array
def function(num):
digits = str(num) # convert number to string
output = []
for i, digit in enumerate(digits):
output.append("(" + digit + "x10^" + str(len(digits)-i-1) + ")")
return " + ".join(output)
Here len(digits)-i-1 plays the role of the variable that maintains exponent value
Every question like this deserves a solution using a list comprehension:
>>> n = 123456
>>> '+'.join([ '({1}x10^{0})'.format(*t) for t in enumerate(str(n)[::-1]) ][::-1])
'(1x10^5)+(2x10^4)+(3x10^3)+(4x10^2)+(5x10^1)+(6x10^0)'
Explanation:
str(n)[::-1] converts the number to a string and then reverses the string, giving the digits of the number, as strings, from least-significant to most-significant.
enumerate returns pairs t = (i, d) where i is the index and d is the digit. Since the sequence is from least-significant to most-significant, the index equals the corresponding exponent of 10.
*t unpacks (i, d) for {0} and {1} in the format string, so the result is like ({d}x10^{i}).
The [::-1] applied to the list comprehension reverses the results back into the right order.
'+'.join joins those results together into a single string, with the + symbol between the parts.

how to make an imputed string to a list, change it to a palindrome(if it isn't already) and reverse it as a string back

A string is palindrome if it reads the same forward and backward. Given a string that contains only lower case English alphabets, you are required to create a new palindrome string from the given string following the rules gives below:
1. You can reduce (but not increase) any character in a string by one; for example you can reduce the character h to g but not from g to h
2. In order to achieve your goal, if you have to then you can reduce a character of a string repeatedly until it becomes the letter a; but once it becomes a, you cannot reduce it any further.
Each reduction operation is counted as one. So you need to count as well how many reductions you make. Write a Python program that reads a string from a user input (using raw_input statement), creates a palindrome string from the given string with the minimum possible number of operations and then prints the palindrome string created and the number of operations needed to create the new palindrome string.
I tried to convert the string to a list first, then modify the list so that should any string be given, if its not a palindrome, it automatically edits it to a palindrome and then prints the result.after modifying the list, convert it back to a string.
c=raw_input("enter a string ")
x=list(c)
y = ""
i = 0
j = len(x)-1
a = 0
while i < j:
if x[i] < x[j]:
a += ord(x[j]) - ord(x[i])
x[j] = x[i]
print x
else:
a += ord(x[i]) - ord(x[j])
x [i] = x[j]
print x
i = i + 1
j = (len(x)-1)-1
print "The number of operations is ",a print "The palindrome created is",( ''.join(x) )
Am i approaching it the right way or is there something I'm not adding up?
Since only reduction is allowed, it is clear that the number of reductions for each pair will be the difference between them. For example, consider the string 'abcd'.
Here the pairs to check are (a,d) and (b,c).
Now difference between 'a' and 'd' is 3, which is obtained by (ord('d')-ord('a')).
I am using absolute value to avoid checking which alphabet has higher ASCII value.
I hope this approach will help.
s=input()
l=len(s)
count=0
m=0
n=l-1
while m<n:
count+=abs(ord(s[m])-ord(s[n]))
m+=1
n-=1
print(count)
This is a common "homework" or competition question. The basic concept here is that you have to find a way to get to minimum values with as few reduction operations as possible. The trick here is to utilize string manipulation to keep that number low. For this particular problem, there are two very simple things to remember: 1) you have to split the string, and 2) you have to apply a bit of symmetry.
First, split the string in half. The following function should do it.
def split_string_to_halves(string):
half, rem = divmod(len(string), 2)
a, b, c = '', '', ''
a, b = string[:half], string[half:]
if rem > 0:
b, c = string[half + 1:], string[rem + 1]
return (a, b, c)
The above should recreate the string if you do a + c + b. Next is you have to convert a and b to lists and map the ord function on each half. Leave the remainder alone, if any.
def convert_to_ord_list(string):
return map(ord, list(string))
Since you just have to do a one-way operation (only reduction, no need for addition), you can assume that for each pair of elements in the two converted lists, the higher value less the lower value is the number of operations needed. Easier shown than said:
def convert_to_palindrome(string):
halfone, halftwo, rem = split_string_to_halves(string)
if halfone == halftwo[::-1]:
return halfone + halftwo + rem, 0
halftwo = halftwo[::-1]
zipped = zip(convert_to_ord_list(halfone), convert_to_ord_list(halftwo))
counter = sum([max(x) - min(x) for x in zipped])
floors = [min(x) for x in zipped]
res = "".join(map(chr, floors))
res += rem + res[::-1]
return res, counter
Finally, some tests:
target = 'ideal'
print convert_to_palindrome(target) # ('iaeai', 6)
target = 'euler'
print convert_to_palindrome(target) # ('eelee', 29)
target = 'ohmygodthisisinsane'
print convert_to_palindrome(target) # ('ehasgidihmhidigsahe', 84)
I'm not sure if this is optimized nor if I covered all bases. But I think this pretty much covers the general concept of the approach needed. Compared to your code, this is clearer and actually works (yours does not). Good luck and let us know how this works for you.

Function to find the max of 3 numbers in Python

I'm trying to write a function that takes the inputs and puts them into a list, then sorts the list, and finds the greatest number. I keep getting errors and I'm not really sure what's wrong. I'll post the current code that I have typed up already. Any help or advice would be greatly appreciated, thank you.
Code:
def findMax3():
y = list(lst)
y.sort(lst)
y[0] == y[-1]
lst = int(input())
print(findMax3())
You need to pass in a variable - lst maybe?
You need to return value if you want your main to print something.
You need a constant input format for integer arrays, I will suggest 1 2 3 4 5 (space separated), that can be reversed to list using map(int, input().split())
Use the built-in max.
Do you want to limit yourself to 3 number arrays? if yes, use assertion.
That should be enough:
def findMax3(lst):
assert len(lst) == 3
lst.sort()
return max(lst)
lst = map(int, input().split())
print(findMax3(lst))
This is the corrected code:
def findMax3(lst):
y = lst[:]
y.sort()
return y[-1]
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I'd say findMax() would be a better name as this could find the maximum of lists of any length.
Bear in mind the following does the same thing:
lst = [int(x) for x in input().split()]
print(max(lst))
Put the numbers in a list, then use max() function to get the maximum value in a list, like this:
#create an empty numbers list
lst=[]
#loop for getting input numbers
for i in range(1,4):
try:
#here we get the input number
my_new_number=int(raw_input("Please input the number "+str(i)+"/3 :\n"))
except:
#in case of it is not a number raise an alert
print "not regular integer number"
#here we check that number not exist
if my_new_number not in lst:
#add the current input number to the list
lst.append(my_new_number)
else:
print "the number",my_new_number,"already exist in this list"
#show the maximum number of the list
print "The maximum number is",max(lst)
You might be interested in typing your list items one by one instead of using split() function to split your input. Also, to retrieve your list max, you have already a built-in max() function that you can use:
>>> num_list = []
>>>
>>> for i in range(3):
... num = input("Enter number {}: ".format(i + 1))
... num_list.append(int(num))
...
Enter number 1: 3
Enter number 2: 6
Enter number 3: 2
>>>
>>> max_num = max(num_list)
>>> print(max_num)
6
First off, Ebe Isaac gave a good explanation and you should look at his solution and understand why it works.
There's a few issues with your code.
lst = int(input())
print(findMax3())
You're inputting a list of numbers that need to be separated by some non-numeric character, so you cannot use int() on your input value.
lst = [int(x) for x in input().split()]
should give you what you want (with default separator being blank space). To learn more about this format, see list comprehensions.
Next, you call findMax3() but this function does not return a value so it will not have anything to print (see below). Additionally, it would be better to send it your list as an argument, this will save you from another line copying it later (see below).
lst = input().split()
print(findMax3(lst))
Now for your function:
def findMax3():
y = list(lst)
You should probably send an argument (the inputted list) to the function. This argument can be renamed whatever you put in the parentheses after the name of the function. You are using y here so we can rewrite it as:
def findMax3(y):
and delete the y = list(lst) line.
y.sort(lst)
When using a method or function, it's a good idea to look up the documentation to identify what arguments it takes. You'll see that sort can take two arguments (key and reverse) neither are needed here so we can fix this line by changing it to:
y.sort()
The next line:
y[0] == y[-1]
is a Boolean expression and returns either True or False if the first element of the sorted list (y[0]) is equal to the last element of the sorted list (y[-1]). To be honest, I'm not really sure what you were trying to do here. Since the function is designed to find the max value of the list, it needs to return that value so we need to use return(). The max value will be the last of the list so you can do:
return(y[-1])
So if you want to keep the flow of your original code, it can work by changing it to:
def findMax3(y):
y.sort()
return(y[-1])
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I hope this helps. Best of luck.
As many have mentioned, you need to let your function know what list to find the max of. To do that, you need to put the name of the list in the parameter list of the function i.e. findMax3(lst).
Your function will still not work because you are not returning anything from it. You need to use the return keyword followed by what to return in order to have the function give you a response. For example, return 1 will return the value of 1 to anyone who called this function. Using that example, you need to decide what to return to the caller.
My version of findMax3 without any other function calls:
def findMax3(*args):
max3 = args[0]
for n in args[1:3]:
if n > max3:
max3 = n
return max3
This is pretty close to what the built in max function will do given those same 3 inputs
If you already have a list then you can simply use the max function to get the highest number among 3 numbers in the list.
lst = [5, 2, 9]
print(max(lst))
# output
9
Or I assume you have three different numbers as input and then you can pass them to your desired method to get the highest number.
# function to get max among 3 integers
find_max(x, y, z):
return max([x, y, z])
# take input
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
num3 = int(input("enter num3: "))
# call your function
print(find_max(num1, num2, num3))
If we do not want to use the built in function for solving the problem we could always follow the below simple approach.
Using max() to find maximum of numbers is already shown in above few solutions.
Posting a sample solution without use of max()
num1=51
num2=6
num3=72
def find_max(num1,num2,num3):
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
return largest
print(find_max(num1,num2,num3))

How to convert str in a list to int without using int() in Python

The question is pretty straightforward. Sorry I am very new to this. I'm not allowed to use int().
The algorithm you are looking for is:
initialise number to 0
for each character in str
multiply number by 10
find number of character (ascii value, avaiable from ord(), - 48 is simplest)
add character number to number
Of course, you should check that the string is actually all numbers first.
Here is how to do it for binary (base2) numbers:
>>> bin(12)
'0b1100'
>>> sum([2**i * (ord(ch)-ord('0')) for i, ch in enumerate(reversed('1100'))])
12
Here is a nice, Pythonic way of doing it.
def str_to_int(s):
if type(s) != str:
raise TypeError("invalid type for str_to_int: {}".format(type(s)))
if not s.isdigit():
raise ValueError("invalid literal for str_to_int: '{}'".format(s))
return sum((ord(char) - 48) * 10**(len(s) - n) for n, char in enumerate(s, start=1))
If you don't care about checking the argument to make sure it's a string and contains only digits, then it can be reduced down to the following one-liner:
str_to_int = lambda s: sum((ord(char) - 48) * 10**(len(s) - n) for n, char in enumerate(s, start=1))
This answer depends on the numbers' ASCII values being in sequential order. You want to simply reverse the string, then turn each digit to an int and add it's weighted value to the string. So, if your number is "12345", your first addend would be 5*1, or 5. Your second would be 4*10 or 40. Keep adding them and multiplying your weight by 10 until you reach the end of the string, and you are done!
def str_to_int(string):
if not string.isdigit():
raise ValueError("String must be a digit")
weight = 1
ans = 0
for c in reversed(string):
i = ord(c) - ord('0')
ans = ans + i*weight
weight = weight * 10
return ans
If you can do it for one string, you can do it for all strings! Either use a for loop or the handy map function:
l = ["12312" , '32355']
print(list(map(str_to_int, l)))
print([str_to_int(i) for i in l])

Categories