I'm trying to write a function that returns the highest and lowest number in a list.
def high_and_low(numbers):
return max(numbers), min(numbers)
print(high_and_low("1 2 8 4 5"))
But I have this result:
('8', ' ')
Why do I have ' ' as a lowest number?
You are passing string to a function. In order to achieve the desired result, you need to split the string and then type-cast each element to int. Then only your min and max function will work expectedly. For example:
def high_and_low(numbers):
# split numbers based on space v
numbers = [int(x) for x in numbers.split()]
# ^ type-cast each element to `int`
return max(numbers), min(numbers)
Sample Run:
>>> high_and_low("1 2 8 4 5")
(8, 1)
Currently your code is finding the minimum and maximum value based on lexicographical order of the characters.
In order to achieve your desired result you can call split() on the string you are passing in. This essentially creates a list() of your input string—which you can call the min() and max() functions on.
def high_and_low(numbers: str):
"""
Given a string of characters, ignore and split on
the space ' ' character and return the min(), max()
:param numbers: input str of characters
:return: the minimum and maximum *character* values as a tuple
"""
return max(numbers.split(' ')), min(numbers.split(' '))
As others have pointed out you can also pass in a list of values you'd like to compare and can call the min and max functions on that directly.
def high_and_low_of_list(numbers: list):
"""
Given a list of values, return the max() and
min()
:param numbers: a list of values to be compared
:return: the min() and max() *integer* values within the list as a tuple
"""
return min(numbers), max(numbers)
Your original functions does technically work, however, it is comparing numerical values for each character and not just the integer values.
Another (faster) way using mapping:
def high_and_low(numbers: str):
#split function below will use space (' ') as separator
numbers = list(map(int,numbers.split()))
return max(numbers),min(numbers)
You can split your string by ' ' and pass it as Array
def high_and_low(numbers):
# split string by space character
numbers = numbers.split(" ")
# convert string array to int, also making list from them
numbers = list(map(int, numbers))
return max(numbers), min(numbers)
print(high_and_low("1 2 10 4 5"))
use numbers_list=[int(x) for x in numbers.split()] and use numbers_list in min() and max().
split() turns '1 23 4 5' into ['1','23','4','5']; and by using a list comprehension all the strings get converted to integers.
Related
Given a string of the form "3,9,13,4,42". It is necessary to convert it into a list and calculate its square for each element. Then join the squares of those elements back into a string and print it in the console.
input
input:
string = "3,9,13,4,42"
output:
string= "9,81,169,16,1764"
Managed to get it squared up, tried converting it to list fist, but when checked type at the end, always somehow getting it as tuple.
Ty for help.
Hope this answers your question.
# input
str_numbers = "3,9,13,4,42"
# string to list
str_number_list = str_numbers.split(",")
# list of strings to list of ints
number_list = [int(x) for x in str_number_list]
# square all numbers
squared_numbers = [x ** 2 for x in number_list]
# squared numbers back to a list of strings
str_squared_numbers = [str(x) for x in squared_numbers]
# joing the list items into one string
result = ",".join(str_squared_numbers)
# print it out
print(f"Input: {str_numbers}")
print(f"Output: {result}")
// First Approach
string = "3,9,13,4,42"
array = string.split(',')
array = map(lambda x: str(int(x)**2),array)
result = ','.join(list(array))
print(result) // "9,81,169,16,1764"
// Second Approach
string = "3,9,13,4,42"
result = ','.join([str(int(x)**2) for x in string.split(',')])
print(result) // '9,81,169,16,1764'
Can do with split + join,
In [1]: ','.join(map(lambda x: str(int(x)**2), s.split(',')))
Out[1]: '9,81,169,16,1764'
You have so many ways to solve the problem. I'll show you a few by degree of complexity of understanding. Each way has a different computational complexity, but for such a problem we will not go into detail.
N.B.: Casting should be done at float and not at int because it is not certain a priori that there are integers in the input string.
Using List Comprehension
List comprehension offers a shorter syntax when you want to create a
new list based on the values of an existing list.
I divide the code into 3 steps just for greater understanding:
input_string = "3,9,13,4,42"
num_list = [float(x) for x in input_string.split(",")] # split list by comma and cast each element to float
squares_list = [x**2 for x in num_list] # make square of each number in list
output_string = [str(x) for x in squares_list] # cast to string each element in list
print(output_string)
Using join, map and lambda
The join() method takes all items in an iterable and joins them into
one string.
The map() function applies a given function to each item of an
iterable (list, tuple etc.) and returns an iterator.
A Lambda Function is an anonymous function, that is, a function that
has not been assigned a name and is used to use the features of
functions but without having to define them.
output_string = ','.join(map(lambda x: str(float(x)**2), input_string.split(',')))
You are absolutely right assume-irrational-is-rational
string = "3,9,13,4,42"
def squares_string(string):
output = ",".join(tuple(map(lambda x: str(int(x)**2), "3,9,13,4,42".split(","))))
return output
output = squares_string(string)
print(output)
print(type(output))
Result:
9,81,169,16,1764
<class 'str'>
randomgenerator() is a function that yields 6 random integers, the user is prompted to also enter 6 values which are added to lucky[].
I want to compare each yield value to the lucky[] list for a match, but the if condition is not being met.
for x in randomgenerator():
print(f"\n{x} is a winning number.")
if x in lucky:
print(f"There is a match with number {x}")
match.append(x)
def randomgenerator():
for i in range(5):
yield random.randint(1,2)
yield random.randint(1,2)
You said randomgenerator returns a tuple containing ints.
randomgenerator() is a function that yields 6 random values
I guess by "values" you meant integers, since it's very strange to generate random strings.
Then lucky is filled with input() returned values, which are strings.
if str(x) in lucky: # This should work, since it will convert the int x to a string
a similar solution would be:
lucky = list(map(int, lucky)) # all the elements are converted to integers
Today i'll publish a riddle.
The best answer will be the shortest code.
Write a one liner function that accepts a currency and a list of numbers. The function needs to return a string where each number from the list is attached with its currency.
Here's an example for a simple way to solve it.
def combine_coin(coin, numbers):
coins_str = ''
for num in numbers:
coins_str += coin + str(num) + ', '
return coins_str[:-2]
print(combine_coin('$', range(5)))
def combine_coin(coin, numbers):
return ', '.join([f'{coin}{k}' for k in numbers])
print(','.join(list(map(lambda num:"$"+num,input("enter the values <sep by space>").split()))))
Okay splitting this long line, we get 1)
','.join(list( - this will join the list we get with a comma
2)map- maps a function to all values in a list and returns a map object containing the return value of the function
3)lambda num:'$'+str(num) - takes a number and returns its string with a '$' example: '$1'
4)input().split()- splits the input by space
Codegolf is fun:
def combine_coin(c, n):
return ', '.join(c+str(k) for k in n)
This question already has answers here:
How to sort a list of strings numerically?
(14 answers)
Closed 2 years ago.
I made a program to calculate the second largest number from a list. Input is a string that is sliced into a list. Here's the code
score1 = input()
score = score1.split()
score.sort()
maximum = max(score)
count = score.count(maximum)
for i in range(0,count):
score.pop()
print(max(score))
And it is working fine for positive numbers but if the list contains a negative number my program fails to produce the correct answer.
For Input -7 -7 -7 -7 -6
Output is -6 instead of -7
Any way to improve it?
Since the input is a string, when you call sort and max they're working lexicographically, not numerically. You need to convert to integers first:
score = [int(item) for item in score1.split()]
The reason your code does not work for negative numbers (btw it also does not work for numbers with more than 1 digits as well) is that you are not sorting numbers, you are sorting strings. input()'s return value is always a string since no implicit conversion takes place. Therefore, in order to get the result you want you have to cast them to some number form first.
score = [int(x) for x in input().split()]
score.sort()
after that you can do whatever you want with it.
Note that wrapping the list-comprehension in a try-except block would also be a good idea to avoid bad input.
score1 = input()
score = score1.split()
#converting the list of strings into list of integers
score = [int(i) for i in score]
#removing duplicates
score = list(set(score))
#sorting the list
score.sort()
#printing the second largest number
print(score[-2])
You can get your expected answer by doing this :
score = input().split()
li = []
for value in score:
x = int(value) # converting to int
li.append(x) # appending to empty list
final = set(li) # removing duplicates values
print(max(final)) # getting the maximum value
Hope that it will help you ..
Try this maybe:
score1 = input()
score = score1.split()
score = sorted(set(map(int, score)))
second_max=score[-2]
two fixes:, main should sort the returned list, and the for loop should print all numbers on one line.
This is the question I am answering, Thought I got it all but the two errors I have explained above need help:
In main, generate a random integer that is greater than 5 and less than 13. print this number on its own line.
Call the makelist function with the random integer as sole argument.
Make an empty list inside the makelist function.
Use a loop to append to the list a number of elements equal to the random integer argument. All new list elements must be random integers ranging from 1 to 100, inclusive. Duplicates are okay.
Return the list to main.
Back in main, catch the returned list and sort it.
Finally, use a for loop to display the sorted list elements, all on one line, separated by single spaces.
List size will be 7
Here is the sorted list:
8 28 35 41 51 62 72
ANOTHER SAMPLE OUTPUT
List size will be 10
Here is the sorted list:
3 3 9 20 36 43 48 50 81 93
Any help with my code is very much appreciated. Im a beginner and have tried tutorials.
Here is my code
import random
def main():
random_int = random.randint(6, 12)
print (random_int)
elements = makelist(random_int)
for n in sorted(elements):
print (n,)
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 101))
return number_list
main()
print (n,) if you want to print your items like your samples output, Your comma placement is where the problem lies. You see, parenthesis in python are used both for enclosing mathematical / logical expressions and for tuples. What happens if you want a 1-item tuple? (n) is the same as n. To solve that, python understands (n,)as a tuple.
So to print your items like you want, use:
for n in sorted(elements):
print (n),
print() # This last one is only to go down a line
# for any further prints
Edit: also, if you want a random_intbetween 1 and 100, use random.randint(1, 100), not 101
I would sort the list in the makelist function. In addition to this, you should remove the comma from print (n,). Otherwise your code pretty much solves the problem. Just be more specific with your question next time.
Edit: Calling each print() on each element on the list will print each element on a newline (Vertically). Since you needed to get rid of the commas, ' '.join(map(str, sorted(elements)) will convert the list to a string, with each element separated by an empty space.
import random
def main():
random_int = random.randint(6, 12)
print ("The list size will be %d" %random_int)
elements = makelist(random_int)
print("This sorted list is %s" %' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list
Do it like this
import random
def main():
random_int = random.randint(6, 12)
print ('List size will be %d' % random_int)
elements = makelist(random_int)
print('Here is the sorted list:')
print( ' '.join(map(str, sorted(elements))) )
def makelist(random_int):
number_list = []
for count in range(random_int):
number_list.append(random.randint(1, 100))
return number_list
main()
The line of interest is
print( ' '.join(map(str, sorted(elements))) )
Which does a few things.
sorted(elements)
Return a sorted copy of the list.
map(str, sorted(elements))
Map (convert) the integer elements to strings. This just calls str on each element in the list. Its needed because join requires an iterable of strings.
' '.join(map(str, sorted(elements)))
This funny looking syntax will create one long string out of all the values. It will use ' ' (space character) as the value between each element and will join all the elements which have been sorted and converted to strings into one long string which can be printed.