max() arg is an empty sequence in max(listname) - python-3.x

I have written a program which accepts a list of numbers and returns the largest number possible by concatenating the list of numbers in Python. But when I execute the code I get following error message ValueError: max() arg is an empty sequence. Here is my code:
def create_largest_number(number_list):
l=list()
m=max(number_list)
while(number_list!=0):
m=max(number_list)
l.append(m)
number_list.remove(m)
return l
number_list=[23,45,67]
largest_number=create_largest_number(number_list)
print(largest_number)
Sample Input: 23,34,55
Sample Output: 554323

number_list!=0 is always going to be true because number_list is a list, not a number, so while number_list != 0 is an infinite loop, and given that you're removing items from the list on each iteration, the list will eventually become empty. Yet it'll never become zero, so on the next iteration your code will attempt to calculate max(number_list) == max([]), which is an error.
You can solve it this way:
while number_list: # a.k.a. `while len(number_list) > 0:`

Related

Palindrome problem - Trying to check 2 lists for equality python3.9

I'm writing a program to check if a given user input is a palindrome or not. if it is the program should print "Yes", if not "no". I realize that this program is entirely too complex since I actually only needed to check the whole word using the reversed() function, but I ended up making it quite complex by splitting the word into two lists and then checking the lists against each other.
Despite that, I'm not clear why the last conditional isn't returning the expected "Yes" when I pass it "racecar" as an input. When I print the lists in line 23 and 24, I get two lists that are identical, but then when I compare them in the conditional, I always get "No" meaning they are not equal to each other. can anyone explain why this is? I've tried to convert the lists to strings but no luck.
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
Despite your comments first_half and second_half are substrings of your input, not lists. When you print them out, you're converting them to lists, but in the comparison, you do not convert first_half or reversed(second_half). Thus you are comparing a string to an iterator (returned by reversed), which will always be false.
So a basic fix is to do the conversion for the if, just like you did when printing the lists out:
if list(first_half) == list(reversed(second_half)):
A better fix might be to compare as strings, by making one of the slices use a step of -1, so you don't need to use reversed. Try second_half = the_string[-1:x//2:-1] (or similar, you probably need to tweak either the even or odd case by one). Or you could use the "alien smiley" slice to reverse the string after you slice it out of the input: second_half = second_half[::-1].
There are a few other oddities in your code, like your for i in range(x) loop that overwrites all of its results except the last one. Just use x - 1 in the slicing code and you don't need that loop at all. You're also calling int a lot more often than you need to (if you used // instead of /, you could get rid of literally all of the int calls).

Program not breaking

Could anyone provide insight into why my program keeps terminating when I am trying to break?
Below is the prompt:
Write a function that returns a list of numbers, say make_list. make_list will not take any arguments. In the function body, construct an empty list and then prompt the user to enter a nonnegative number, -999 to quit. You will need a loop. If the user enters a number other than -999, add it to the list. Once the user enters -999, quit the loop and return the list. (Do not include -999 in the list.)
Write another function, say sum_list, that takes a list of numbers as an argument and returns the sum of the list of numbers. If the list is empty return 0. Do not use the built-in sum function. Use a loop.
You need to call both functions. First call the make_list function. Then use the returned list as the argument for the sum_list function. Print the result.
My solution:
def make_list():
i=[]
while(True):
n=int(input("Enter a number (-999 to quit): "))
if n==-999:
break
i+=[n]
return i
def sum_list(i):
if len(1)==0:
return 0
sum1=0
for k in i:
sum1+=k
return sum1
i=make_list()
s=sum_list(i)
print("Sum :", s)

Why is there no IndexError thrown when length of list is smaller than the index used in return statement?

Here is the python code:
#!/usr/bin/python3
def top_three_new(input_list):
return sorted(input_list, reverse=True)[:100]
print(top_three_new([2, 1]))
[:100] does not mean that it will return exactly the 100th element.
[:n] returns the n items from last. If there is less than n items it simply returns all.

Error: maximum recursion depth exceeded in comparison

I am trying to find a character in an alphabetized string... Here is the code
def isIn(char, aStr):
middleChar = len(aStr)//2
if char == aStr[middleChar]:
return True
elif char < aStr[middleChar]:
LowerHalf = aStr[:middleChar]
return isIn(char, LowerHalf)
elif char > aStr[middleChar]:
UpperHalf = aStr[middleChar:]
return isIn(char, UpperHalf)
else:
return False
print(isIn('a', 'abc'))
It returns True. But When I put
print(isIn('d', 'abc'))
it returns this error: maximum recursion depth exceeded in comparison; instead of False.
I don't understand whats wrong. Please tell me where is the logical mistake I am doing.
With d, The program splits the string from abc and picks out UpperHalf bc. Then it searches the new string bc. It then returns 'c' from 'bc' as expected. Since d > c, the program goes chooses that condition and once again returns the upper half of string 'c', which is c. Hence the recursion. To fix this, you need a separate way of handling length 1 strings.
The last else is useless - it will never be executed.
The end of binary search is when the array becomes of one item - if this item isn't the searched one, the searched item isn't in the array.

recursion not stopping with 'if'

I am trying to write a code which prints True if given string has at max 2 consecutive c, and at max 1 b. I am using recursion to reduce the string and check that at max 'c' is present in the same index twice.But my recursion is not stopping till it empties the whole list. Can you please suggest what's wrong with my code. Thanks!
def stringcond(N,count=0,k=0):
N=list(N)
if(N.count('b')>1):
return False
if len(N)<2:
return True
else:
for i,j in enumerate(N):
if(j=='c'):
del N[i]
count+=1
if(k==i and count>2):
return False
stringcond(N,count=count,k=i)
return True
You have several mistakes. First, why are you splitting the characters into a list? There is a perfectly good count method for strings.
Your recursion fails because you ignore the return value. You would want something like
if not stringcond(N,count=count,k=i):
return False
# I make no claim that this logic is correct.
In any case, there is no need to recur. Use count to check the quantity of "b" and many-'c' substrings:
def stringcond(s, c_max=0):
return s.count('b') <= 1 and \
s.count("c" * (c_max+1)) == 0
You have to use the result of the stringcond call. Now your function will only return whatever was determined on the top level call.

Resources